<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading"
    >
      <el-form-item label="身份证号" prop="idNo">
        <el-input v-model="formData.idNo" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="职级档位" prop="levelGear">
        <el-input v-model="formData.levelGear" placeholder="请输入职级档位" />
      </el-form-item>
      <el-form-item label="岗位工资" prop="stationSalary">
        <el-input v-model="formData.stationSalary" placeholder="请输入岗位工资" />
      </el-form-item>
      <el-form-item label="艰苦补贴" prop="hardshipAllowance">
        <el-input v-model="formData.hardshipAllowance" placeholder="请输入艰苦补贴" />
      </el-form-item>
      <el-form-item label="企业年金缴纳基数" prop="annuityBase">
        <el-input v-model="formData.annuityBase" placeholder="请输入企业年金缴纳基数" />
      </el-form-item>
      <el-form-item label="社保缴纳基数" prop="socialSecurityBase">
        <el-input v-model="formData.socialSecurityBase" placeholder="请输入社保缴纳基数" />
      </el-form-item>
      <el-form-item label="养老金缴纳基数" prop="pensionBase">
        <el-input v-model="formData.pensionBase" placeholder="请输入养老金缴纳基数" />
      </el-form-item>
      <el-form-item label="住房公积金缴纳基数" prop="housingFundBase">
        <el-input v-model="formData.housingFundBase" placeholder="请输入住房公积金缴纳基数" />
      </el-form-item>
      <el-form-item label="年月" prop="month">
        <el-input v-model="formData.month" placeholder="请输入年月" />
      </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 { SalaryConfApi, SalaryConfVO } from '@/api/arcb/salary/salaryconfig'

/** 员工薪资项目配置 表单 */
defineOptions({ name: 'SalaryConfForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  idNo: undefined,
  levelGear: undefined,
  stationSalary: undefined,
  hardshipAllowance: undefined,
  annuityBase: undefined,
  socialSecurityBase: undefined,
  pensionBase: undefined,
  housingFundBase: undefined,
  month: undefined,
})
const formRules = reactive({
  idNo: [{ required: true, message: '身份证号不能为空', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入有效的身份证号',
      trigger: 'blur'
    }
  ],
  levelGear: [{ required: true, message: '职级档位不能为空', trigger: 'blur' }],
  stationSalary: [{ required: true, message: '岗位工资不能为空', trigger: 'blur' }],
  hardshipAllowance: [{ required: true, message: '艰苦补贴不能为空', trigger: 'blur' }],
  annuityBase: [{ required: true, message: '企业年金缴纳基数不能为空', trigger: 'blur' }],
  socialSecurityBase: [{ required: true, message: '社保缴纳基数不能为空', trigger: 'blur' }],
  pensionBase: [{ required: true, message: '养老金缴纳基数不能为空', trigger: 'blur' }],
  housingFundBase: [{ required: true, message: '住房公积金缴纳基数不能为空', trigger: 'blur' }],
  month: [{ required: true, message: '年月不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const regex = /^\d{6}$/; // 匹配6位数字，如202412
        if (!regex.test(value)) {
          const currentYear = new Date().getFullYear();
          const currentMonth = String(new Date().getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1，并确保是两位数
          const currentYearMonth = `${currentYear}${currentMonth}`;

          callback(new Error(`请输入正确的年月格式，如${currentYearMonth}`));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
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 SalaryConfApi.getSalaryConf(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SalaryConfVO
    if (formType.value === 'create') {
      await SalaryConfApi.createSalaryConf(data)
      message.success(t('common.createSuccess'))
    } else {
      await SalaryConfApi.updateSalaryConf(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    idNo: undefined,
    levelGear: undefined,
    stationSalary: undefined,
    hardshipAllowance: undefined,
    annuityBase: undefined,
    socialSecurityBase: undefined,
    pensionBase: undefined,
    housingFundBase: undefined,
    month: undefined,
  }
  formRef.value?.resetFields()
}
</script>