<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="schoolYear">
            <el-select 
              v-model="searchForm.schoolYear" 
              placeholder="请选择学年" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in schoolYearList"
                :key="item.year"
                :label="item.year"
                :value="item.year">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学期" prop="schoolTerm">
            <el-select 
              v-model="searchForm.schoolTerm" 
              placeholder="请选择学期" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in schoolTermList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="searchForm.deptCode" 
              placeholder="请选择学院" 
              clearable
              filterable
              style="width: 200px">
              <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="classNo">
            <el-input 
              v-model="searchForm.classNo" 
              placeholder="请输入班号" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="学号" prop="stuNo">
            <el-input 
              v-model="searchForm.stuNo" 
              placeholder="请输入学号" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="姓名" prop="realName">
            <el-input 
              v-model="searchForm.realName" 
              placeholder="请输入姓名" 
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="日期范围" prop="dateRange">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
              style="width: 240px" />
          </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">
              <el-button 
                icon="FolderAdd" 
                type="primary" 
                @click="formDialogRef.openDialog()">
                新增
              </el-button>
              <el-button 
                icon="User" 
                type="success" 
                class="ml10" 
                @click="teacherDialogRef.openDialog()">
                指定带班教师
              </el-button>
              <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" 
              show-overflow-tooltip
              align="center"
              :min-width="col.minWidth"
              :width="col.width">
              <template #header>
                <el-icon><component :is="columnConfigMap[col.prop || '']?.icon || Calendar" /></el-icon>
                <span style="margin-left: 4px">{{ col.label }}</span>
              </template>
            <!-- 学期列特殊模板 -->
            <template v-if="col.prop === 'schoolTerm'" #default="scope">
              <el-tag size="small" type="primary" effect="plain">
                {{ formatSchoolTerm(scope.row.schoolTerm) }}
              </el-tag>
            </template>
            <!-- 工学交替开始时间列特殊模板 -->
            <template v-else-if="col.prop === 'startTime'" #default="scope">
              <span>{{ scope.row.startTime ? scope.row.startTime.split(' ')[0] : '-' }}</span>
            </template>
            <!-- 工学交替结束时间列特殊模板 -->
            <template v-else-if="col.prop === 'endTime'" #default="scope">
              <span>{{ scope.row.endTime ? scope.row.endTime.split(' ')[0] : '-' }}</span>
            </template>
            <!-- 带班教师列特殊模板 -->
            <template v-else-if="col.prop === 'attendanceTeacherName'" #default="scope">
              <span>{{ scope.row.attendanceTeacherName || '-' }}</span>
            </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button 
                icon="Delete" 
                link 
                type="danger" 
                @click="handleDelete(scope.row)">
                删除
              </el-button>
            </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>

    <!-- 新增表单弹窗 -->
    <form-dialog ref="formDialogRef" @refresh="getDataList" />

    <!-- 指定带班教师弹窗 -->
    <teacher-dialog ref="teacherDialogRef" @refresh="getDataList" />
  </div>
</template>

<script setup lang="ts" name="StuWorkStudyAlternate">
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj } from "/@/api/stuwork/stuworkstudyalternate";
import { getDeptList } from "/@/api/basic/basicclass";
import { queryAllSchoolYear } from "/@/api/basic/basicyear";
import { getDicts } from "/@/api/admin/dict";
import { useMessage, useMessageBox } from "/@/hooks/message";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import FormDialog from './form.vue'
import TeacherDialog from './teacher.vue'
import { List, Calendar, Clock, OfficeBuilding, CreditCard, Avatar, Grid, UserFilled, Setting, Menu, Search, Document } 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[]>([])
const schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const formDialogRef = ref()
const teacherDialogRef = ref()

// 表格列配置
const tableColumns = [
  { prop: 'schoolYear', label: '学年' },
  { prop: 'schoolTerm', label: '学期' },
  { prop: 'deptName', label: '系部名称' },
  { prop: 'stuNo', label: '学号' },
  { prop: 'realName', label: '姓名' },
  { prop: 'classNo', label: '班号' },
  { prop: 'className', label: '班级简称' },
  { prop: 'startTime', label: '工学交替开始时间', width: 180 },
  { prop: 'endTime', label: '工学交替结束时间', width: 180 },
  { prop: 'attendanceTeacherName', label: '带班教师' }
]

// 列配置映射（用于图标显示）
const columnConfigMap: Record<string, { icon: any }> = {
  schoolYear: { icon: Calendar },
  schoolTerm: { icon: Clock },
  deptName: { icon: OfficeBuilding },
  stuNo: { icon: CreditCard },
  realName: { icon: Avatar },
  classNo: { icon: Grid },
  className: { icon: Grid },
  startTime: { icon: Calendar },
  endTime: { icon: Calendar },
  attendanceTeacherName: { icon: UserFilled }
}

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

// 搜索表单
const searchForm = reactive({
  schoolYear: '',
  schoolTerm: '',
  deptCode: '',
  classNo: '',
  stuNo: '',
  realName: '',
  dateRange: null as [string, string] | null
})

// 配置 useTable（接口返回 data.tableData.records / data.tableData.total，需包装以适配 hook 的 res.data[props.item] 取数）
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: searchForm,
  pageList: async (params: any) => {
    const res = await fetchList(params)
    const data = res?.data
    const tableData = data?.tableData
    return {
      data: {
        'tableData.records': tableData?.records ?? [],
        'tableData.total': tableData?.total ?? data?.total ?? 0
      }
    }
  },
  props: {
    item: 'tableData.records',
    totalCount: 'tableData.total'
  },
  createdIsNeed: true
})

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

// 查询
const handleSearch = () => {
  // 处理日期范围
  const params: any = { ...searchForm }
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    params.dateRangeStr = `${searchForm.dateRange[0]},${searchForm.dateRange[1]}`
  }
  delete params.dateRange
  
  // 处理学年数组
  if (params.schoolYear) {
    params.schoolYear = [params.schoolYear]
  }
  
  // 更新查询参数
  Object.assign(searchForm, params)
  getDataList()
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  searchForm.schoolYear = ''
  searchForm.schoolTerm = ''
  searchForm.deptCode = ''
  searchForm.classNo = ''
  searchForm.stuNo = ''
  searchForm.realName = ''
  searchForm.dateRange = null
  getDataList()
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await useMessageBox().confirm('确定要删除这条记录吗？')
    await delObj([row.id])
    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) {
    deptList.value = []
  }
}

// 获取学年列表
const getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data && Array.isArray(res.data)) {
      schoolYearList.value = res.data
    }
  } catch (err) {
    schoolYearList.value = []
  }
}

// 获取学期列表
const getSchoolTermList = async () => {
  try {
    const res = await getDicts('school_term')
    if (res.data && Array.isArray(res.data)) {
      schoolTermList.value = res.data.map((item: any) => ({
        label: item.label ?? item.dictLabel ?? item.name,
        value: item.value ?? item.dictValue ?? item.code
      }))
    } else {
      schoolTermList.value = []
    }
  } catch (err) {
    schoolTermList.value = []
  }
}

// 学期列展示：按字典转成文案
const formatSchoolTerm = (value: string | number) => {
  if (value === '' || value == null) return '-'
  const item = schoolTermList.value.find((t: any) => String(t.value) === String(value))
  return item ? item.label : value
}

// 初始化
onMounted(() => {
  getDeptListData()
  getSchoolYearList()
  getSchoolTermList()
  nextTick(() => {
    if (visibleColumns.value.length === 0) {
    }
  })
})
</script>

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

