<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="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              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:ss"
              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="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="selectedStudents">
            <el-input
              v-model="selectedStudentsText"
              placeholder="请选择学生"
              readonly
              style="width: 100%"
              @click="openStudentDialog">
              <template #suffix>
                <el-button 
                  icon="Search" 
                  circle 
                  @click.stop="openStudentDialog" />
              </template>
            </el-input>
          </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-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>

  <!-- 学生选择弹窗 -->
  <el-dialog 
    title="选择学生" 
    v-model="studentDialogVisible"
    :close-on-click-modal="false" 
    draggable
    width="900px">
    <!-- 搜索表单 -->
    <el-form :model="studentSearchForm" :inline="true" @keyup.enter="handleStudentSearch">
      <el-form-item label="班号" prop="classNo">
        <el-input 
          v-model="studentSearchForm.classNo" 
          placeholder="请输入班号" 
          clearable
          style="width: 200px" />
      </el-form-item>
      <el-form-item label="学号" prop="stuNo">
        <el-input 
          v-model="studentSearchForm.stuNo" 
          placeholder="请输入学号" 
          clearable
          style="width: 200px" />
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input 
          v-model="studentSearchForm.realName" 
          placeholder="请输入姓名" 
          clearable
          style="width: 200px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain icon="Search" @click="handleStudentSearch">查询</el-button>
        <el-button icon="Refresh" @click="handleStudentReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 学生表格 -->
    <el-table 
      ref="studentTableRef"
      :data="studentTableData" 
      v-loading="studentTableLoading"
      border
      @selection-change="handleStudentSelectionChange"
      style="margin-top: 20px; max-height: 400px; overflow-y: auto;">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="classNo" label="班号" show-overflow-tooltip align="center" />
      <el-table-column prop="stuNo" label="学号" show-overflow-tooltip align="center" />
      <el-table-column prop="realName" label="姓名" show-overflow-tooltip align="center" />
    </el-table>

    <!-- 分页 -->
    <pagination 
      @size-change="studentSizeChangeHandle" 
      @current-change="studentCurrentChangeHandle" 
      v-bind="studentPagination"
      style="margin-top: 20px" />

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="studentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmStudentSelection">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="StuInnerLeaveApplyGroupFormDialog">
import { ref, reactive, nextTick, onMounted, computed } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/stuinnerleaveapplygroup'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { fetchList as getStudentList } from '/@/api/basic/basicstudent'

const emit = defineEmits(['refresh'])

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

// 学生选择弹窗相关
const studentDialogVisible = ref(false)
const studentTableLoading = ref(false)
const studentTableData = ref<any[]>([])
const selectedStudentRows = ref<any[]>([]) // 表格中选中的行
const studentSearchForm = reactive({
  classNo: '',
  stuNo: '',
  realName: ''
})
const studentPagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
})

// 已选学生文本显示
const selectedStudentsText = computed(() => {
  if (!form.selectedStudents || form.selectedStudents.length === 0) {
    return ''
  }
  return `已选择 ${form.selectedStudents.length} 名学生`
})

// 提交表单数据
const form = reactive({
  id: '',
  startTime: '',
  endTime: '',
  classCode: '',
  selectedStudents: [] as string[], // 选中的学号数组
  reason: '',
  stuList: [] as any[]
})

// 定义校验规则
const dataRules = {
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  classCode: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  selectedStudents: [
    { required: true, message: '请至少选择一个学生', trigger: 'change', type: 'array', min: 1 }
  ],
  reason: [
    { required: true, message: '请输入请假事由', trigger: 'blur' }
  ]
}

// 打开学生选择弹窗
const openStudentDialog = () => {
  if (!form.classCode) {
    useMessage().warning('请先选择班级')
    return
  }
  studentDialogVisible.value = true
  // 重置搜索表单，但保留班级代码
  studentSearchForm.classNo = ''
  studentSearchForm.stuNo = ''
  studentSearchForm.realName = ''
  // 加载学生列表
  loadStudentTableData()
}

// 加载学生表格数据
const loadStudentTableData = async () => {
  studentTableLoading.value = true
  try {
    const params: any = {
      current: studentPagination.currentPage,
      size: studentPagination.pageSize,
      classCode: form.classCode
    }
    
    // 添加搜索条件
    if (studentSearchForm.classNo) {
      params.classNo = studentSearchForm.classNo
    }
    if (studentSearchForm.stuNo) {
      params.stuNo = studentSearchForm.stuNo
    }
    if (studentSearchForm.realName) {
      params.realName = studentSearchForm.realName
    }
    
    const res = await getStudentList(params)
    if (res.data) {
      studentTableData.value = res.data.records || []
      studentPagination.total = res.data.total || 0
      
      // 如果有已选中的学生，自动勾选
      nextTick(() => {
        if (form.selectedStudents && form.selectedStudents.length > 0 && studentTableRef.value) {
          studentTableData.value.forEach((row: any) => {
            if (form.selectedStudents.includes(row.stuNo)) {
              studentTableRef.value.toggleRowSelection(row, true)
            }
          })
        }
      })
    } else {
      studentTableData.value = []
      studentPagination.total = 0
    }
  } catch (err) {
    studentTableData.value = []
    studentPagination.total = 0
  } finally {
    studentTableLoading.value = false
  }
}

// 学生搜索
const handleStudentSearch = () => {
  studentPagination.currentPage = 1
  loadStudentTableData()
}

// 学生搜索重置
const handleStudentReset = () => {
  studentSearchForm.classNo = ''
  studentSearchForm.stuNo = ''
  studentSearchForm.realName = ''
  studentPagination.currentPage = 1
  loadStudentTableData()
}

// 学生表格选择变化
const handleStudentSelectionChange = (selection: any[]) => {
  selectedStudentRows.value = selection
}

// 学生分页大小变化
const studentSizeChangeHandle = (size: number) => {
  studentPagination.pageSize = size
  studentPagination.currentPage = 1
  loadStudentTableData()
}

// 学生分页页码变化
const studentCurrentChangeHandle = (page: number) => {
  studentPagination.currentPage = page
  loadStudentTableData()
}

// 确认学生选择
const confirmStudentSelection = () => {
  if (selectedStudentRows.value.length === 0) {
    useMessage().warning('请至少选择一个学生')
    return
  }
  
  // 更新选中的学号数组
  form.selectedStudents = selectedStudentRows.value.map((row: any) => row.stuNo)
  studentDialogVisible.value = false
  useMessage().success(`已选择 ${form.selectedStudents.length} 名学生`)
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.startTime = ''
    form.endTime = ''
    form.classCode = ''
    form.selectedStudents = []
    form.reason = ''
    form.stuList = []
    selectedStudentRows.value = []
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.startTime = row.startTime || ''
      form.endTime = row.endTime || ''
      form.reason = row.reason || ''
      
      // 获取详情以获取stuList和classCode
      if (row.id) {
        getDetailData(row.id)
      }
    }
  })
}

// 获取详情
const getDetailData = async (id: string) => {
  try {
    loading.value = true
    const res = await getDetail(id)
    if (res.data && Array.isArray(res.data) && res.data.length > 0) {
      const detail = res.data[0]
      form.stuList = detail.stuList || []
      
      // 如果有学生列表，提取学号和班级代码
      if (form.stuList.length > 0) {
        // 获取第一个学生的班级代码
        const firstStudent = form.stuList[0]
        if (firstStudent.classCode) {
          form.classCode = firstStudent.classCode
          // 设置选中的学生
          form.selectedStudents = form.stuList.map((stu: any) => stu.stuNo)
        }
      }
    }
  } catch (err) {
  } finally {
    loading.value = false
  }
}

// 提交表单
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
      }
    }
    
    // 构建stuList数组
    const buildStuList = async () => {
      if (!form.selectedStudents || form.selectedStudents.length === 0) {
        return []
      }
      
      // 需要重新获取学生信息来构建stuList
      try {
        const params: any = {
          current: 1,
          size: 1000,
          classCode: form.classCode
        }
        const res = await getStudentList(params)
        const allStudents = res.data?.records || []
        
        return form.selectedStudents.map((stuNo: string) => {
          const student = allStudents.find((s: any) => s.stuNo === stuNo)
          if (student) {
            return {
              stuNo: student.stuNo,
              realName: student.realName,
              classCode: form.classCode,
              status: '0', // 审核状态，默认0
              inOut: student.inOut || '1' // 是否允许离校，默认1
            }
          }
          return null
        }).filter((item: any) => item !== null)
      } catch (err) {
        return []
      }
    }
    
    loading.value = true
    try {
      const stuList = await buildStuList()
      
      if (stuList.length === 0) {
        useMessage().error('请至少选择一个学生')
        loading.value = false
        return
      }
      
      const submitData: any = {
        startTime: form.startTime,
        endTime: form.endTime,
        reason: form.reason,
        stuList: stuList
      }
      
      // 编辑时需要包含id
      if (operType.value === 'edit') {
        submitData.id = form.id
      }
      
      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 getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data) {
      classList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    classList.value = []
  }
}

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

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

