<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="12" class="mb20">
          <el-form-item label="校门" prop="schoolDoor">
            <el-select
              v-model="form.schoolDoor"
              placeholder="请选择校门"
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in schoolDoorList"
                :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="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 { getClassListByRole } from '/@/api/basic/basicclass'
import { queryStudentListByClass, queryAllStudentByClassCode } from '/@/api/basic/basicstudent'
import { listAll as getSchoolDoorList } from '/@/api/safety/clouddeviceposition'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const deptList = ref<any[]>([])
const allClassList = ref<any[]>([])  // 保存所有班级数据
const classList = ref<any[]>([])     // 显示的班级数据（筛选后）
const studentList = ref<any[]>([])
const schoolDoorList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  deptCode: '',
  classCode: '',
  stuNo: '',
  realName: '',
  startTime: '',
  endTime: '',
  schoolDoor: '',
  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.schoolDoor = ''
  form.reason = ''
  form.remarks = ''
  studentList.value = []
  // 重置班级列表为全部
  classList.value = allClassList.value
}

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

// 班级变化
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,
        schoolDoor: form.schoolDoor,
        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 getClassListByRole()
    if (res.data) {
      const list = Array.isArray(res.data) ? res.data : []
      allClassList.value = list
      classList.value = list
    }
  } catch (err) {
    allClassList.value = []
    classList.value = []
  }
}

// 获取学生列表
const getStudentListData = async () => {
  if (!form.classCode) return
  try {
    // 先尝试 queryStudentListByClass 接口
    let res = await queryStudentListByClass({ classCode: form.classCode })
    let data = res?.data

    // 如果数据为空或不是数组，尝试 queryAllStudentByClassCode 接口
    if (!data || (Array.isArray(data) && data.length === 0)) {
      res = await queryAllStudentByClassCode(form.classCode)
      data = res?.data
    }

    if (Array.isArray(data)) {
      studentList.value = data
    } else if (data?.records && Array.isArray(data.records)) {
      studentList.value = data.records
    } else if (data && typeof data === 'object') {
      // 可能返回的是单个对象或包装对象
      studentList.value = [data]
    } else {
      studentList.value = []
    }
  } catch (err) {
    console.error('获取学生列表失败', err)
    studentList.value = []
  }
}

// 获取校门列表
const getSchoolDoorData = async () => {
  try {
    const res = await getSchoolDoorList()
    if (res.data) {
      schoolDoorList.value = Array.isArray(res.data)
        ? res.data.map((item: any) => ({
            label: item.positionName || item.name,
            value: item.id || item.positionCode
          }))
        : []
    }
  } catch (err) {
    schoolDoorList.value = []
  }
}

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

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

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

