<template>
  <div>
    <v-card class="pa-5">
      <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 desc">{{ val.desc }}</div>
            <component :is="val.path" :ref="val.ref" :itemData="itemData"></component>
          </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'

// 添加只为之后是否需要额外操作
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: '#00897B',
    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
  }
]


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.expireTime && !baseInfo.soFar) {
    Snackbar.warning('请选择职位过期时间')
    window.scrollTo({ top: 0, behavior: 'smooth' })
    return
  }
  // if (!requirement?.areaId) return Snackbar.warning('请选择工作城市')
  if (!baseInfo || !requirement) return Snackbar.warning('请将信息填写完整')
  
  submitParams = Object.assign(baseInfo, requirement, { currency_type: 0, source: props.isFair ? '2' : '0', bizId: props.isFair ? route.params.id : null }) // currency_type: 写死0（人民币）  source: 0职位管理|1招聘会
  console.log('submitParams', submitParams)
  if (route.query && route.query.id) submitParams.id = route.query.id // 有id则为编辑
  if (props.valid) {
    const { valid } = await props.valid()
    if (!valid) {
      return
    }
  }
  saveEmit()
}

const saveEmit = async () => {
  loading.value = true
  try {
    const res = await saveJobAdvertised({ ...submitParams, fair: props.isFair ? true : false }) // fair：是否为招聘会职位编辑-必填
    // 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
    }
    if (props.afterAdd) {
      await props.afterAdd(res)
      return
    }
    Snackbar.success(submitParams.id ? t('common.editSuccessMsg') : '发布成功')
    handleCancel()
  } catch (error) {
    console.log('error', error)
    // 可发布职位额度不足时，将status设为99重新提交
    if (error === '企业额度已超过') {
      submitParams.status = '99'
      saveEmit()
    }
  } 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 getPositionDetail = async (id) => {
  const data = await getJobDetails({ id })
  if (!data && !Object.keys(data).length) return
  itemData.value = {...data, ...dealDictObjData({}, data)}
}

// 有id为编辑
if (route.query && route.query.id) {
  if (route.query.id) getPositionDetail(route.query.id)
}

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

<style scoped lang="scss">
.desc {
  font-size: 13px;
  color: var(--color-666);
}
</style>

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