<template>
  <view class="ss-m-x-20 ss-p-b-100">
    <uni-section v-if="show" class="ss-m-y-20" title="职位基本信息">
      <template v-slot:decoration>
        <view class="decoration decoration1">1</view>
      </template>
      <!-- 基本信息 -->
      <baseInfo ref="baseInfoRef" :data="itemData"></baseInfo>
    </uni-section>
    <uni-section v-if="show" class="ss-m-y-20" title="岗位要求">
      <template v-slot:decoration>
        <view class="decoration decoration2">2</view>
      </template>
      <!-- 岗位要求 -->
      <requirement ref="requirementRef" :data="itemData" @requireTypeChange="bool => isStudent = bool"></requirement>
    </uni-section>
    <template v-if="isStudent && showExtend">
      <uni-section class="ss-m-y-20" title="其他">
        <template v-slot:decoration>
          <view class="decoration decoration3">3</view>
        </template>
        <!-- 扩展信息 -->
        <extendInfo ref="extendRef" :data="extendData"></extendInfo>
      </uni-section>
    </template>
    <view class="f-horizon-center">
      <button type="primary" size="default" class="send-button" @click="getSubmitParams">提 交</button>
    </view>
    <!-- 支付 -->
    <payPopup v-if="showPay" ref="payRef" :amount="amount" @paySuccess="paySuccess" @close="payClose"></payPopup>
  </view>
</template>

<script setup>
import baseInfo from './components/baseInfo.vue'
import requirement from './components/requirement.vue'
import extendInfo from './components/extend.vue'
import { ref, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import payPopup from '@/components/payPopup'
import { dealDictObjData } from '@/utils/position'
import {
  saveJobAdvertised,
  saveJobAdvertisedExtend,
  getJobDetails,
  getJobAdvertisedExtend,
} from '@/api/new/position'
const props = defineProps({
  jobId: String
})

let jobId = ''
let fairId = ''
onLoad((options) => {
  jobId = options?.jobId || props.jobId || ''
  fairId = options?.fairId || ''
  // console.log('jobId:', jobId); console.log('fairId:', fairId)
  if (jobId) getPositionDetail(jobId)
  else {
    show.value = showExtend.value = true
  }
})

// 获取编辑的职位详情
const show = ref(false)
const itemData = ref({})
const getPositionDetail = async (id) => {
  const res = await getJobDetails({ id })
  if (!res?.data && !Object.keys(res.data).length) return
  itemData.value = {...res.data, ...dealDictObjData({}, res.data)}
  show.value = true
  if (itemData.value?.type === '3') {
    isStudent.value = true
    getPositionExtendDetail(id)
  }
}
// getPositionDetail('1904154452278009858')

// 获取编辑的职位详情
const showExtend = ref(false)
const extendData = ref({})
const getPositionExtendDetail = async (jobId) => {
  const res = await getJobAdvertisedExtend(jobId)
  extendData.value = res?.data || {}
  showExtend.value = true
}

const baseInfoRef = ref(null)
const requirementRef = ref(null)
const extendRef = ref(null)
let submitParams = null
const getSubmitParams = async() => {
  const baseInfo = await baseInfoRef.value.getQuery()
  const requirement = await requirementRef.value.getQuery()
  if (!baseInfo || !requirement) return
  
  submitParams = {
    ...baseInfo,
    ...requirement,
    fair: Boolean(fairId), // fair：是否为招聘会职位编辑-必填
    currency_type: 0, // currency_type: 写死0（人民币）
    source: fairId ? '2' : '0', // source: 0职位管理|1招聘会
    bizId:  fairId ? fairId : null,
  }
  if (jobId) submitParams.id = jobId  // 有id则为编辑
  saveEmit()
}
// 
const price = 1 // 39900
const isStudent = ref(false)
let _jobId = ''
const saveEmit = async (retry) => {
  try {
    uni.showLoading({ title: '操作中...', mask: true })
    const res = await saveJobAdvertised(submitParams)
    _jobId = res?.data || res || ''
    if (isStudent.value) handleSaveExtend() // 保存扩展信息
    // status：99为待支付职位，弹窗支付
    if (submitParams?.status && submitParams?.status === '99') {
      showPay.value = true
      console.log('1payRef:', payRef.value)
      uni.showToast({ title: '当前可发布职位额度不足，请支付', icon: 'none', duration: 2000 })
      nextTick(() => {
        // 金额*100，页面展示/100
        console.log('2payRef:', payRef.value?.handleOpen)
        payRef.value && payRef.value.handleOpen({ spuId: _jobId||'', spuName: submitParams?.name||'', price, type: 1 })
      })
      return
    }
    uni.switchTab({ url: '/pages/index/position' })
    setTimeout(() => { uni.showToast({ title: '发布成功', icon: 'success' }) }, 1000)

  } catch (error) {
    console.log('error:', error)
    // 可发布职位额度不足时，将status设为99重新提交
    if (error?.msg === '企业额度已超过') {
      showPay.value = true
      submitParams.status = '99'
      setTimeout(() => {
        if (!retry) saveEmit(true) // true：重新提交避免死循环
      }, 1000)
    }
  } finally {
    uni.hideLoading()
  }
}

const payRef = ref(null)
const showPay = ref(false)
const paySuccess = () => {
  uni.switchTab({ url: '/pages/index/position' })
  setTimeout(() => { uni.showToast({ title: '发布成功', icon: 'success' }) }, 1000)
}
const payClose = () => {
  uni.switchTab({ url: '/pages/index/position' }) // 不支持传参
}

// 保存扩展信息
const handleSaveExtend = async () => {
  if (!_jobId) return
  try {
    const extend = await extendRef.value && extendRef.value.getQuery() || null
    if (!extend) return
    await saveJobAdvertisedExtend({ ...extend, jobId: _jobId })
  } catch (error) {
    console.error('保存扩展信息失败', error)
  }
}

</script>

<style scoped lang="scss">
.decoration {
  color: #fff;
  border-radius: 50%;
  width: 15px;
  height: 15px;
  line-height: 15px;
  font-size: 10px;
  text-align: center;
  margin-right: 4px;
}

.decoration1 {
  background-color: #00b760;
}

.decoration2 {
  background-color: #7a87c9;
}

.decoration3 {
  background-color: #1caaf2;
}
</style>