<template>
  <div class="modern-page-container">
    <div class="page-wrapper">
      <!-- 搜索表单卡片 -->
      <el-card v-show="showSearch" class="search-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Search /></el-icon>
              筛选条件
            </span>
          </div>
        </template>
        <el-form :model="searchForm" ref="searchFormRef" :inline="true" @keyup.enter="handleSearch" class="search-form">
          <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-card>

      <!-- 操作按钮 -->
      <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">
            <TableColumnControl
              ref="columnControlRef"
              :columns="tableColumns"
              v-model="visibleColumns"
              trigger-type="default"
              trigger-circle
              @change="handleColumnChange"
              @order-change="handleColumnOrderChange"
            >
              <template #trigger>
                <el-tooltip class="item" effect="dark" content="列设置" placement="top">
                  <el-button circle style="margin-left: 0;">
                    <el-icon><Menu /></el-icon>
                  </el-button>
                </el-tooltip>
              </template>
            </TableColumnControl>
          </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">
          <template #header>
            <el-icon><List /></el-icon>
            <span style="margin-left: 4px;">序号</span>
          </template>
        </el-table-column>
        <el-table-column 
          v-for="col in visibleColumnsSorted" 
          :key="col.prop"
          :prop="col.prop" 
          :label="col.label" 
          :width="col.width"
          :min-width="col.minWidth"
          :show-overflow-tooltip="col.showOverflowTooltip !== false"
          :align="col.align">
          <template #header>
            <el-icon v-if="col.icon"><component :is="col.icon" /></el-icon>
            <span :style="{ marginLeft: col.icon ? '4px' : '0' }">{{ col.label }}</span>
          </template>
          <template #default="scope" v-if="col.prop === 'gender'">
            <GenderTag :gender="scope.row.gender" />
          </template>
          <template #default="scope" v-else-if="col.prop === 'education'">
            <el-tag v-if="getEducationLabel(scope.row.education)" size="small" type="info" effect="plain">
              {{ getEducationLabel(scope.row.education) }}
            </el-tag>
            <span v-else>-</span>
          </template>
          <template #default="scope" v-else-if="col.prop === 'isDorm'">
            <el-tag v-if="scope.row.isDorm === 1 || scope.row.isDorm === '1'" size="small" type="success" effect="plain">是</el-tag>
            <el-tag v-else-if="scope.row.isDorm === 0 || scope.row.isDorm === '0'" size="small" type="info" effect="plain">否</el-tag>
            <span v-else>-</span>
          </template>
          <template #default="scope" v-else-if="col.prop === 'enrollStatus'">
            <el-tag 
              v-if="getEnrollStatusLabel(scope.row.enrollStatus)" 
              size="small" 
              type="info" 
              effect="plain">
              {{ getEnrollStatusLabel(scope.row.enrollStatus) }}
            </el-tag>
            <span v-else>-</span>
          </template>
          <template #default="scope" v-else-if="col.prop === 'stuStatus'">
            <el-tag 
              v-if="getStuStatusLabel(scope.row.stuStatus)" 
              size="small" 
              :type="getStuStatusType(scope.row.stuStatus)" 
              effect="plain">
              {{ getStuStatusLabel(scope.row.stuStatus) }}
            </el-tag>
            <span v-else>-</span>
          </template>
          <template #default="scope" v-else-if="col.prop === 'isClassLeader'">
            <el-tag v-if="scope.row.isClassLeader == 1 || scope.row.isClassLeader === '1'" size="small" type="success" effect="plain">是</el-tag>
            <el-tag v-else-if="scope.row.isClassLeader == 0 || scope.row.isClassLeader === '0'" size="small" type="info" effect="plain">否</el-tag>
            <span v-else>-</span>
          </template>
          <template #default="scope" v-else-if="col.prop === 'isInout'">
            <el-tag v-if="scope.row.isInout === 1 || scope.row.isInout === '1'" size="small" type="success" effect="plain">是</el-tag>
            <el-tag v-else-if="scope.row.isInout === 0 || scope.row.isInout === '0'" size="small" type="danger" effect="plain">否</el-tag>
            <span v-else>-</span>
          </template>
          <template #default="scope" v-else-if="col.prop === 'completeRate'">
            <el-tag v-if="scope.row.completeRate !== undefined && scope.row.completeRate !== null" size="small" type="primary" effect="plain">
              {{ scope.row.completeRate }}%
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="300">
          <template #header>
            <el-icon><Setting /></el-icon>
            <span style="margin-left: 4px;">操作</span>
          </template>
          <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 { useRoute } from 'vue-router'
import { List, OfficeBuilding, Briefcase, Grid, Document, UserFilled, User, CreditCard, HomeFilled, School, CircleCheck, Phone, Location, Tickets, Medal, Lock, DataAnalysis, Setting, Menu } from '@element-plus/icons-vue'
import { getTableConfigFromLocal, saveTableConfigToLocal, updateUserTableConfig } from '/@/api/admin/usertable'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList } from "/@/api/basic/basicstudentinfo";
import { 
  delObj, 
  exportStudentData,
  applyInternship,
  getDownPic,
  preBatchPrint,
  importCertificate,
  exportStuInfoCard,
  exportCertificate,
  resetPassWord,
  editIsleader,
  updateInout,
  updateStuSimpleInfo,
  prePrint
} from "/@/api/basic/basicstudent";
import { getDeptList, getClassListByRole } from "/@/api/basic/basicclass";
import { getDicts } from "/@/api/admin/dict";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { downBlobFile, adaptationUrl } from "/@/utils/other";
import { Session } from "/@/utils/storage";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import GenderTag from '/@/components/GenderTag/index.vue'

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

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

// 表格列配置
const tableColumns = [
  { prop: 'deptName', label: '学院', icon: OfficeBuilding },
  { prop: 'majorName', label: '专业', icon: Briefcase },
  { prop: 'className', label: '班级', icon: Grid },
  { prop: 'stuNo', label: '学号', icon: Document },
  { prop: 'realName', label: '姓名', icon: UserFilled },
  { prop: 'gender', label: '性别', icon: User, width: 80 },
  { prop: 'idCard', label: '身份证号', icon: CreditCard },
  { prop: 'teacherNo', label: '班主任', icon: UserFilled },
  { prop: 'isDorm', label: '住宿', icon: HomeFilled, width: 80 },
  { prop: 'education', label: '文化程度', icon: School },
  { prop: 'enrollStatus', label: '学籍状态', icon: CircleCheck },
  { prop: 'phone', label: '个人电话', icon: Phone },
  { prop: 'householdAddress', label: '户籍所在地', icon: Location },
  { prop: 'stuStatus', label: '学生状态', icon: Tickets },
  { prop: 'isClassLeader', label: '是否班干部', icon: Medal, width: 100 },
  { prop: 'isInout', label: '是否允许进出', icon: Lock, width: 120 },
  { prop: 'completeRate', label: '资料完成度', icon: DataAnalysis, width: 120 }
]

// 当前显示的列
const visibleColumns = ref<string[]>([])
// 列排序顺序
const columnOrder = ref<string[]>([])

// 从本地统一存储加载配置
const loadSavedConfig = () => {
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  const savedConfig = getTableConfigFromLocal(storageKey)
  
  if (savedConfig && savedConfig.visibleColumns) {
    const validColumns = tableColumns.map(col => col.prop || col.label)
    const filteredSaved = savedConfig.visibleColumns.filter((col: string) => validColumns.includes(col))
    visibleColumns.value = filteredSaved.length > 0 ? filteredSaved : validColumns
  } else {
    visibleColumns.value = tableColumns.map(col => col.prop || col.label)
  }
  
  if (savedConfig && savedConfig.columnOrder) {
    const validColumns = tableColumns.map(col => col.prop || col.label)
    columnOrder.value = savedConfig.columnOrder.filter((key: string) => validColumns.includes(key))
    validColumns.forEach(key => {
      if (!columnOrder.value.includes(key)) {
        columnOrder.value.push(key)
      }
    })
  } else {
    columnOrder.value = tableColumns.map(col => col.prop || col.label)
  }
}

// 列变化处理
const handleColumnChange = (value: string[]) => {
  visibleColumns.value = value
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  const selectableColumns = value.filter(col => {
    const column = tableColumns.find(c => (c.prop || c.label) === col)
    return column && !column.alwaysShow && !column.fixed
  })
  // 保存到本地统一存储
  saveTableConfigToLocal(storageKey, { visibleColumns: selectableColumns })
  // 异步保存到后端
  updateUserTableConfig(storageKey, { visibleColumns: selectableColumns }).catch(() => {})
}

// 列排序变化处理
const handleColumnOrderChange = (order: string[]) => {
  columnOrder.value = order
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  // 保存到本地统一存储
  saveTableConfigToLocal(storageKey, { columnOrder: order })
  // 异步保存到后端
  updateUserTableConfig(storageKey, { columnOrder: order }).catch(() => {})
}

// 排序后的表格列
const visibleColumnsSorted = computed(() => {
  const columns = tableColumns.filter(col => {
    const key = col.prop || col.label
    return visibleColumns.value.includes(key)
  })
  
  if (columnOrder.value.length > 0) {
    const orderedColumns: any[] = []
    const unorderedColumns: any[] = []
    
    columnOrder.value.forEach(key => {
      const col = columns.find(c => (c.prop || c.label) === key)
      if (col) {
        orderedColumns.push(col)
      }
    })
    
    columns.forEach(col => {
      const key = col.prop || col.label
      if (!columnOrder.value.includes(key)) {
        unorderedColumns.push(col)
      }
    })
    
    return [...orderedColumns, ...unorderedColumns]
  }
  
  return columns
})

// 搜索表单
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 () => {
  useMessage().warning('功能开发中')
}

// 申请顶岗
const handleApplyInternship = async () => {
  useMessage().warning('功能开发中')
}

// 导出头像
const handleExportAvatar = async () => {
  useMessage().warning('功能开发中')
}

// 批量打印
const handleBatchPrint = async () => {
  useMessage().warning('功能开发中')
}

// 段段清证书导入
const handleImportCertificate = () => {
  useMessage().warning('功能开发中')
}

// 上传相关
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 () => {
  useMessage().warning('功能开发中')
}

// 证书导出
const handleExportCertificate = async () => {
  useMessage().warning('功能开发中')
}

// 简单信息维护
const handleSimpleEdit = (row: any) => {
  useMessage().warning('功能开发中')
}

// 查看详情
const handleViewDetail = (row: any) => {
  useMessage().warning('功能开发中')
}

// 打印证件照
const handlePrintPhoto = async (row: any) => {
  useMessage().warning('功能开发中')
}

// 重置密码
const handleResetPassword = async (row: any) => {
  useMessage().warning('功能开发中')
}

// 设为班干部
const handleSetLeader = async (row: any) => {
  useMessage().warning('功能开发中')
}

// 取消班干部
const handleCancelLeader = async (row: any) => {
  useMessage().warning('功能开发中')
}

// 禁止进出
const handleForbidInout = async (row: any) => {
  useMessage().warning('功能开发中')
}

// 获取学院列表
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 getDicts('enroll_status')
    if (res.data) {
      if (Array.isArray(res.data)) {
        // 确保数据格式统一为 {label, value}
        statusList.value = res.data.map((item: any) => ({
          label: item.label || item.name || item.dictLabel || item.text || '',
          value: String(item.value || item.code || item.dictValue || item.id || '')
        })).filter((item: any) => item.label && item.value !== undefined && item.value !== null && item.value !== '')
      } else {
        statusList.value = []
      }
    }
  } catch (err) {
    console.error('获取学籍状态列表失败', err)
    statusList.value = []
  }
}

// 获取文化程度字典
const getEducationListData = async () => {
  try {
    const res = await getDicts('pre_school_education')
    if (res.data && Array.isArray(res.data)) {
      educationList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      educationList.value = []
    }
  } catch (err) {
    console.error('获取文化程度字典失败', err)
    educationList.value = []
  }
}

// 获取学生状态列表
const getStuStatusListData = async () => {
  try {
    const res = await getDicts('student_status')
    if (res.data) {
      if (Array.isArray(res.data)) {
        // 确保数据格式统一为 {label, value, type}
        stuStatusList.value = res.data.map((item: any) => ({
          label: item.label || item.name || item.dictLabel || item.text || '',
          value: String(item.value || item.code || item.dictValue || item.id || ''),
          type: item.type || 'info'
        })).filter((item: any) => item.label && item.value !== undefined && item.value !== null && item.value !== '')
      } else {
        stuStatusList.value = []
      }
    }
  } catch (err) {
    console.error('获取学生状态列表失败', err)
    stuStatusList.value = []
  }
}

// 根据学籍状态值获取标签
const getEnrollStatusLabel = (value: any) => {
  if (value === undefined || value === null || value === '') return ''
  const status = statusList.value.find(item => String(item.value) === String(value))
  return status ? status.label : ''
}

// 根据文化程度值获取标签
const getEducationLabel = (value: any) => {
  if (value === undefined || value === null || value === '') return ''
  const item = educationList.value.find(i => String(i.value) === String(value))
  return item ? item.label : ''
}

// 根据学生状态值获取标签
const getStuStatusLabel = (value: any) => {
  if (value === undefined || value === null || value === '') return ''
  const status = stuStatusList.value.find(item => String(item.value) === String(value))
  return status ? status.label : ''
}

// 根据学生状态值获取标签类型
const getStuStatusType = (value: any) => {
  if (value === undefined || value === null || value === '') return 'info'
  const status = stuStatusList.value.find(item => String(item.value) === String(value))
  return status ? (status.type || 'info') : 'info'
}

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