<template>
  <div>
    <v-card class="pa-5" v-if="show">
      <v-timeline align="start" side="end">
        <v-timeline-item
          v-for="(val, i) in list"
          :key="i"
          :dot-color="val.color"
          :icon="val.icon"
        >
          <div>
            <h2 class="mt-n1 headline font-weight-regular">{{ val.title }}</h2>
            <div class="mb-4 color-666 font-size-13">{{ val.desc }}</div>
            <component :is="val.path" :ref="val.ref" :isFair="props.isFair" :itemData="itemData"></component>
          </div>
        </v-timeline-item>
        <!-- <v-timeline-item v-if="showExtend" dot-color="light-blue darken-1" icon="mdi-numeric-3">
          <div>
            <h2 class="mt-n1 headline font-weight-regular">其他</h2>
            <CtForm ref="formPageRef" class="mt-3" :items="items" style="width: 650px;"></CtForm>
          </div>
        </v-timeline-item> -->
        <slot name="timeline"></slot>
      </v-timeline>
      <div class="text-center mb">
        <v-btn class="half-button mr-3" color="primary" variant="outlined" @click="handleCancel()">{{ $t('common.cancel') }}</v-btn>
        <v-btn class="half-button" color="primary" :loading="loading" @click="handleSave">{{ $t('common.release') }}</v-btn>
      </div>
    </v-card>

    <!-- 弹窗支付 -->
    <confirmPaymentDialog
      v-if="showConfirmPaymentDialog"
      :cost="payInfo.cost"
      :spuId="payInfo.spuId"
      :spuName="payInfo.spuName"
      :showEnterpriseJump="true"
      :showOriginalPrice="true"
      :orderType="1"
      @paySuccess="paySuccess"
      @close="handlePayClose"
    ></confirmPaymentDialog>
  </div>
</template>

<script setup>
defineOptions({ name: 'enterprise-position-add'})
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { dealDictObjData } from '@/utils/position'
import { saveJobAdvertised, getJobDetails } from '@/api/position'
import baseInfo from './baseInfo.vue'
import jobRequirements from './jobRequirements.vue'
import Snackbar from '@/plugins/snackbar'
import { useI18n } from '@/hooks/web/useI18n'
import { useUserStore } from '@/store/user'
import { createTradeOrder } from '@/api/position'
// import { saveJobAdvertisedExtend, getJobAdvertisedExtend } from '@/api/recruit/enterprise/jobFair'
// import { schoolMajorByName, schoolMajorById } from '@/api/recruit/personal/resume'

// 添加只为之后是否需要额外操作
const props = defineProps({
  afterAdd: Function,
  // valid: Function,
  isFair: Boolean
})

const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const baseInfoRef = ref()
const jobRequirementsRef = ref()
const loading = ref(false)
const itemData = ref({})
const showConfirmPaymentDialog = ref(false)
const payInfo = ref({})

const list = [
  {
    color: '#00B760',
    icon: 'mdi-numeric-1',
    title: t('position.positionInformation'),
    desc: '',
    path: baseInfo,
    ref: baseInfoRef
  },
  {
    color: 'indigo-lighten-2',
    icon: 'mdi-numeric-2',
    title: t('position.jobRequirements'),
    desc: t('position.requirementDesc'),
    path: jobRequirements,
    ref: jobRequirementsRef
  }
]

// const formPageRef = ref()
// const items = ref({
//   options: [
//     {
//       type: 'text',
//       key: 'dept',
//       value: null,
//       col: 6,
//       label: '招聘部门 '
//     },
//     {
//       type: 'autocomplete',
//       key: 'majorId',
//       search: getMajorList,
//       value: null,
//       label: '专业要求 ',
//       itemText: 'nameCn',
//       col: 6,
//       itemValue: 'id',
//       flexStyle: 'ml-3',
//       noDataText: '请输入检索专业',
//       items: []
//     },
//     {
//       type: 'autocomplete',
//       key: 'frequency-dateType',
//       value: null,
//       label: '工作频率 ',
//       col: 6,
//       items: [
//         { label: '每周', value: 'week' },
//         { label: '每月', value: 'month' },
//         { label: '每年', value: 'year' }
//       ]
//     },
//     {
//       type: 'number',
//       key: 'frequency-day',
//       value: null,
//       flexStyle: 'ml-3',
//       col: 6,
//       label: '出勤天数 '
//     }
//   ]
// })

// 是否展示扩展信息
// const showExtend = ref(false)
// const handleChangeType = (show) => {
//   console.log(show, '招聘类型是否为实习')
//   showExtend.value = show
//   if (!show) {
//     items.value.options.forEach(e => e.value = null)
//   }
// }
// console.log(route)

// async function initPosition (jobId) {
//   const res = await getJobAdvertisedExtend(jobId)
//   console.log(res, '获取扩展信息')
//   if (!res) return
//   items.value.options.forEach(e => {
//     if (e.key.includes('frequency') && res.frequency) {
//       const keys = e.key.split('-')
//       e.value = res[keys[0]][keys[1]]
//       return
//     }
//     if (e.key === 'majorId') {
//       getMajorById(res.majorId)
//     }
//     e.value = res[e.key]
//   })
//   showExtend.value = true
// }

// async function getMajorList (name) {
//   if (!name) {
//     return
//   }
//   const res = await schoolMajorByName({ name })
//   items.value.options.find(e => e.key === 'majorId').items = res
// }

// async function getMajorById (id) {
//   if (!id) return
//   const res = await schoolMajorById({ id })
//   items.value.options.find(e => e.key === 'majorId').items = [res]
// }

// 保存扩展信息
// const handleSaveExtend = async (jobId) => {
//   const query = items.value.options.reduce((r, v) => {
//     if (v.key.includes('frequency')) {
//       const keys = v.key.split('-')
//       if (!r[keys[0]]) {
//         r[keys[0]] = {}
//       }
//       r[keys[0]][keys[1]] = v.type === 'number' ? +v.value : v.value
//       return r
//     }
//     if (v.key === 'majorId') {
//       r.major = v.items.find(e => e.id === v.value)?.nameCn || ''
//     }
//     r[v.key] = v.type === 'number' ? +v.value : v.value
//     return r
//   }, { jobId })
//   console.log(query, 'extendInfo')
//   await saveJobAdvertisedExtend(query)
// }

let submitParams = {}
// 发布
const handleSave = async () => {
  const baseInfo = await baseInfoRef.value[0].getQuery()
  if (baseInfo === 'failed') return
  const requirement = await jobRequirementsRef.value[0].getQuery()
  if (!requirement) return Snackbar.warning('请按要求填写信息')
  if (!baseInfo || !requirement) return Snackbar.warning('请将信息填写完整')
  
  submitParams = Object.assign(baseInfo, requirement, { currency_type: 0 }) // currency_type: 写死0（人民币）  source: 0职位管理|1招聘会

  submitParams.source = props.isFair ? '2' : submitParams.source ? submitParams.source : '0'  // 职位来源(0职位管理|1众聘职位|2招聘会)
  // submitParams.bizId = props.isFair ? route.params.id : submitParams.bizId ? submitParams.bizId : null
  if (props.isFair) submitParams.bizId = route.params.id // 招聘会职位新增添加招聘会id

  if (route.query && route.query.id) submitParams.id = route.query.id // 有id则为编辑
  console.log('发布职位参数', submitParams, isClone.value)

  if (isClone.value) delete submitParams.id // 克隆职位删除id

  saveEmit()
}

const saveEmit = async (retry) => {
  loading.value = true
  try {
    const res = await saveJobAdvertised({ ...submitParams, fair: props.isFair ? true : false }) // fair：是否为招聘会职位编辑-必填
    // if (props.isFair) await handleSaveExtend(res) // 保存扩展信息

    // status：99为待支付职位，弹窗支付
    if (submitParams?.status && submitParams?.status === '99') {
      loading.value = true
      // 金额*100，页面展示/100
      await createTradeOrder({ spuId: res, spuName: submitParams.name, price: 39900, type: 1 }) // 普通职位type 1
      loading.value = false
      payInfo.value = { cost: 39900, spuId: res, spuName: submitParams.name }
      showConfirmPaymentDialog.value = true
      Snackbar.warning('当前可发布职位额度不足，请扫码支付')
      return
    }

    Snackbar.success(submitParams.id ? t('common.editSuccessMsg') : '发布成功')
    handleCancel()
  } catch (error) {
    console.log('error', error)
    // 可发布职位额度不足时，将status设为99重新提交
    if (error === '企业额度已超过') {
      submitParams.status = '99'
      if (!retry) saveEmit(true) // true：重新提交避免死循环
    }
  } finally {
    loading.value = false
  }
}

const paySuccess = async () => {
  showConfirmPaymentDialog.value = false
  if (props.afterAdd) {
    await props.afterAdd(payInfo.value.spuId)
    payInfo.value = {}
    return
  }
  payInfo.value = {}
  Snackbar.success(submitParams.id ? t('common.editSuccessMsg') : '发布成功')
  handleCancel()
}

const handlePayClose = () => {
  Snackbar.warning('您已取消支付')
  itemData.value = {}
  showConfirmPaymentDialog.value = false
  router.push({ path: '/recruit/enterprise/position', query: { key: 0 }})
}

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

  // 招聘类型为实习则获取扩展信息
  // if (data.type === '3') initPosition(id)
}

// 有id为编辑
if (route.query?.id) {
  // 是否为克隆职位
  isClone.value = route.query.clone === '1'
  getPositionDetail(route.query.id)
} else show.value = true

// 取消
const handleCancel = () => {
  itemData.value = {}
  const currentPage = router.currentRoute.value.path
  router.push({ path: currentPage.indexOf('jobFair') !== -1 ? `/recruit/enterprise/jobFair/details/${route.params.id}` : '/recruit/enterprise/position' })
  // 新增职位发布需更新账户信息
  if (route.query && !route.query?.id) {
    setTimeout(async () => {
      await userStore.getEnterpriseUserAccountInfo()
    }, 2000)
  }
}
</script>

<style scoped lang="scss">
.mb {
  margin-bottom: 100px;
}
</style>
