<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <el-row v-show="showSearch">
        <el-form :model="searchForm" ref="searchFormRef" :inline="true" @keyup.enter="handleSearch">
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="searchForm.deptCode" 
              placeholder="请选择学院" 
              clearable
              filterable
              style="width: 200px"
              @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-form-item label="班级" prop="classCode">
            <el-select 
              v-model="searchForm.classCode" 
              placeholder="请选择班级" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班级状态" prop="classStatus">
            <el-select 
              v-model="searchForm.classStatus" 
              placeholder="请选择班级状态" 
              clearable
              style="width: 200px">
              <el-option label="正常" value="0" />
              <el-option label="离校" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否住宿" prop="isDorm">
            <el-select 
              v-model="searchForm.isDorm" 
              placeholder="请选择是否住宿" 
              clearable
              style="width: 200px">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="学籍状态" prop="status">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择学籍状态" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="借读学年" prop="borrowYear">
            <el-input 
              v-model="searchForm.borrowYear" 
              placeholder="请输入借读学年" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="学生状态" prop="stuStatus">
            <el-select 
              v-model="searchForm.stuStatus" 
              placeholder="请选择学生状态" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in stuStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="停车证" prop="parkingCard">
            <el-select 
              v-model="searchForm.parkingCard" 
              placeholder="请选择停车证" 
              clearable
              style="width: 200px">
              <el-option label="有" value="1" />
              <el-option label="无" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="完成度" prop="completion">
            <el-input 
              v-model="searchForm.completion" 
              placeholder="请输入完成度" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="联院班" prop="isUnionClass">
            <el-select 
              v-model="searchForm.isUnionClass" 
              placeholder="请选择联院班" 
              clearable
              style="width: 200px">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名/学号/身份证号" prop="keyword">
            <el-input 
              v-model="searchForm.keyword" 
              placeholder="请输入姓名/学号/身份证号" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain icon="Search" @click="handleSearch">查询</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button 
            icon="FolderAdd" 
            type="primary" 
            class="ml10" 
            @click="formDialogRef.openDialog()">
            新 增
          </el-button>
          <el-button 
            icon="Download" 
            type="success" 
            class="ml10" 
            @click="handleExportStudent">
            学生信息导出
          </el-button>
          <el-button 
            icon="Document" 
            type="warning" 
            class="ml10" 
            @click="handleApplyInternship">
            申请顶岗
          </el-button>
          <el-button 
            icon="Picture" 
            type="info" 
            class="ml10" 
            @click="handleExportAvatar">
            导出头像
          </el-button>
          <el-button 
            icon="Printer" 
            type="primary" 
            plain
            class="ml10" 
            @click="handleBatchPrint">
            批量打印
          </el-button>
          <el-button 
            icon="Upload" 
            type="success" 
            plain
            class="ml10" 
            @click="handleImportCertificate">
            段段清证书导入
          </el-button>
          <el-button 
            icon="Document" 
            type="warning" 
            plain
            class="ml10" 
            @click="handleExportStudentCard">
            学籍卡导出
          </el-button>
          <el-button 
            icon="Tickets" 
            type="info" 
            plain
            class="ml10" 
            @click="handleExportCertificate">
            证书导出
          </el-button>
          <right-toolbar  
            v-model:showSearch="showSearch" 
            class="ml10 mr20"
            style="float: right;"
            @queryTable="getDataList">
          </right-toolbar>
        </div>
      </el-row>

      <!-- 表格 -->
      <el-table 
        :data="state.dataList" 
        v-loading="state.loading" 
        border 
        :cell-style="tableStyle.cellStyle" 
        :header-cell-style="tableStyle.headerCellStyle"
        @sort-change="sortChangeHandle"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" align="center" />
        <el-table-column prop="deptName" label="学院" show-overflow-tooltip />
        <el-table-column prop="majorName" label="专业" show-overflow-tooltip />
        <el-table-column prop="className" label="班级" show-overflow-tooltip />
        <el-table-column prop="stuNo" label="学号" show-overflow-tooltip />
        <el-table-column prop="realName" label="姓名" show-overflow-tooltip />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="scope">
            <span>{{ scope.row.gender === '1' || scope.row.gender === 1 ? '男' : scope.row.gender === '0' || scope.row.gender === 0 ? '女' : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号" show-overflow-tooltip />
        <el-table-column prop="teacherNo" label="班主任" show-overflow-tooltip />
        <el-table-column prop="isDorm" label="住宿" width="80" align="center">
          <template #default="scope">
            <span>{{ scope.row.isDorm === 1 || scope.row.isDorm === '1' ? '是' : scope.row.isDorm === 0 || scope.row.isDorm === '0' ? '否' : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="education" label="文化程度" show-overflow-tooltip />
        <el-table-column prop="enrollStatus" label="学籍状态" show-overflow-tooltip />
        <el-table-column prop="phone" label="个人电话" show-overflow-tooltip />
        <el-table-column prop="householdAddress" label="户籍所在地" show-overflow-tooltip />
        <el-table-column prop="stuStatus" label="学生状态" show-overflow-tooltip />
        <el-table-column prop="isClassLeader" label="是否班干部" width="100" align="center">
          <template #default="scope">
            <span>{{ scope.row.isClassLeader == 1 || scope.row.isClassLeader === '1' ? '是' : scope.row.isClassLeader == 0 || scope.row.isClassLeader === '0' ? '否' : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isInout" label="是否允许进出" width="120" align="center">
          <template #default="scope">
            <span>{{ scope.row.isInout === 1 || scope.row.isInout === '1' ? '是' : scope.row.isInout === 0 || scope.row.isInout === '0' ? '否' : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="completeRate" label="资料完成度" width="120" align="center">
          <template #default="scope">
            <span>{{ scope.row.completeRate || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="300">
          <template #default="scope">
            <el-button 
              icon="Edit" 
              text 
              type="primary" 
              @click="handleSimpleEdit(scope.row)">
              简单信息维护
            </el-button>
            <el-button 
              icon="View" 
              text 
              type="primary" 
              @click="handleViewDetail(scope.row)">
              详情
            </el-button>
            <el-button 
              icon="Picture" 
              text 
              type="primary" 
              @click="handlePrintPhoto(scope.row)">
              打印证件照
            </el-button>
            <el-button 
              icon="Key" 
              text 
              type="warning" 
              @click="handleResetPassword(scope.row)">
              重置密码
            </el-button>
            <el-button 
              v-if="scope.row.isClassLeader == 1 || scope.row.isClassLeader === '1'"
              icon="User" 
              text 
              type="danger" 
              @click="handleCancelLeader(scope.row)">
              取消班干部
            </el-button>
            <el-button 
              v-else
              icon="User" 
              text 
              type="success" 
              @click="handleSetLeader(scope.row)">
              设为班干部
            </el-button>
            <el-button 
              icon="Lock" 
              text 
              type="danger" 
              @click="handleForbidInout(scope.row)">
              禁止进出
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination 
        @size-change="sizeChangeHandle" 
        @current-change="currentChangeHandle" 
        v-bind="state.pagination" />
    </div>

    <!-- 编辑、新增  -->
    <FormDialog ref="formDialogRef" @refresh="getDataList(false)" />
    
    <!-- 学生详情 -->
    <DetailDialog ref="detailDialogRef" />
    
    <!-- 简单信息维护对话框 -->
    <SimpleEditDialog ref="simpleEditDialogRef" @refresh="getDataList(false)" />
    
    <!-- 段段清证书导入对话框 -->
    <el-dialog 
      title="段段清证书导入" 
      v-model="importCertificateDialogVisible"
      :close-on-click-modal="false" 
      draggable
      width="500px">
      <el-upload
        ref="uploadRef"
        :action="uploadAction"
        :headers="uploadHeaders"
        :data="uploadData"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :auto-upload="false"
        accept=".xlsx,.xls">
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button type="success" @click="submitUpload" :loading="uploadLoading">上传</el-button>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importCertificateDialogVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="BasicStudent">
import { ref, reactive, defineAsyncComponent, computed, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { 
  fetchList, 
  delObj, 
  exportStudentData,
  applyInternship,
  getDownPic,
  preBatchPrint,
  importCertificate,
  exportStuInfoCard,
  exportCertificate,
  resetPassWord,
  editIsleader,
  updateInout,
  updateStuSimpleInfo,
  getStuStatus,
  prePrint
} from "/@/api/basic/basicstudent";
import { getDeptList, getClassListByRole } from "/@/api/basic/basicclass";
import { queryDictByTypeList } from "/@/api/admin/dict";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { downBlobFile, adaptationUrl } from "/@/utils/other";
import { Session } from "/@/utils/storage";

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const DetailDialog = defineAsyncComponent(() => import('./detail.vue'));
const SimpleEditDialog = defineAsyncComponent(() => import('./components/SimpleEdit.vue'));

// 定义变量内容
const formDialogRef = ref()
const detailDialogRef = ref()
const simpleEditDialogRef = ref()
const searchFormRef = ref()
const uploadRef = ref()
const showSearch = ref(true)
const deptList = ref<any[]>([])
const classList = ref<any[]>([])
const statusList = ref<any[]>([])
const stuStatusList = ref<any[]>([])
const selectedRows = ref<any[]>([])
const importCertificateDialogVisible = ref(false)
const uploadLoading = ref(false)
const fileList = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  deptCode: '',
  classCode: '',
  classStatus: '',
  isDorm: '',
  status: '',
  borrowYear: '',
  stuStatus: '',
  parkingCard: '',
  completion: '',
  isUnionClass: '',
  keyword: ''
})

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: searchForm,
  pageList: fetchList,
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true
})

// table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  tableStyle
} = useTable(state)

// 学院选择变化
const handleDeptChange = () => {
  // 可以根据需要清空班级选择
  searchForm.classCode = ''
}

// 查询
const handleSearch = () => {
  getDataList()
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  Object.assign(searchForm, {
    deptCode: '',
    classCode: '',
    classStatus: '',
    isDorm: '',
    status: '',
    borrowYear: '',
    stuStatus: '',
    parkingCard: '',
    completion: '',
    isUnionClass: '',
    keyword: ''
  })
  getDataList()
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 学生信息导出
const handleExportStudent = async () => {
  try {
    await exportStudentData(searchForm)
    useMessage().success('导出成功')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  }
}

// 申请顶岗
const handleApplyInternship = async () => {
  if (selectedRows.value.length === 0) {
    useMessage().warning('请先选择学生')
    return
  }
  try {
    const stuNos = selectedRows.value.map((row: any) => row.stuNo)
    await applyInternship({ stuNos })
    useMessage().success('申请成功')
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg || '申请失败')
  }
}

// 导出头像
const handleExportAvatar = async () => {
  try {
    const params: any = { ...searchForm }
    if (selectedRows.value.length > 0) {
      params.stuNos = selectedRows.value.map((row: any) => row.stuNo)
    }
    await getDownPic(params)
    useMessage().success('导出成功')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  }
}

// 批量打印
const handleBatchPrint = async () => {
  if (selectedRows.value.length === 0) {
    useMessage().warning('请先选择学生')
    return
  }
  try {
    const stuNos = selectedRows.value.map((row: any) => row.stuNo)
    await preBatchPrint({ stuNos })
    useMessage().success('打印准备成功')
  } catch (err: any) {
    useMessage().error(err.msg || '打印准备失败')
  }
}

// 段段清证书导入
const handleImportCertificate = () => {
  importCertificateDialogVisible.value = true
  fileList.value = []
}

// 上传相关
const uploadAction = computed(() => {
  return adaptationUrl('/basic/basicstudent/importCertificate')
})

const uploadHeaders = computed(() => {
  return {
    'Authorization': `Bearer ${Session.getToken()}`
  }
})

const uploadData = computed(() => {
  return {}
})

const beforeUpload = (file: any) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    useMessage().error('只能上传 Excel 文件')
    return false
  }
  return true
}

const submitUpload = () => {
  uploadRef.value?.submit()
}

const handleUploadSuccess = (response: any) => {
  uploadLoading.value = false
  useMessage().success('导入成功')
  importCertificateDialogVisible.value = false
  getDataList()
}

const handleUploadError = (err: any) => {
  uploadLoading.value = false
  useMessage().error('导入失败')
}

// 学籍卡导出
const handleExportStudentCard = async () => {
  try {
    const params: any = { ...searchForm }
    if (selectedRows.value.length > 0) {
      params.stuNos = selectedRows.value.map((row: any) => row.stuNo)
    }
    await exportStuInfoCard(params)
    useMessage().success('导出成功')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  }
}

// 证书导出
const handleExportCertificate = async () => {
  try {
    const params: any = { ...searchForm }
    if (selectedRows.value.length > 0) {
      params.stuNos = selectedRows.value.map((row: any) => row.stuNo)
    }
    await exportCertificate(params)
    useMessage().success('导出成功')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  }
}

// 简单信息维护
const handleSimpleEdit = (row: any) => {
  if (simpleEditDialogRef.value) {
    simpleEditDialogRef.value.openDialog(row)
  }
}

// 查看详情
const handleViewDetail = (row: any) => {
  if (detailDialogRef.value) {
    detailDialogRef.value.openDialog(row.id)
  }
}

// 打印证件照
const handlePrintPhoto = async (row: any) => {
  try {
    await prePrint(row.stuNo)
    useMessage().success('打印准备成功')
  } catch (err: any) {
    useMessage().error(err.msg || '打印准备失败')
  }
}

// 重置密码
const handleResetPassword = async (row: any) => {
  try {
    await useMessageBox().confirm('确定要重置该学生的密码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await resetPassWord({ stuNo: row.stuNo })
    useMessage().success('重置成功')
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '重置失败')
    }
  }
}

// 设为班干部
const handleSetLeader = async (row: any) => {
  try {
    await editIsleader({ id: row.id, isClassLeader: 1 })
    useMessage().success('设置成功')
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg || '设置失败')
  }
}

// 取消班干部
const handleCancelLeader = async (row: any) => {
  try {
    await editIsleader({ id: row.id, isClassLeader: 0 })
    useMessage().success('取消成功')
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg || '取消失败')
  }
}

// 禁止进出
const handleForbidInout = async (row: any) => {
  try {
    await useMessageBox().confirm('确定要禁止该学生进出吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await updateInout({ id: row.id, isAllowInout: 0 })
    useMessage().success('操作成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '操作失败')
    }
  }
}

// 获取学院列表
const getDeptListData = async () => {
  try {
    const res = await getDeptList()
    if (res.data) {
      deptList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取学院列表失败', err)
    deptList.value = []
  }
}

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

// 获取学籍状态列表
const getStatusListData = async () => {
  try {
    const res = await getStuStatus()
    if (res.data) {
      statusList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取学籍状态列表失败', err)
    statusList.value = []
  }
}

// 获取学生状态列表
const getStuStatusListData = async () => {
  try {
    // 先尝试使用批量字典接口
    const res = await queryDictByTypeList(['student_status'])
    
    // 尝试多种可能的数据结构
    let dictData = null
    if (res.data) {
      // 可能是 res.data.student_status
      if (res.data.student_status) {
        dictData = res.data.student_status
      }
      // 可能是 res.data['student_status']
      else if (res.data['student_status']) {
        dictData = res.data['student_status']
      }
      // 可能是直接返回数组
      else if (Array.isArray(res.data)) {
        dictData = res.data
      }
      // 可能是对象，键为 student_status
      else if (typeof res.data === 'object') {
        const keys = Object.keys(res.data)
        if (keys.length > 0) {
          dictData = res.data[keys[0]]
        }
      }
    }
    
    if (dictData && Array.isArray(dictData) && dictData.length > 0) {
      const parseDictList = (dictData: any) => {
        return dictData.map((item: any) => ({
          label: item.label || item.name || item.dictLabel || item.text || '',
          value: item.value || item.code || item.dictValue || item.id || ''
        })).filter((item: any) => item.label && item.value !== undefined && item.value !== null && item.value !== '')
      }
      stuStatusList.value = parseDictList(dictData)
      return
    }
  } catch (err) {
    console.error('批量字典接口获取学生状态失败', err)
  }
  
  // 如果批量字典接口失败或返回数据格式不对，使用原来的单个字典接口
  try {
    const fallbackRes = await getStuStatus()
    if (fallbackRes.data) {
      if (Array.isArray(fallbackRes.data)) {
        // 确保数据格式统一为 {label, value}
        stuStatusList.value = fallbackRes.data.map((item: any) => ({
          label: item.label || item.name || item.dictLabel || item.text || '',
          value: item.value || item.code || item.dictValue || item.id || ''
        })).filter((item: any) => item.label && item.value !== undefined && item.value !== null && item.value !== '')
      } else {
        stuStatusList.value = []
      }
    }
  } catch (fallbackErr) {
    console.error('获取学生状态列表失败', fallbackErr)
    stuStatusList.value = []
  }
}

// 初始化
onMounted(() => {
  getDeptListData()
  getClassListData()
  getStatusListData()
  getStuStatusListData()
})
</script>
