<template>
  <el-dialog
    :title="dataForm.id ? '修改' : '新增'"
    :close-on-click-modal="false"
    width="600px"
    v-model="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmit" label-width="120px">
      <el-form-item label="年份" prop="year">
        <el-date-picker
          v-model="dataForm.year"
          type="year"
          format="YYYY"
          value-format="YYYY"
          placeholder="请选择年份"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="招生计划名称" prop="groupName">
        <el-input v-model="dataForm.groupName" placeholder="招生计划名称"></el-input>
      </el-form-item>

      <date-range-picker
        label="报名时间"
        start-prop="startDate"
        end-prop="endDate"
        v-model:start-value="dataForm.startDate"
        v-model:end-value="dataForm.endDate"
        required
      >
        <template #startDatePicker>
          <el-date-picker
            v-model="dataForm.startDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
            :disabled-date="startDateDisabledDate"
            type="datetime"
            placeholder="请选择开始时间"
            @change="handleStartDateChange"
          ></el-date-picker>
        </template>
        <template #endDatePicker>
          <el-date-picker
            v-model="dataForm.endDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
            :disabled-date="endDateDisabledDate"
            type="datetime"
            placeholder="请选择结束时间"
            @change="handleEndDateChange"
          ></el-date-picker>
        </template>
      </date-range-picker>
      <date-range-picker
        label="维护时间"
        start-prop="maintenanceStartDate"
        end-prop="maintenanceEndDate"
        v-model:start-value="dataForm.maintenanceStartDate"
        v-model:end-value="dataForm.maintenanceEndDate"
        required
      >
        <template #startDatePicker>
          <el-date-picker
            v-model="dataForm.maintenanceStartDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
            :disabled-date="maintenanceStartDateDisabledDate"
            type="datetime"
            placeholder="请选择开始时间"
            @change="handleMaintenanceStartDateChange"
          ></el-date-picker>
        </template>
        <template #endDatePicker>
          <el-date-picker
            v-model="dataForm.maintenanceEndDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
            :disabled-date="maintenanceEndDateDisabledDate"
            type="datetime"
            placeholder="请选择结束时间"
            @change="handleMaintenanceEndDateChange"
          ></el-date-picker>
        </template>
      </date-range-picker>

      <el-form-item label="初中生报名" prop="czSignStart">
        <el-select v-model="dataForm.czSignStart" placeholder="请选择" clearable>
          <el-option
            v-for="item in yes_no_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="高中生报名" prop="gzSignStart">
        <el-select v-model="dataForm.gzSignStart" placeholder="请选择" clearable>
          <el-option
            v-for="item in yes_no_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="技职校报名" prop="jzxSignStart">
        <el-select v-model="dataForm.jzxSignStart" placeholder="请选择" clearable>
          <el-option
            v-for="item in yes_no_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit" v-if="canSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, defineAsyncComponent } from 'vue'
import { ElNotification } from 'element-plus'
import { addObj, getObj, putObj } from '/@/api/recruit/recruitstudentplangroup'
import { useDict } from '/@/hooks/dict'

const DateRangePicker = defineAsyncComponent(() => import('/@/components/DateRangePicker/index.vue'))

// 使用字典
const { yes_no_type } = useDict('yes_no_type')

// Emits
const emit = defineEmits<{
  (e: 'refreshDataList'): void
}>()

// 表单引用
const dataFormRef = ref()

// 响应式数据
const visible = ref(false)
const canSubmit = ref(false)

const dataForm = reactive({
  id: "",
  year: "",
  groupName: "",
  startDate: "",
  endDate: "",
  maintenanceStartDate: "",
  maintenanceEndDate: "",
  feeAgency: 0,
  czSignStart: "",
  gzSignStart: "",
  jzxSignStart: ""
})

const dataRule = {
  year: [
    { required: true, message: '年份不能为空', trigger: 'blur' }
  ],
  groupName: [
    { required: true, message: '招生计划名称不能为空', trigger: 'blur' },
    { min: 0, max: 30, message: '长度在 0 到 30 个字符', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '报名开始时间不能为空', trigger: 'blur' }
  ],
  endDate: [
    { required: true, message: '报名截止时间不能为空', trigger: 'blur' }
  ],
  maintenanceStartDate: [
    { required: true, message: '维护开始时间不能为空', trigger: 'blur' }
  ],
  maintenanceEndDate: [
    { required: true, message: '维护截止时间不能为空', trigger: 'blur' }
  ],
  feeAgency: [
    { required: true, message: '代办费不能为空', trigger: 'blur' }
  ],
  czSignStart: [
    { required: true, message: '初中生报名不能为空', trigger: 'blur' }
  ],
  gzSignStart: [
    { required: true, message: '高中生报名不能为空', trigger: 'blur' }
  ],
  jzxSignStart: [
    { required: true, message: '技职校报名不能为空', trigger: 'blur' }
  ],
}

// 日期选择器的禁用日期函数
const startDateDisabledDate = (time: Date) => {
  if (dataForm.endDate) {
    return new Date(dataForm.endDate).getTime() < time.getTime()
  }
  return false
}

const endDateDisabledDate = (time: Date) => {
  if (dataForm.startDate) {
    return new Date(dataForm.startDate).getTime() > time.getTime()
  }
  return false
}

const maintenanceStartDateDisabledDate = (time: Date) => {
  if (dataForm.maintenanceEndDate) {
    return new Date(dataForm.maintenanceEndDate).getTime() < time.getTime()
  }
  return false
}

const maintenanceEndDateDisabledDate = (time: Date) => {
  if (dataForm.maintenanceStartDate) {
    return new Date(dataForm.maintenanceStartDate).getTime() > time.getTime()
  }
  return false
}

// 处理日期变化事件
const handleStartDateChange = (val: string) => {
  dataForm.startDate = val
}

const handleEndDateChange = (val: string) => {
  dataForm.endDate = val
}

const handleMaintenanceStartDateChange = (val: string) => {
  dataForm.maintenanceStartDate = val
}

const handleMaintenanceEndDateChange = (val: string) => {
  dataForm.maintenanceEndDate = val
}

// 表单提交
const dataFormSubmit = () => {
  dataFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      canSubmit.value = false
      if (dataForm.id) {
        putObj(dataForm).then(() => {
          ElNotification.success({
            title: '成功',
            message: '修改成功'
          })
          visible.value = false
          emit('refreshDataList')
        }).catch(() => {
          canSubmit.value = true
        })
      } else {
        addObj(dataForm).then(() => {
          ElNotification.success({
            title: '成功',
            message: '添加成功'
          })
          visible.value = false
          emit('refreshDataList')
        }).catch(() => {
          canSubmit.value = true
        })
      }
    }
  })
}

// 初始化方法
const init = (id?: string | null) => {
  // 重置表单数据
  dataForm.id = ""
  dataForm.year = ""
  dataForm.groupName = ""
  dataForm.startDate = ""
  dataForm.endDate = ""
  dataForm.maintenanceStartDate = ""
  dataForm.maintenanceEndDate = ""
  dataForm.feeAgency = 0
  dataForm.czSignStart = ""
  dataForm.gzSignStart = ""
  dataForm.jzxSignStart = ""
  
  visible.value = true
  canSubmit.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    // 只有当 id 是有效的字符串时才加载数据
    if (id && typeof id === 'string' && id.trim() !== '') {
      dataForm.id = id
      getObj(id).then((response: any) => {
        Object.assign(dataForm, response.data)
        if (dataForm.year) {
          dataForm.year = String(dataForm.year)
        }
      }).catch(() => {
        // 错误处理
      })
    }
  })
}

// 暴露方法给父组件
defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>
