<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="600">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="核算年月" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          type="month"
          style="width: 100%"
          value-format="x"
          placeholder="选择核算年月"
        />
      </el-form-item>
      <el-form-item label="所属公司" prop="companyId">
        <el-select
          v-model="formData.companyId"
          filterable
          placeholder="请选择所属公司"
          style="width: 100%"
        >
          <el-option
            v-for="company in companyOptions"
            :key="company.id"
            :label="company.name"
            :value="company.id"
          />
        </el-select>
      </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 { SalaryMonthRecordApi, SalaryMonthRecord } from '@/api/hr/salarymonthrecord'
import * as DeptApi from "@/api/system/dept";

/** 每月薪资记录 表单 */
defineOptions({ name: 'SalaryMonthRecordForm' })

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,
  companyId: undefined,
  title: undefined,
  year: undefined,
  month: undefined,
  num: undefined,
  startTime: undefined,
  endTime: undefined,
  personalInsuranceAmount: undefined,
  personalProvidentFundAmount: undefined,
  corporateInsuranceAmount: undefined,
  corporateProvidentFundAmount: undefined,
  expectedPaySalary: undefined,
  personalTax: undefined,
  realPaySalary: undefined,
  optionHead: undefined,
  examineRecordId: undefined,
  checkStatus: undefined,
})
const formRules = reactive({
  startTime: [{ required: true, message: '核算年月不能为空', trigger: 'blur' }],
  companyId: [{ required: true, message: '所属公司不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const companyOptions = ref([])

// 获取参保人员选项
const getCompanyOptions = async () => {
  try {
    const deptData = await DeptApi.getCompanyList()
    companyOptions.value = deptData
  } catch (error) {
    console.error('获取人员列表失败', error)
  }
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = '新增薪资核算'
  formType.value = type
  resetForm()
  // 获取可选人员列表
  await getCompanyOptions()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SalaryMonthRecordApi.getSalaryMonthRecord(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 SalaryMonthRecord
    const { startTime } = formData.value as unknown as SalaryMonthRecord
    const { companyId } = formData.value as unknown as SalaryMonthRecord

    // 将时间戳转为 YYYY-MM 格式
    const date = new Date(startTime)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始
    const formattedStartTime = `${year}-${month}`
    await SalaryMonthRecordApi.addNextMonthSalary(formattedStartTime,companyId)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    companyId: undefined,
    title: undefined,
    year: undefined,
    month: undefined,
    num: undefined,
    startTime: undefined,
    endTime: undefined,
    personalInsuranceAmount: undefined,
    personalProvidentFundAmount: undefined,
    corporateInsuranceAmount: undefined,
    corporateProvidentFundAmount: undefined,
    expectedPaySalary: undefined,
    personalTax: undefined,
    realPaySalary: undefined,
    optionHead: undefined,
    examineRecordId: undefined,
    checkStatus: undefined,
  }
  formRef.value?.resetFields()
}
</script>
