<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="top"
      v-loading="formLoading"
    >
      <div class="employeeInfo-box">
        <span>{{ employeeInfo.employeeName || '--' }}</span> |
        <span>{{ employeeInfo.deptName || '--' }}</span> |
        <span>{{ employeeInfo.post || '--' }}</span> |
        <span>{{ statusValue[employeeInfo.status] || '--' }}</span>
      </div>
      <!-- 调薪模板下拉框 -->
      <el-form-item label="定薪模板" prop="templateId">
        <el-select
          v-model="formData.templateId"
          placeholder="请选择定薪模板"
          clearable
          style="width: 250px"
          @change="handleTemplateChange"
        >
          <el-option
            v-for="item in templateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 调薪细则表格 -->
      <el-form-item label="定薪细则" prop="salaryDetails">
        <el-table :data="formData.salaryDetails" show-summary border style="width: 100%">
          <el-table-column label="定薪项" prop="name" width="220" />
          <el-table-column label="试用期工资" prop="probationValue" width="220">
            <template #default="scope">
              <el-input-number
                v-if="employeeInfo.status == 2"
                v-model="scope.row.probationValue"
                :precision="2"
                :min="0"
                :max="9999999.99"
                placeholder="请输入试用期工资"
              />
              <span v-else>{{ scope.row.probationValue }}</span>
            </template>
          </el-table-column>
          <el-table-column label="转正后工资" prop="permanentValue" min-width="150">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.permanentValue"
                :precision="2"
                :min="0"
                :max="9999999.99"
                placeholder="请输入转正后工资"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 备注文本域 -->
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="formData.remarks" type="textarea" rows="2" 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 { SalaryArchivesApi, SalaryArchives } from '@/api/hr/salaryarchives'
import { isEmpty, floatAdd } from '@/utils'
/** 薪资档案 表单 */
defineOptions({ name: 'SalaryArchivesForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
// 非正式类型 特殊 和状态一致
const statusValue = {
  1: '正式',
  2: '试用',
  3: '实习',
  4: '兼职',
  5: '劳务',
  6: '顾问',
  7: '返聘',
  8: '外包',
  // 9: '待离职',
  // 10: '已离职',
  11: '在职',
  12: '全职',
  13: '待入职',
  14: '待离职',
  15: '已离职'
}
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  templateId: undefined, // 调薪模板ID
  salaryDetails: [], // 调薪细则数组（{name, beforeValue, permanentValue}）
  changeReason: undefined, // 调薪原因（文本域）
  enableDate: undefined, // 生效日期（yyyy-MM-dd）
  remarks: undefined // 备注（文本域
})
const formRules = reactive({
  templateId: [{ required: true, message: '模板不能为空', trigger: 'change' }],
  salaryDetails: [
    {
      validator: (rule, value, callback) => {
        if (value.length === 0) callback(new Error('细则至少需要一条记录'))
        else callback()
      },
      trigger: 'change'
    }
  ],
  changeReason: [{ required: true, message: '调薪原因不能为空', trigger: 'blur' }],
  enableDate: [{ required: true, message: '调薪生效日期不能为空', trigger: 'change' }]
  // 备注不再强制校验（根据需求可选）
  // remarks: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref
// 假设从接口获取调薪模板选项（需要根据实际API调整）
const templateOptions = ref([])
const rowData = ref(null)
/** 打开弹窗 */
const open = async (type: string, data?: any) => {
  rowData.value = data
  await getEmployeeDetail()
  getTemplateList()
  dialogVisible.value = true
  dialogTitle.value = data.changeType == 0 ? '定薪' : '调薪'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (data.id) {
    formLoading.value = true
    try {
      formData.value = await SalaryArchivesApi.getSalaryArchives(data.id)
    } finally {
      formLoading.value = false
    }
  }
}
const employeeInfo = ref({})

const getEmployeeDetail = async () => {
  // 获取员工详情
  const res = await SalaryArchivesApi.employeeById(rowData.value.employeeId)
  employeeInfo.value = res
}
const getTemplateList = async () => {
  const res = await SalaryArchivesApi.queryChangeTemplateList()
  console.log(res)
  templateOptions.value = res.map((item) => {
    return {
      value: item.id,
      label: item.templateName,
      list: item.value
    }
  })
  if (res.length > 0) {
    formData.value.templateId = res[0].id
    getTemplateOption(JSON.parse(res[0].value))
  }
}
const handleTemplateChange = (e) => {
  const templateData = templateOptions.value.find((item) => item.value == e)
  getTemplateOption(JSON.parse(templateData.list))
}
/**
 * 获取调薪项
 */
const getTemplateOption = (list) => {
  const value = []
  list.forEach((item) => {
    value.push({
      ...item,
      probationValue: 0.0,
      permanentValue: 0.0
    })
  })
  formData.value.salaryDetails = value
}
const getOptionParams = (list) => {
  const newSalary = []
  const oldSalary = []
  let beforeSum = 0
  let afterSum = 0
  list.forEach((item) => {
    oldSalary.push({
      code: item.code,
      name: item.name,
      value: item.beforeValue
    })
    beforeSum = floatAdd(beforeSum, item.beforeValue)

    newSalary.push({
      code: item.code,
      name: item.name,
      value: item.afterValue
    })
    afterSum = floatAdd(afterSum, item.afterValue)
  })
  return {
    newSalary,
    oldSalary,
    beforeSum,
    afterSum
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const salaryDetails = formData.value.salaryDetails
    const proSalary = []
    let proSum = 0.0
    const salary = []
    let sum = 0.0
    salaryDetails.forEach((item) => {
      proSalary.push({
        code: item.code,
        name: item.name,
        value: item.probationValue
      })
      proSum = floatAdd(proSum, item.probationValue)

      salary.push({
        code: item.code,
        name: item.name,
        value: item.permanentValue
      })
      sum = floatAdd(sum, item.permanentValue)
    })
    const params = {
      employeeId: rowData.value.employeeId,
      remarks: formData.value.remarks,
      proSalary,
      proSum,
      salary,
      sum,
      changeTemplateId: formData.value.templateId
    }
    await SalaryArchivesApi.setFixSalaryRecord(params)
    message.success('定薪成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    templateId: undefined,
    salaryDetails: [],
    changeReason: undefined,
    enableDate: undefined,
    remarks: undefined
  }
  formRef.value?.resetFields()
}
</script>
<style scoped>
.employeeInfo-box {
  padding-left: 10px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}
</style>
