<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>
      </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>
  </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 loading = ref(false)

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 (!baseInfo || !requirement) return Snackbar.warning('请将信息填写完整')
  
  submitParams = Object.assign(baseInfo, requirement, { currency_type: 0 }) // currency_type: 写死0（人民币）
  if (route.query && route.query.id) submitParams.id = route.query.id // 有id则为编辑

  if (!baseInfo.hirePrice) return Snackbar.warning('请填写点数！')
  saveEmit(submitParams) // 正常发布，到列表中发起支付（暂定解决方案）
}

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

// 获取编辑的职位详情
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 = {}
  router.push({ path: '/recruit/enterprise/hirePosition' })
  // 新增职位发布需更新账户信息
  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>
