<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="800px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="120px" 
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="班级" prop="classCode">
            <el-select 
              v-model="form.classCode" 
              placeholder="请选择班级" 
              clearable
              filterable
              style="width: 100%"
              @change="handleClassChange">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="学号" prop="stuNo">
            <el-select 
              v-model="form.stuNo" 
              placeholder="请选择学生" 
              clearable
              filterable
              style="width: 100%"
              :disabled="!form.classCode"
              @change="handleStudentChange">
              <el-option
                v-for="item in studentList"
                :key="item.stuNo"
                :label="`${item.realName} (${item.stuNo})`"
                :value="item.stuNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="处分时间" prop="punlishStartDate">
            <el-date-picker
              v-model="form.punlishStartDate"
              type="date"
              placeholder="选择处分时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="到期日" prop="punlishEndDate">
            <el-date-picker
              v-model="form.punlishEndDate"
              type="date"
              placeholder="选择到期日"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="处分级别" prop="punlishLevel">
            <el-select 
              v-model="form.punlishLevel" 
              placeholder="请选择处分级别" 
              clearable
              style="width: 100%">
              <el-option
                v-for="item in punlishLevelList"
                :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="处分内容" prop="punlishContent">
            <el-input 
              v-model="form.punlishContent" 
              type="textarea" 
              :rows="4"
              placeholder="请输入处分内容" />
          </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="StuPunlishFormDialog">
import { ref, reactive, nextTick, onMounted, watch } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/stupunlish'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'
import { getDicts } from '/@/api/admin/dict'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { queryStudentListByClass } from '/@/api/basic/basicstudent'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const operType = ref('add') // add 或 edit
const schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const classList = ref<any[]>([])
const studentList = ref<any[]>([])
const punlishLevelList = ref<any[]>([])
const publishStatusList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  schoolYear: '',
  schoolTerm: '',
  classCode: '',
  stuNo: '',
  punlishStartDate: '',
  punlishEndDate: '',
  punlishLevel: '',
  punlishContent: '',
  publishStatus: '',
  attachment: ''
})

// 定义校验规则
const dataRules = {
  classCode: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  stuNo: [
    { required: true, message: '请选择学生', trigger: 'change' }
  ],
  punlishStartDate: [
    { required: true, message: '请选择处分时间', trigger: 'change' }
  ],
  punlishEndDate: [
    { required: true, message: '请选择到期日', trigger: 'change' }
  ],
  punlishLevel: [
    { required: true, message: '请选择处分级别', trigger: 'change' }
  ],
  punlishContent: [
    { required: true, message: '请输入处分内容', trigger: 'blur' }
  ]
}

// 班级变化时获取学生列表
const handleClassChange = async (classCode: string) => {
  form.stuNo = ''
  studentList.value = []
  if (!classCode) {
    return
  }

  try {
    // 接口文档：GET，仅 classCode；返回 data 为数组，非 data.records
    const res = await queryStudentListByClass({ classCode })
    const data = res?.data
    if (Array.isArray(data)) {
      studentList.value = data
    } else if (data?.records && Array.isArray(data.records)) {
      studentList.value = data.records
    } else {
      studentList.value = []
    }
  } catch (err) {
    studentList.value = []
  }
}

// 学生变化
const handleStudentChange = (stuNo: string) => {
  // 可以在这里处理学生变化后的逻辑
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.schoolYear = ''
    form.schoolTerm = ''
    form.classCode = ''
    form.stuNo = ''
    form.punlishStartDate = ''
    form.punlishEndDate = ''
    form.punlishLevel = ''
    form.punlishContent = ''
    form.publishStatus = ''
    form.attachment = ''
    studentList.value = []
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.schoolYear = row.schoolYear || ''
      form.schoolTerm = row.schoolTerm || ''
      form.classCode = row.classCode || ''
      form.stuNo = row.stuNo || ''
      form.punlishStartDate = row.punlishStartDate || ''
      form.punlishEndDate = row.punlishEndDate || ''
      form.punlishLevel = row.punlishLevel || ''
      form.punlishContent = row.punlishContent || ''
      form.publishStatus = row.publishStatus || ''
      form.attachment = row.attachment || ''
      
      // 如果有班级代码，加载学生列表
      if (form.classCode) {
        handleClassChange(form.classCode)
      }
    }
  })
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    // 验证到期日必须大于处分时间
    if (form.punlishStartDate && form.punlishEndDate) {
      const start = new Date(form.punlishStartDate)
      const end = new Date(form.punlishEndDate)
      if (end <= start) {
        useMessage().error('到期日必须大于处分时间')
        return
      }
    }
    
    loading.value = true
    try {
      const submitData: any = {
        classCode: form.classCode,
        stuNo: form.stuNo,
        punlishStartDate: form.punlishStartDate,
        punlishEndDate: form.punlishEndDate,
        punlishLevel: form.punlishLevel,
        punlishContent: form.punlishContent,
        publishStatus: form.publishStatus || '1',
        attachment: form.attachment || ''
      }
      
      // 编辑时需要包含id和学年学期
      if (operType.value === 'edit') {
        submitData.id = form.id
        submitData.schoolYear = form.schoolYear
        submitData.schoolTerm = form.schoolTerm
      }
      
      if (operType.value === 'add') {
        await addObj(submitData)
        useMessage().success('新增成功')
      } else {
        await editObj(submitData)
        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) {
      schoolYearList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    schoolYearList.value = []
  }
}

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

// 获取班级列表
const getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data) {
      classList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    classList.value = []
  }
}

// 获取处分级别字典
const getPunlishLevelDict = async () => {
  try {
    const res = await getDicts('punlish_level')
    if (res.data) {
      punlishLevelList.value = Array.isArray(res.data) ? res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      })) : []
    }
  } catch (err) {
    punlishLevelList.value = []
  }
}

// 获取处分状态字典
const getPublishStatusDict = async () => {
  try {
    const res = await getDicts('publish_status')
    if (res.data) {
      publishStatusList.value = Array.isArray(res.data) ? res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      })) : []
    }
  } catch (err) {
    publishStatusList.value = []
  }
}

// 初始化
onMounted(() => {
  getSchoolYearList()
  getSchoolTermDict()
  getClassListData()
  getPunlishLevelDict()
  getPublishStatusDict()
})

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

