<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%">
              <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%">
              <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="type">
            <el-select 
              v-model="form.type" 
              placeholder="请选择季度" 
              clearable
              style="width: 100%">
              <el-option
                v-for="item in quarterList"
                :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="classify">
            <el-select 
              v-model="form.classify" 
              placeholder="请选择类别" 
              clearable
              style="width: 100%">
              <el-option
                v-for="item in classifyList"
                :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="money">
            <el-select 
              v-model="form.money" 
              placeholder="请选择补助金额" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in moneyList"
                :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="24" class="mb20">
          <el-form-item label="备注" prop="remarks">
            <el-input 
              v-model="form.remarks" 
              type="textarea"
              :rows="3"
              placeholder="请输入备注" 
              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="StipendTermBatchForm">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { addObj, editObj, getDetail } from "/@/api/stuwork/stipendtermbatch";
import { queryAllSchoolYear } from "/@/api/basic/basicyear";
import { getDicts } from "/@/api/admin/dict";
import { useMessage } from "/@/hooks/message";

// 定义变量内容
const emit = defineEmits(['refresh'])
const visible = ref(false)
const loading = ref(false)
const dataFormRef = ref()
const operType = ref<'add' | 'edit'>('add')
const schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const quarterList = ref<any[]>([])
const classifyList = ref<any[]>([])
const moneyList = ref<any[]>([])

// 表单数据
const form = reactive({
  id: '',
  title: '',
  schoolYear: '',
  schoolTerm: '',
  type: '',
  classify: '',
  money: '',
  startTime: '',
  endTime: '',
  remarks: ''
})

// 表单验证规则
const dataRules = reactive({
  title: [
    { required: true, message: '请输入批次名称', trigger: 'blur' }
  ],
  schoolYear: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  schoolTerm: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择季度', trigger: 'change' }
  ],
  classify: [
    { required: true, message: '请选择类别', trigger: 'change' }
  ],
  money: [
    { required: true, message: '请选择补助金额', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请输入开始日期', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请输入截止日期', trigger: 'change' }
  ]
})

// 打开弹窗
const openDialog = async (type: 'add' | 'edit', id?: string) => {
  visible.value = true
  operType.value = type
  
  // 重置表单
  Object.assign(form, {
    id: '',
    title: '',
    schoolYear: '',
    schoolTerm: '',
    type: '',
    classify: '',
    money: '',
    startTime: '',
    endTime: '',
    remarks: ''
  })
  
  // 编辑时获取详情
  if (type === 'edit' && id) {
    loading.value = true
    try {
      const res = await getDetail(id)
      if (res.data) {
        Object.assign(form, {
          id: res.data.id,
          title: res.data.title || '',
          schoolYear: res.data.schoolYear || '',
          schoolTerm: res.data.schoolTerm || '',
          type: res.data.type || '',
          classify: res.data.classify || '',
          money: res.data.money || '',
          startTime: res.data.startTime || '',
          endTime: res.data.endTime || '',
          remarks: res.data.remarks || ''
        })
      }
    } catch (err: any) {
      useMessage().error(err.msg || '获取详情失败')
      visible.value = false
    } finally {
      loading.value = false
    }
  }
  
  // 清除验证
  nextTick(() => {
    dataFormRef.value?.clearValidate()
  })
}

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

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

// 获取学期字典
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
      }))
    }
  } catch (err) {
  }
}

// 获取季度字典
const getQuarterDict = async () => {
  try {
    const res = await getDicts('stipend_term_batch_type')
    if (res.data && Array.isArray(res.data)) {
      quarterList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    }
  } catch (err) {
  }
}

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

// 获取补助金额字典
const getMoneyDict = async () => {
  try {
    const res = await getDicts('stipendMoney')
    if (res.data && Array.isArray(res.data)) {
      moneyList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    }
  } catch (err) {
  }
}

// 初始化
onMounted(() => {
  getSchoolYearList()
  getSchoolTermDict()
  getQuarterDict()
  getClassifyDict()
  getMoneyDict()
})

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

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

