<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="graduYear">
            <el-select
              v-model="searchForm.graduYear"
              placeholder="请选择毕业年份"
              clearable
              filterable
              style="width: 140px">
              <el-option
                v-for="y in graduYearOptions"
                :key="y"
                :label="y + '年'"
                :value="y" />
            </el-select>
          </el-form-item>
          <el-form-item label="毕业状态" prop="status">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择"
              clearable
              style="width: 140px">
              <el-option label="待确认" value="0" />
              <el-option label="确认毕业" value="1" />
              <el-option label="不可毕业" value="-1" />
            </el-select>
          </el-form-item>
          <el-form-item label="毕业类型" prop="type">
            <el-select
              v-model="searchForm.type"
              placeholder="请选择"
              clearable
              style="width: 120px">
              <el-option label="段段清" value="1" />
              <el-option label="正常毕业" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="学号" prop="stuNo">
            <el-input
              v-model="searchForm.stuNo"
              placeholder="请输入学号"
              clearable
              style="width: 140px" />
          </el-form-item>
          <el-form-item label="姓名" prop="realName">
            <el-input
              v-model="searchForm.realName"
              placeholder="请输入姓名"
              clearable
              style="width: 120px" />
          </el-form-item>
          <el-form-item label="学院" prop="deptCode">
            <el-select
              v-model="searchForm.deptCode"
              placeholder="请选择学院"
              clearable
              filterable
              style="width: 160px">
              <el-option
                v-for="item in deptList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="班号" prop="classNo">
            <el-input
              v-model="searchForm.classNo"
              placeholder="请输入班号"
              clearable
              style="width: 120px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 内容卡片 -->
      <el-card class="content-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Document /></el-icon>
              毕业学生名单
            </span>
            <div class="header-actions">
              <right-toolbar
                v-model:showSearch="showSearch"
                class="ml10"
                @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>
          </div>
        </template>

        <!-- 表格 -->
        <el-table
          :data="state.dataList"
          v-loading="state.loading"
          stripe
          :cell-style="tableStyle.cellStyle"
          :header-cell-style="tableStyle.headerCellStyle"
          class="modern-table">
          <el-table-column type="index" label="序号" width="70" align="center">
            <template #header>
              <el-icon><List /></el-icon>
            </template>
            <template #default="{ $index }">
              {{ $index + 1 + ((state.pagination?.current || 1) - 1) * (state.pagination?.size || 10) }}
            </template>
          </el-table-column>
          <template v-for="col in visibleColumnsSorted" :key="col.prop || col.label">
            <el-table-column
              v-if="checkColumnVisible(col.prop || '') && col.prop !== '操作'"
              :prop="col.prop"
              :label="col.label"
              :min-width="col.minWidth"
              :width="col.width"
              show-overflow-tooltip
              align="center">
              <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 v-if="col.prop === 'status'" #default="scope">
                <el-tag :type="statusTagType(scope.row.status)" size="small">
                  {{ formatStatus(scope.row.status) }}
                </el-tag>
              </template>
              <template v-else-if="col.prop === 'type'" #default="scope">
                {{ scope.row.type === '1' ? '段段清' : scope.row.type === '2' ? '正常毕业' : scope.row.type || '-' }}
              </template>
            </el-table-column>
          </template>
          <template #empty>
            <el-empty description="暂无数据，请选择条件查询" :image-size="120" />
          </template>
        </el-table>

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

<script setup lang="ts" name="Stugraducheck">
import { reactive, ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from '/@/hooks/table'
import { fetchList } from '/@/api/stuwork/stugraducheck'
import { getDeptList } from '/@/api/basic/basicclass'
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import {
  List,
  Calendar,
  UserFilled,
  Document,
  Menu,
  Search,
  Grid
} from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

const route = useRoute()
const searchFormRef = ref()
const columnControlRef = ref<any>()
const showSearch = ref(true)
const deptList = ref<any[]>([])

// 毕业年份：当前年前后各 5 年
const graduYearOptions = computed(() => {
  const y = new Date().getFullYear()
  return Array.from({ length: 11 }, (_, i) => y - 5 + i)
})

// 表格列配置（与其它页面一致，icon 写在列上）
const tableColumns = [
  { prop: 'stuNo', label: '学号', icon: UserFilled },
  { prop: 'realName', label: '姓名', icon: UserFilled },
  { prop: 'classNo', label: '班号', icon: Grid },
  { prop: 'majorName', label: '专业名称', icon: Document, minWidth: 140 },
  { prop: 'graduYear', label: '毕业年份', icon: Calendar },
  { prop: 'status', label: '毕业状态', icon: Document },
  { prop: 'type', label: '毕业类型', icon: Document },
  { prop: 'scoreCondition', label: '学分情况', icon: Document, minWidth: 100 },
  { prop: 'skillCondition', label: '技能情况', icon: Document, minWidth: 100 },
  { prop: 'conductCondition', label: '操行情况', icon: Document, minWidth: 100 }
]

const {
  visibleColumns,
  visibleColumnsSorted,
  checkColumnVisible,
  handleColumnChange,
  handleColumnOrderChange
} = useTableColumnControl(tableColumns, route.path)

// 搜索表单（与接口文档一致：graduYear, status, type, stuNo, realName, deptCode, classCode 等）
const searchForm = reactive({
  graduYear: '',
  status: '',
  type: '',
  stuNo: '',
  realName: '',
  deptCode: '',
  classNo: ''
})

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

const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  tableStyle
} = useTable(state)

const formatStatus = (status: string) => {
  const map: Record<string, string> = { '0': '待确认', '1': '确认毕业', '-1': '不可毕业' }
  return map[status] || status || '-'
}

const statusTagType = (status: string) => {
  const map: Record<string, string> = { '0': 'warning', '1': 'success', '-1': 'danger' }
  return map[status] || 'info'
}

const handleSearch = () => {
  getDataList()
}

const handleReset = () => {
  searchFormRef.value?.resetFields()
  searchForm.graduYear = ''
  searchForm.status = ''
  searchForm.type = ''
  searchForm.stuNo = ''
  searchForm.realName = ''
  searchForm.deptCode = ''
  searchForm.classNo = ''
  getDataList()
}

const loadDeptList = async () => {
  try {
    const res = await getDeptList()
    deptList.value = Array.isArray(res.data) ? res.data : []
  } catch (err) {
    deptList.value = []
  }
}

onMounted(() => {
  loadDeptList()
})
</script>

<style scoped lang="scss">
@import '/@/assets/styles/modern-page.scss';
</style>
