<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :validate-on-rule-change="false"
    >
      <el-form-item label="奖励点数" prop="hirePrice">
        <el-input-number v-model="formData.hirePrice" :min="1" :step="5" />
        <div style="color: var(--el-color-danger)">
          <div>众聘岗位分配比例：推荐人占比{{ ratio.recommendRate }}%&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 平台占比{{ ratio.headhuntRate }}%&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 投递人占比{{ ratio.cvRate }}%</div>
          <div style="display: flex;">
            按众聘岗位分配比例计算后的赏金： 
            <span style="display: block; width: 120px;">推荐人{{ commissionCalculation(formData.hirePrice, 1, true) }}元</span>
            <span style="display: block; width: 120px;">平台{{ commissionCalculation(formData.hirePrice, 0, true) }}元</span>
            <span style="display: block; width: 120px;">投递人{{ commissionCalculation(formData.hirePrice, 2, true) }}元</span>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="职位类型" prop="positionId">
        <el-cascader v-model="formData.positionId" :options="position" :props="{ label: 'nameCn', value: 'id', emitPath: false }"  class="!w-240px" />
        <el-button v-if="showTemplateBtn" @click="handleSearchTemplate" type="primary" style="margin-left: 20px">职位模板</el-button>
      </el-form-item>
      <el-form-item label="职位名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入职位名称" class="!w-240px"/>
      </el-form-item>
      <el-form-item label="到期时间" prop="expireTime">
        <el-date-picker v-model="formData.expireTime" :disabled="disabled" :disabledDate="disabledDates" value-format="x" type="date" placeholder="请选择职位到期时间"  class="!w-240px" />
        <el-checkbox v-model="loadingTerm" label="长期有效" size="large" style="margin-left: 20px;" @change="handleLongTerm"/>
      </el-form-item>
      <el-form-item label="职位内容" prop="content">
        <Editor v-model="formData.content" height="150px" />
      </el-form-item>
      <el-form-item label="职位要求" prop="requirement">
        <Editor v-model="formData.requirement" height="150px" />
      </el-form-item>
      <el-form-item label="招聘类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择招聘类型" class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_JOB_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="工作经验" prop="expType">
        <el-select v-model="formData.expType" placeholder="请选择工作经验" class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_EXP_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="学历要求" prop="eduType">
        <el-select v-model="formData.eduType" placeholder="请选择学历要求" class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_EDUCATION_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="最低薪资" prop="payFrom">
        <el-input-number v-model="formData.payFrom" :min="1" :step="1000" class="!w-240px" />
      </el-form-item>
      <el-form-item label="最高薪资" prop="payTo">
        <el-input-number v-model="formData.payTo" :min="1" :step="1000" class="!w-240px" />
      </el-form-item>
      <el-form-item label="计薪时段" prop="payUnit">
        <el-select v-model="formData.payUnit" placeholder="请选择计薪时段" class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_PAY_UNIT)" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="工作地区" prop="areaId">
        <el-cascader v-model="formData.areaId" :options="area" :props="{ label: 'name', value: 'id', emitPath: false }"  class="!w-240px" />
      </el-form-item>
      <el-form-item label="详情地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入工作地址" />
      </el-form-item>
      <el-form-item label="职位关键字" prop="tagList">
        <el-cascader v-model="formData.tagList" :options="tagTreeData" :props="{ label: 'nameCn', value: 'nameCn', emitPath: false, multiple: true }"  class="!w-240px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { JobAdvertisedApi, JobAdvertisedVO } from '@/api/menduner/system/job'
import { commissionCalculation } from '@/utils/transform/position'
import * as CommissionRatioApi from '@/api/menduner/system/hire/commissionRatio/index'
import { dictApi } from '@/api/menduner/common/useDictionaries'

/** 门墩儿-招聘职位 表单 */
defineOptions({ name: 'JobAdvertisedForm' })
defineProps({
  area: Array,
  position: Array
})
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const loadingTerm = ref(false) // 长期有效
const showTemplateBtn = ref(true) // 职位模板按钮
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  areaId: undefined,
  name: undefined,
  positionId: undefined,
  type: undefined,
  expType: undefined,
  expireTime: undefined,
  eduType: undefined,
  payFrom: 6000,
  payTo: 8000,
  hirePrice: 10,
  payUnit: undefined,
  tagList: undefined,
  content: undefined,
  requirement: undefined,
  address: undefined
})

const checkPayFrom = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('最低薪资不能为空'))
  } else {
    if (value >= formData.value.payTo) {
      callback(new Error('应低于最高薪资'))
    }
    callback()
  }
}
const checkPayTo = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('最高薪资不能为空'))
  } else {
    if (value <= formData.value.payFrom) {
      callback(new Error('应高于最低薪资'))
    }
    callback()
  }
}
const formRules = reactive({
  hirePrice: [{ required: true, message: '请填写点数', trigger: 'change' }],
  areaId: [{ required: true, message: '工作地区不能为空', trigger: 'change' }],
  name: [{ required: true, message: '职位名称不能为空', trigger: 'blur' }],
  positionId: [{ required: true, message: '职位类型不能为空', trigger: 'change' }],
  type: [{ required: true, message: '招聘类型不能为空', trigger: 'change' }],
  expType: [{ required: true, message: '工作经验不能为空', trigger: 'change' }],
  eduType: [{ required: true, message: '学历要求不能为空', trigger: 'change' }],
  payUnit: [{ required: true, message: '计薪时段不能为空', trigger: 'change' }],
  payFrom: [{ required: true, validator: checkPayFrom, trigger: 'change' }],
  payTo: [{ required: true, validator: checkPayTo, trigger: 'change' }],
  content: [{ required: true, message: '职位内容不能为空', trigger: 'change' }],
  requirement: [{ required: true, message: '职位要求不能为空', trigger: 'change' }],
  address: [{ required: true, message: '工作详情地址不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const disabled = ref(false) // 是否禁用日期选择器

// 过去的日期不可选
const disabledDates = (date) => {
  const currentDate = new Date()
  currentDate.setDate(currentDate.getDate() - 1)
  return date.getTime() < currentDate.getTime()
}

// 职位过期时间长期有效
const handleLongTerm = (e) => {
  if (e) formData.value.expireTime = null
  disabled.value = e ? true : false
}

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

// 职位标签
const tagTreeData = ref([])
const getTagList = async () => {
  const data = await dictApi.getTagTreeDataApi({ type: 2 })
  tagTreeData.value = data || []
}
getTagList()

// 职位模板填充
const handleSearchTemplate = async () => {
  if (!formData.value.positionId) return message.warning('请先选择职位类型')
  const res = await JobAdvertisedApi.getRecruitPositionDetails(formData.value.positionId)

  if (!res || !res.content || !res.requirement) {
    message.warning('此职位类型没有可使用的模板！')
    showTemplateBtn.value = false
    return
  }
  if (formData.value.content || formData.value.requirement) {
    await message.confirm('您确定要放弃目前岗位描述的内容吗？')
    formData.value.content = res.content
    formData.value.requirement = res.requirement
    message.success('模板填充完成！')
  } else {
    // 无内容点击默认填充
    formData.value.content = res.content
    formData.value.requirement = res.requirement
    message.success('模板填充完成！')
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await JobAdvertisedApi.getJobAdvertised(id)
      formData.value.expType = Number(formData.value.expType)
      formData.value.eduType = Number(formData.value.eduType)
      formData.value.payUnit = Number(formData.value.payUnit)
      formData.value.type = Number(formData.value.type)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  if (!loadingTerm.value && !formData.value.expireTime) return message.warning('请选择过期时间')
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as JobAdvertisedVO
    if (formType.value === 'create') {
      await JobAdvertisedApi.createJobAdvertised(data)
      message.success(t('common.createSuccess'))
    } else {
      await JobAdvertisedApi.updateJobAdvertised(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    areaId: undefined,
    name: undefined,
    positionId: undefined,
    type: undefined,
    expType: undefined,
    payUnit: undefined,
    expireTime: undefined,
    eduType: undefined,
    payFrom: 6000,
    tagList: undefined,
    hirePrice: 10,
    payTo: 8000,
    content: undefined,
    requirement: undefined,
    address: undefined
  }
  formRef.value?.resetFields()
}
</script>