<template>
  <el-dialog 
    :title="form.id ? '编辑批次' : '新增批次'" 
    v-model="visible" 
    :width="800" 
    :close-on-click-modal="false" 
    draggable>
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="120px" 
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="批次名称" prop="title">
            <el-input 
              v-model="form.title" 
              placeholder="请输入批次名称" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="学年" prop="schoolYear">
            <el-select 
              v-model="form.schoolYear" 
              placeholder="请选择学年" 
              clearable
              filterable
              style="width: 100%"
              :disabled="!!form.id">
              <el-option
                v-for="item in schoolYearList"
                :key="item.year"
                :label="item.year"
                :value="item.year">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="学期" prop="schoolTerm">
            <el-select 
              v-model="form.schoolTerm" 
              placeholder="请选择学期" 
              clearable
              style="width: 100%"
              :disabled="!!form.id">
              <el-option
                v-for="item in schoolTermList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="上报开始日期" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="date"
              placeholder="请输入上报开始日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="上报截止日期" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="date"
              placeholder="请输入上报截止日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="类别" prop="type">
            <el-select 
              v-model="form.type" 
              placeholder="请选择类别" 
              clearable
              style="width: 100%">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="excel表头" prop="excelTitle">
            <el-input 
              v-model="form.excelTitle" 
              type="textarea"
              :rows="4"
              placeholder="请输入excel表头" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="TuitionFreeTermFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/tuitionfreeterm'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'
import { getDicts } from '/@/api/admin/dict'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const operType = ref('add')
const schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const typeList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  title: '',
  schoolYear: '',
  schoolTerm: '',
  startTime: '',
  endTime: '',
  type: '',
  excelTitle: ''
})

// 定义校验规则
const dataRules = {
  title: [
    { required: true, message: '请输入批次名称', trigger: 'blur' }
  ],
  schoolYear: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  schoolTerm: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请输入上报开始日期', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请输入上报截止日期', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择类别', trigger: 'change' }
  ],
  excelTitle: [
    { required: true, message: '请输入excel表头', trigger: 'blur' }
  ]
}

// 获取学年列表
const getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data && Array.isArray(res.data)) {
      schoolYearList.value = res.data
    } else {
      schoolYearList.value = []
    }
  } catch (err) {
    schoolYearList.value = []
  }
}

// 获取学期字典
const getSchoolTermDict = async () => {
  try {
    const res = await getDicts('school_term')
    if (res.data && Array.isArray(res.data)) {
      schoolTermList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      schoolTermList.value = []
    }
  } catch (err) {
    schoolTermList.value = []
  }
}

// 获取类别字典
const getTypeDict = async () => {
  try {
    const res = await getDicts('tuition_free_term_type')
    if (res.data && Array.isArray(res.data)) {
      typeList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      typeList.value = []
    }
  } catch (err) {
    typeList.value = []
  }
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  operType.value = type
  visible.value = true
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.title = ''
    form.schoolYear = ''
    form.schoolTerm = ''
    form.startTime = ''
    form.endTime = ''
    form.type = ''
    form.excelTitle = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.title = row.title || ''
      form.schoolYear = row.schoolYear || ''
      form.schoolTerm = row.schoolTerm || ''
      form.startTime = row.startTime || ''
      form.endTime = row.endTime || ''
      form.type = row.type || ''
      form.excelTitle = row.excelTitle || ''
      
      // 如果需要获取详情
      if (row.id && (!row.title || !row.schoolYear)) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.title = res.data.title || ''
            form.schoolYear = res.data.schoolYear || ''
            form.schoolTerm = res.data.schoolTerm || ''
            form.startTime = res.data.startTime || ''
            form.endTime = res.data.endTime || ''
            form.type = res.data.type || ''
            form.excelTitle = res.data.excelTitle || ''
          }
        }).catch((err) => {
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const submitData = {
          title: form.title,
          schoolYear: form.schoolYear,
          schoolTerm: form.schoolTerm,
          startTime: form.startTime,
          endTime: form.endTime,
          type: form.type,
          excelTitle: form.excelTitle
        }
        
        if (operType.value === 'edit' && form.id) {
          await editObj({ ...submitData, id: form.id })
          useMessage().success('编辑成功')
        } else {
          await addObj(submitData)
          useMessage().success('新增成功')
        }
        
        visible.value = false
        emit('refresh')
      } catch (err: any) {
        useMessage().error(err.msg || (operType.value === 'edit' ? '编辑失败' : '新增失败'))
      } finally {
        loading.value = false
      }
    }
  })
}

// 初始化
onMounted(() => {
  getSchoolYearList()
  getSchoolTermDict()
  getTypeDict()
})

// 暴露方法
defineExpose({
  openDialog
})
</script>

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

