<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="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>
            <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-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"
          @sort-change="sortChangeHandle">
          <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>
        <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 === 'headImg'">
            <el-image
              v-if="scope.row.headImg || scope.row.imageUrl || scope.row.qrCode"
              :src="scope.row.headImg || scope.row.imageUrl || scope.row.qrCode"
              :preview-src-list="[scope.row.headImg || scope.row.imageUrl || scope.row.qrCode]"
              fit="cover"
              style="width: 80px; height: 100px; cursor: pointer;"
              lazy>
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <span v-else>-</span>
          </template>
        </el-table-column>
        </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="BasicStudentAvatar">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList } from "/@/api/basic/basicstudentavatar";
import { getClassListByRole } from "/@/api/basic/basicclass";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import { Picture, List, Document, UserFilled, Grid, Menu, Search } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

// 定义变量内容
const route = useRoute()
const searchFormRef = ref()
const columnControlRef = ref()
const showSearch = ref(true)
const classList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'stuNo', label: '学号', icon: Document },
  { prop: 'realName', label: '姓名', icon: UserFilled },
  { prop: 'className', label: '班级', icon: Grid },
  { prop: 'headImg', label: '头像', icon: Picture, width: 120 }
]

// 使用表格列控制hook
const {
  visibleColumns,
  visibleColumnsSorted,
  checkColumnVisible,
  handleColumnChange,
  handleColumnOrderChange
} = useTableColumnControl(tableColumns)

// 搜索表单
const searchForm = reactive({
  classCode: ''
})

// 配置 useTable - 接口返回的数据结构是 { classes: [], students: [] }
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: searchForm,
  pageList: async (queryParams: any) => {
    const res = await fetchList(queryParams)
    // 接口返回的数据结构是 { classes: [], students: [] }
    // 需要将 students 数组转换为表格数据，并关联班级信息
    if (res.data && res.data.students) {
      const students = res.data.students || []
      const classes = res.data.classes || []
      const classMap = new Map()
      classes.forEach((cls: any) => {
        classMap.set(cls.classCode, cls)
      })
      
      // 将学生数据与班级信息合并
      const dataList = students.map((stu: any) => {
        const classInfo = classMap.get(stu.classCode)
        return {
          ...stu,
          className: classInfo ? classInfo.classNo : stu.className || '',
          classNo: classInfo ? classInfo.classNo : ''
        }
      })
      
      return {
        ...res,
        data: {
          records: dataList,
          total: dataList.length,
          current: 1,
          size: dataList.length,
          pages: 1
        }
      }
    }
    return res
  },
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true
})

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

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

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  searchForm.classCode = ''
  getDataList()
}

// 获取班级列表
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 = []
  }
}

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

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

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}
</style>
