<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 class="mt-10" :is="val.path" :ref="val.ref" :itemData="itemData"></component>
          </div>
        </v-timeline-item>
      </v-timeline>
      <div class="text-center mb">
        <v-btn class="half-button mr-3" color="primary" variant="outlined" @click="handleCancel(itemData.hire)">{{ $t('common.cancel') }}</v-btn>
        <v-btn class="half-button" color="primary" @click="handleSave">{{ $t('common.release') }}</v-btn>
      </div>
    </v-card>
  </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, createTradeOrder } 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'

const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const baseInfoRef = ref()
const jobRequirementsRef = ref()
const itemData = 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()
  const requirement = await jobRequirementsRef.value[0].getQuery()
  if (!baseInfo || !requirement) return Snackbar.warning('请将信息填写完整')
  
  submitParams = Object.assign(baseInfo, requirement)
  if (route.query && route.query.id) submitParams.id = route.query.id // 有id则为编辑

  // 判断是否有选择众聘岗位，选择了是否有填赏金或积分
  if (!baseInfo?.hire) {
    saveEmit(submitParams)
  } else {
    if (!baseInfo.hirePrice && !baseInfo.hirePoint) return Snackbar.warning('您选择的是众聘岗位，请填写奖励赏金或积分！')
    if (Number(baseInfo.hirePrice) === 0 && Number(baseInfo.hirePoint) === 0) return Snackbar.warning('填写的赏金/积分不得小于1')
    
    const point = JSON.parse(localStorage.getItem('enterpriseUserAccount'))?.point
    if (Number(baseInfo.hirePoint) && (Number(baseInfo.hirePoint) > Number(point))) {
      // 积分不足
      return Snackbar.warning('您所剩的积分不足，请修改奖励的积分！')
    }
    saveEmit(submitParams) // 正常发布，到列表中发起支付（暂定解决方案）
    // needPrice.value = Number(baseInfo.hirePrice)
    // // 生成订单
  }
}

const saveEmit = async () => {
  try {
    const res = await saveJobAdvertised(submitParams)
    Snackbar.success(submitParams.id ? t('common.editSuccessMsg') : submitParams.hire ? t('common.publishSuccessMsg1') : t('common.publishSuccessMsg'))
    if (submitParams.hire) {
      // 生成订单
      await createTradeOrder({
        spuId: res,
        spuName: submitParams.name,
        price: submitParams.hirePrice,
        type: 2, // 发布众聘职位订单
      })
    }
    handleCancel(submitParams.hire)
  } catch (error) {
    console.log('error', error)
  }
}

// 获取编辑的职位详情
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)
}
// getPositionDetail('1821495780406075393') // 测试使用

// 取消
const handleCancel = (hire) => { //  hire：是否是众聘岗位
  itemData.value = {}
  router.push({ path: '/recruit/enterprise/position', query: { hire: hire ? 1 : 0 } })
  // 新增职位发布需更新账户信息
  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>
