<template>
  <div class="mt-10">
    <CtForm ref="formPageRef" :items="items" style="width: 650px;">
      <template #numericalValue>
        <div class="font-size-14 color-error my-1">
          <div class="d-flex align-center font-size-13">
          <div style="color: var(--v-error-base); cursor: pointer; text-decoration: underline;" @click="handleViewRule">
            <v-icon size="20" color="error">mdi-help-circle-outline</v-icon>
            众聘岗位规则说明。
          </div>
          <div class=" ml-5" style="color: var(--v-error-base);">
            众聘岗位分配比例：推荐人占比{{ ratio.recommendRate }}%&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 平台占比{{ ratio.headhuntRate }}%&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 投递人占比{{ ratio.cvRate }}%
          </div>
        </div>
          <div class="d-flex">
            按众聘岗位分配比例计算后的赏金： 
            <span class="calculation ml-3">推荐人{{ calculation('hirePrice', 1, true) }}元</span>
            <span class="calculation">平台{{ calculation('hirePrice', 0, true) }}元</span>
            <span class="calculation">投递人{{ calculation('hirePrice', 2, true) }}元</span>
          </div>
        </div>
      </template>
      <template #positionId="{ item }">
        <v-menu :close-delay="1" :open-delay="0" v-bind="$attrs">
          <template v-slot:activator="{  props }">
            <textUI
              :modelValue="item.value"
              :item="item"
              v-bind="props"
              style="position: relative;"
            ></textUI>
          </template>
          <jobTypeCard class="jobTypeCardBox" :select="[query.positionId].filter(Boolean)" :isSingle="true" @handleJobClick="handleJobClickItem"></jobTypeCard>
        </v-menu>
        <v-btn v-if="showTemplateBtn" class="ml-3 half-button" color="primary" style="margin-top: 2px;" @click="useJobTemplate(item)">职位模板</v-btn>
      </template>
    </CtForm>

    <CtDialog :visible="show" :widthType="1" titleClass="text-h6" title="众聘岗位规则说明" :footer="false" @close="show = false">
      <RulePage />
    </CtDialog>
  </div>
</template>

<script setup>
defineOptions({ name: 'position-add-baseInfo'})
import CtForm from '@/components/CtForm'
import { reactive, ref, watch } from 'vue'
import textUI from '@/components/FormUI/TextInput'
import jobTypeCard from '@/components/jobTypeCard'
import RulePage from './rule.vue'
import { commissionCalculation } from '@/utils/position'
import { getPublicRatio, getRecruitPositionDetails } from '@/api/recruit/enterprise/position'

const props = defineProps({
  itemData: Object
})

const showTemplateBtn = ref(true)
const show = ref(false)
const ratio = ref({})

// 按分配比例计算金额积分
const calculation = (key, type) => {
  const value = items.value.options.find(e => e.key === key).value
  return commissionCalculation(value, type)
}

const getValue = (key) => {
  return items.value.options.find(e => e.key === key)
}
const formPageRef = ref()
let query = reactive({})

const items = ref({
  options: [
    {
      type: 'number',
      key: 'hirePrice',
      value: null,
      label: '请填写点数 * （1赏金=10点数，点数填入不得少于10且为10的倍数）',
      suffix: '点',
      hideDetails: true,
      change: val => hirePriceChange(val, 'hirePrice')
    },
    {
      slotName: 'numericalValue',
      noParam: true,
    },
    {
      type: 'text',
      key: 'name',
      value: '',
      label: '职位名称 *',
      rules: [v => !!v || '请填写职位名称']
    },
    {
      type: 'datePicker',
      key: 'expireTime',
      value: null,
      format: 'YYYY-MM-DD',
      labelWidth: 120,
      label: '到期时间 *'
    },
    {
      slotName: 'positionId',
      key: 'positionId',
      value: '',
      labelKey: 'positionName',
      label: '职位类型 *',
      noParam: true,
      flexStyle: 'mt-5',
      readonly: true,
      rules: [v => !!v || '请选择职位类型']
    },
    {
      type: 'wangEditor',
      key: 'content',
      value: '',
      label: '岗位职责 *',
      maxLength: 5000,
      rules: '请填写岗位职责'
    },
    {
      type: 'wangEditor',
      key: 'requirement',
      value: '',
      label: '岗位要求 *',
      maxLength: 5000,
      rules: '请填写岗位要求'
    }
  ]
})


// 获取众聘分配比例
const getRatio = async () => {
  const data = await getPublicRatio()
  ratio.value = data
}
getRatio()

// 编辑回显
watch(
  () => props.itemData,
  (val) => {
    if (!Object.keys(val).length) return
    items.value.options.forEach(e => {
      if (e.labelKey) {
        query[e.key] = val[e.key]
        e.value = val[e.labelKey]
        return
      }
      if (e.noParam) return
      e.value = val[e.key]
      e.change && e.change(e.value)
    })
  },
  { immediate: true },
  { deep: true }
)

// 职位类型
const handleJobClickItem = (list, name) => {
  const positionId = getValue('positionId')
  if (!list.length) {
    delete query.positionId
    positionId.value = ''
    return
  }
  showTemplateBtn.value = true
  query.positionId = list[0]
  positionId.value = name
}

// 职位模板
import Confirm from '@/plugins/confirm'
import Snackbar from '@/plugins/snackbar'
import { useI18n } from '@/hooks/web/useI18n'; const { t } = useI18n()
const useJobTemplate = async () => {
  if (!query.positionId) return Snackbar.warning('请先选择职位类型')
  // 获取职位模板内容-赋值
  const res = await getRecruitPositionDetails(query.positionId)
  if (!res || !res.content || !res.requirement) {
    Snackbar.warning('此职位类型没有可使用的模板！')
    showTemplateBtn.value = false
    return
  }
  const content =  items.value.options.find(e => e.key === 'content')
  const requirement =  items.value.options.find(e => e.key === 'requirement')
  if ((content && content.value) || (requirement && requirement.value)) {
    // 弹窗提示
    Confirm(t('common.confirmTitle'), '您确定要放弃目前岗位描述的内容吗？').then(() => {
      content.value = res.content
      requirement.value = res.requirement
      Snackbar.success('模板填充完成！')
    })
  } else {
    // 无内容点击默认填充
    if (content) content.value = res.content
    if (requirement) requirement.value = res.requirement
    Snackbar.success('模板填充完成！')
  }
}

// 众聘规则查看
const handleViewRule = () => {
  show.value = true
}

// 众聘规则查看
const hirePriceChange = (value, key) => {
  let calcCost = value-0
  if (calcCost < 10 ) calcCost = 10
  else {
    calcCost = parseInt(calcCost/10)*10
  }
  const obj = items.value.options.find(k => k.key === key)
  if (obj) {
    obj.value = calcCost
  }
}

const getQuery = async () => {
  const { valid } = await formPageRef.value.formRef.validate()
  if (!valid) return
  const obj = {
    hire: true
  }
  items.value.options.forEach(e => {
    if (e.noParam) return
    else obj[e.key] = e.value
  })
  if (!obj.content) {
    Snackbar.warning('请填写岗位职责')
    return 'failed'
  }
  if (!obj.requirement) {
    Snackbar.warning('请填写岗位要求')
    return 'failed'
  }
  
  query = Object.assign(query, obj)
  return query
}

defineExpose({
  formPageRef,
  getQuery
})
</script>

<style scoped lang="scss">
.jobTypeCardBox {
  position: absolute;
  top: -22px;
  left: 0;
}
.calculation {
  display: block;
  width: 120px;
}
</style>
