<template>
  <view v-if="show" class="ss-m-x-20 ss-p-b-100">
    <uni-section 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 class="ss-m-y-20" title="岗位要求">
      <template v-slot:decoration>
        <view class="decoration decoration2">2</view>
      </template>
      <!-- 岗位要求 -->
      <requirement ref="requirementRef" :data="itemData"></requirement>
    </uni-section>
    <!-- <template v-if="isStudent">
      <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 ref="payRef" :tabBar="false" @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,
  fairId: String,
})

const jobId = ref('')
onLoad((options) => {
  jobId.value = options?.jobId || props.jobId || ''
  if (jobId.value) getPositionDetail(jobId.value)
  else {
    show.value = true
  }
})

// 获取编辑的职位详情
const show = ref(false)
const itemData = ref({})
const getPositionDetail = async (id) => {
  try {
    uni.showLoading({ title: '加载中...', mask: true })
    const res = await getJobDetails({ id })
    if (!res?.data || !Object.keys(res.data).length) return
    itemData.value = {...res.data, ...dealDictObjData({}, res.data)}
    // itemData.value.name = new Date().getTime().toString() + '测试小程序发布职位'
    // if (itemData.value?.type === '3') {
    //   await getPositionExtendDetail(id)
    // }
    show.value = true
  } finally {
    uni.hideLoading()
  }
}
// // 测试数据
// setTimeout(async() => {
//   show.value = false
//   await getPositionDetail('1904786675108691969')
// }, 2000)

// 获取实习扩展信息
// const extendData = ref({})
// const getPositionExtendDetail = async (id) => {
//   try {
//     const res = await getJobAdvertisedExtend(id)
//     extendData.value = res?.data || {}
//     isStudent.value = true
//   } catch (error) {
//   }
// }

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

  // if (cleanedHtml(baseInfo.content)?.length > 5000) return uni.showToast({ title: '岗位职责字数超出限制', icon: 'none', duration: 2000 })
  // if (cleanedHtml(baseInfo.requirement)?.length > 5000) return uni.showToast({ title: '岗位要求字数超出限制', icon: 'none', duration: 2000 })
  
  submitParams = {
    ...baseInfo,
    ...requirement,
    fair: props.fairId ? true : false, // fair：是否为招聘会职位编辑-必填
    currency_type: 0, // currency_type: 写死0（人民币）
    source: props.fairId ? '2' : '0', // source: 职位来源(0职位管理|1众聘职位|2招聘会)
  }
  if (props.fairId) submitParams.bizId = props.fairId // 招聘会职位添加招聘会id
  
  if (!submitParams.salary) {
    if (!submitParams.payFrom) return uni.showToast({ title: '请填写最低薪资', icon: 'none', duration: 2000 })
    if (!submitParams.payTo) return uni.showToast({ title: '请填写最高薪资', icon: 'none', duration: 2000 })
  }
  
  if (jobId.value) submitParams.id = jobId.value  // 有id则为编辑
  saveEmit()
}
// 
const price = 39900 // 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') {
      uni.showToast({ title: '当前可发布职位额度不足，请支付', icon: 'none', duration: 2000 })
      nextTick(() => {
        // 金额*100，页面展示/100
        payRef.value && payRef.value.handleOpen({ spuId: _jobId||'', spuName: submitParams?.name||'', price, type: 1 })
      })
      return
    }
    if (!props.fairId) uni.switchTab({ url: '/pages/index/position' })
    else {
      uni.reLaunch({
        url: `/pagesB/jobFair/details?id=${props.fairId}`
      })
    }
    // const title = itemData.value?.status === '99' '编辑成功，请前往支付' : jobId.value ? '编辑成功' : '发布成功'
    setTimeout(() => { uni.showToast({ title: jobId.value ? '编辑成功' : '发布成功', icon: 'success' }) }, 1000)

  } catch (error) {
    console.log('error:', error)
    // 可发布职位额度不足时，将status设为99重新提交
    if (error?.msg === '企业额度已超过') {
      submitParams.status = '99'
      setTimeout(() => {
        if (!retry) saveEmit(true) // true：重新提交避免死循环
      }, 1000)
    }
    // else if (error?.msg === '招聘会时间已过,暂停招聘') {
    //   uni.showToast({ title: error.msg, icon: 'none', duration: 2000 })
    // }
  } finally {
    uni.hideLoading()
  }
}

const payRef = ref(null)
const paySuccess = () => {
  uni.switchTab({ url: '/pages/index/position' })
  setTimeout(() => { uni.showToast({ title: '发布成功', icon: 'success', duration: 2000 }) }, 1000)
}
const payClose = () => {
  setTimeout(() => { uni.showToast({ title: '您已取消支付，请前往待发布查看！', icon: 'none', duration: 3000 }) }, 500)
  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>