<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" style="width: 1200px">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px">
      <el-form-item label="方案名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入方案名称" style="width: 240px" />
      </el-form-item>
    </el-form>
    <div class="mt-10px mb-10px">
      <el-button type="primary" @click="handleAddYearPlan"> 添加年度考勤方案 </el-button>
      <span class="ml-20px font-bold">请配置每月计薪天数，计薪天数 = 应出勤天数 + 带薪假天数</span>
    </div>
    <el-table :data="form.planList" border stripe>
      <el-table-column label="年份" width="150px">
        <template #default="{ row }">
          <el-input-number
            v-model="row.year"
            size="small"
            :min="0"
            :controls="false"
            style="width: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in 12"
        :prop="item + ''"
        :key="item"
        :label="item + '月'"
        width="140px"
      >
        <el-table-column label="应出勤">
          <template #default="{ row }">
            <el-input-number
              v-model="row[item + ''].shouldWorkDay"
              size="small"
              :min="0"
              :max="31"
              :controls="false"
              style="width: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column label="带薪假">
          <template #default="{ row }">
            <el-input-number
              v-model="row[item].paidLeaveDay"
              size="small"
              :min="0"
              :max="31"
              :controls="false"
              style="width: 50px"
            />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="操作" :width="80" fixed="right">
        <template #default="{ $index }">
          <Icon icon="ep:remove-filled" class="text-red-500" @click="handleRemove($index)" />
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <span>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">保存</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script setup name="DialogAttendancePlan">
import * as PlanApi from '@/api/pers/attendancePlan'

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('考勤方案设置')
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const formType = ref('create')
/** 打开弹窗 */
const open = async (type, row) => {
  dialogVisible.value = true
  dialogTitle.value = type == 'create' ? `新增方案` : '修改方案'
  formType.value = type
  resetForm()
  if (row?.attendanceSettingId) {
    formLoading.value = true
    try {
      const data = await PlanApi.getPlanDetail(row.attendanceSettingId)
      const list = data.attendancePeriodS.map((item) => {
        item.monthSettings.map((it) => {
          item[it.month + ''] = {
            shouldWorkDay: it.shouldWorkDay,
            paidLeaveDay: it.paidLeaveDay
          }
        })
        item.year = item.year
        delete item.monthSettings
        return item
      })
      form.value = {
        attendanceSettingId: data.attendanceSettingId,
        name: data.name,
        status: data.status,
        planList: list
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const form = ref({})
const rules = {
  name: { required: true, message: '方案名称不可为空', trigger: 'blur' }
}
function resetForm() {
  form.value = {
    name: undefined,
    planList: []
  }
}

function handleAddYearPlan() {
  form.value.planList.push({
    year: new Date().getFullYear(),
    1: { shouldWorkDay: 0, paidLeaveDay: 0 },
    2: { shouldWorkDay: 0, paidLeaveDay: 0 },
    3: { shouldWorkDay: 0, paidLeaveDay: 0 },
    4: { shouldWorkDay: 0, paidLeaveDay: 0 },
    5: { shouldWorkDay: 0, paidLeaveDay: 0 },
    6: { shouldWorkDay: 0, paidLeaveDay: 0 },
    7: { shouldWorkDay: 0, paidLeaveDay: 0 },
    8: { shouldWorkDay: 0, paidLeaveDay: 0 },
    9: { shouldWorkDay: 0, paidLeaveDay: 0 },
    10: { shouldWorkDay: 0, paidLeaveDay: 0 },
    11: { shouldWorkDay: 0, paidLeaveDay: 0 },
    12: { shouldWorkDay: 0, paidLeaveDay: 0 }
  })
}

const emit = defineEmits(['success'])
const formRef = ref()
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const arr = form.value.planList.map((item) => {
      const list = []
      for (let i = 1; i <= 12; i++) {
        list.push({
          month: i,
          ...item[i + '']
        })
      }
      return {
        year: item.year,
        monthSettings: list
      }
    })
    const data = {
      name: form.value.name,
      attendancePeriodS: arr
    }
    if (formType.value === 'create') {
      await PlanApi.createPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      data.attendanceSettingId = form.value.attendanceSettingId
      data.status = form.value.status
      await PlanApi.updatePlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (err) {
    console.log(err)
  } finally {
    formLoading.value = false
  }
}

function handleRemove(index) {
  form.value.planList.splice(index, 1)
}
</script>

<style lang="scss" scoped></style>
