<template>
  <el-dialog 
    title="新增" 
    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="deptCode">
            <el-select 
              v-model="form.deptCode" 
              placeholder="请选择系部" 
              clearable
              filterable
              style="width: 100%"
              @change="handleDeptChange">
              <el-option
                v-for="item in deptList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <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="realName">
            <el-input 
              v-model="form.realName" 
              placeholder="自动填充" 
              disabled
              style="width: 100%" />
          </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="datetime"
              placeholder="请选择开始时间"
              format="YYYY-MM-DD HH:mm"
              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="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="请选择结束时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="请假事由" prop="reason">
            <el-input 
              v-model="form.reason" 
              type="textarea" 
              :rows="4"
              placeholder="请输入请假事由" />
          </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="请输入备注" />
          </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="StuTemLeaveApplyFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj } from '/@/api/stuwork/stutemleaveapply'
import { getDeptListByLevelTwo } from '/@/api/basic/basicdept'
import { list as getClassList } 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 deptList = ref<any[]>([])
const classList = ref<any[]>([])
const studentList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  deptCode: '',
  classCode: '',
  stuNo: '',
  realName: '',
  startTime: '',
  endTime: '',
  reason: '',
  remarks: ''
})

// 定义校验规则
const dataRules = {
  deptCode: [
    { required: true, message: '请选择系部代码', trigger: 'change' }
  ],
  classCode: [
    { required: true, message: '请选择班级代码', trigger: 'change' }
  ],
  stuNo: [
    { required: true, message: '请选择学号', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择请假开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择请假结束时间', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入请假事由', trigger: 'blur' }
  ]
}

// 打开弹窗
const openDialog = () => {
  visible.value = true
  resetForm()
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
}

// 重置表单
const resetForm = () => {
  form.deptCode = ''
  form.classCode = ''
  form.stuNo = ''
  form.realName = ''
  form.startTime = ''
  form.endTime = ''
  form.reason = ''
  form.remarks = ''
  studentList.value = []
}

// 系部变化
const handleDeptChange = () => {
  form.classCode = ''
  form.stuNo = ''
  form.realName = ''
  studentList.value = []
  // 根据系部筛选班级
  if (form.deptCode) {
    classList.value = classList.value.filter((item: any) => item.deptCode === form.deptCode)
  } else {
    getClassListData()
  }
}

// 班级变化
const handleClassChange = async () => {
  form.stuNo = ''
  form.realName = ''
  studentList.value = []
  if (form.classCode) {
    await getStudentListData()
  }
}

// 学生变化
const handleStudentChange = () => {
  const student = studentList.value.find((item: any) => item.stuNo === form.stuNo)
  if (student) {
    form.realName = student.realName || ''
  } else {
    form.realName = ''
  }
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    // 验证时间
    if (form.startTime && form.endTime) {
      const start = new Date(form.startTime)
      const end = new Date(form.endTime)
      if (end <= start) {
        useMessage().error('请假结束时间必须大于开始时间')
        return
      }
    }
    
    loading.value = true
    try {
      await addObj({
        deptCode: form.deptCode,
        classCode: form.classCode,
        stuNo: form.stuNo,
        startTime: form.startTime,
        endTime: form.endTime,
        reason: form.reason,
        remarks: form.remarks
      })
      useMessage().success('新增成功')
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      useMessage().error(err.msg || '新增失败')
    } finally {
      loading.value = false
    }
  })
}

// 获取系部列表
const getDeptListData = async () => {
  try {
    const res = await getDeptListByLevelTwo()
    if (res.data) {
      deptList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    deptList.value = []
  }
}

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

// 获取学生列表（接口文档：GET 仅 classCode，返回 data 为数组）
const getStudentListData = async () => {
  if (!form.classCode) return
  try {
    const res = await queryStudentListByClass({ classCode: form.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 = []
  }
}

// 初始化
onMounted(() => {
  getDeptListData()
  getClassListData()
})

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

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

