<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="oldClassCode">
            <el-select 
              v-model="searchForm.oldClassCode" 
              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="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="turnoverType">
            <el-select 
              v-model="searchForm.turnoverType" 
              placeholder="请选择异动类型" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in turnoverTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </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">
              <el-button 
                icon="FolderAdd" 
                type="primary" 
                @click="formDialogRef.openDialog()">
                批量新增异动
              </el-button>
              <el-button 
                icon="Download" 
                type="success" 
                class="ml10" 
                @click="handleExport">
                导出
              </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 === 'turnoverDate'" #default="scope">
              <span>{{ scope.row.turnoverDate ? formatDate(scope.row.turnoverDate) : '-' }}</span>
            </template>
            <!-- 异动类型列特殊模板 -->
            <template v-else-if="col.prop === 'turnoverType'" #default="scope">
              <el-tag size="small" type="warning" effect="plain">
                {{ formatTurnoverType(scope.row.turnoverType) }}
              </el-tag>
            </template>
            <!-- 转制类型列特殊模板 -->
            <template v-else-if="col.prop === 'turnYear'" #default="scope">
              <el-tag size="small" type="info" effect="plain">
                {{ formatTurnYear(scope.row.turnYear) }}
              </el-tag>
            </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="220" align="center" fixed="right">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button 
                icon="Edit" 
                link 
                type="primary" 
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button 
                icon="RefreshLeft" 
                link 
                type="warning" 
                @click="handleCancel(scope.row)">
                异动撤销
              </el-button>
              <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" />
  </div>
</template>

<script setup lang="ts" name="StuTurnover">
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj, cancelObj } from "/@/api/stuwork/stuturnover";
import { makeExportStudentChangeTask } from "/@/api/stuwork/file";
import { queryAllSchoolYear } from "/@/api/basic/basicyear";
import { getDicts } from "/@/api/admin/dict";
import { getDeptListByLevelTwo } from "/@/api/basic/basicdept";
import { list as getClassList } from "/@/api/basic/basicclass";
import { useMessage, useMessageBox } from "/@/hooks/message";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import FormDialog from './form.vue'
import { List, Calendar, Clock, OfficeBuilding, Grid, CreditCard, Avatar, Collection, Document, Setting, Menu, Search, RefreshLeft } 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 schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const deptList = ref<any[]>([])
const classList = ref<any[]>([])
const turnoverTypeList = ref<any[]>([])
const turnYearList = ref<any[]>([])
const formDialogRef = ref()

// 表格列配置
const tableColumns = [
  { prop: 'schoolYear', label: '学年' },
  { prop: 'schoolTerm', label: '学期' },
  { prop: 'deptName', label: '学院' },
  { prop: 'oldClassNo', label: '原班级' },
  { prop: 'newClassNo', label: '现班号' },
  { prop: 'stuNo', label: '学号' },
  { prop: 'realName', label: '姓名' },
  { prop: 'turnoverDate', label: '异动时间', width: 180 },
  { prop: 'turnoverType', label: '异动类型' },
  { prop: 'turnYear', label: '转制类型' },
  { prop: 'remarks', label: '异动原因', minWidth: 150 }
]

// 列配置映射（用于图标显示）
const columnConfigMap: Record<string, { icon: any }> = {
  schoolYear: { icon: Calendar },
  schoolTerm: { icon: Clock },
  deptName: { icon: OfficeBuilding },
  oldClassNo: { icon: Grid },
  newClassNo: { icon: Grid },
  stuNo: { icon: CreditCard },
  realName: { icon: Avatar },
  turnoverDate: { icon: Calendar },
  turnoverType: { icon: Collection },
  turnYear: { icon: Collection },
  remarks: { icon: Document }
}

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

// 搜索表单
const searchForm = reactive({
  schoolYear: '',
  schoolTerm: '',
  deptCode: '',
  oldClassCode: '',
  stuNo: '',
  realName: '',
  turnoverType: ''
})

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

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

// 格式化学期
const formatSchoolTerm = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = schoolTermList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  // 如果包含时间部分，只显示日期部分
  if (dateStr.includes(' ')) {
    return dateStr.split(' ')[0]
  }
  return dateStr
}

// 格式化异动类型
const formatTurnoverType = (value: string) => {
  if (!value) return '-'
  const item = turnoverTypeList.value.find((item: any) => item.value === value)
  return item ? item.label : value
}

// 格式化转制类型
const formatTurnYear = (value: string) => {
  if (!value) return '-'
  const item = turnYearList.value.find((item: any) => item.value === value)
  return item ? item.label : value
}

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

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

// 编辑
const handleEdit = (row: any) => {
  formDialogRef.value?.openDialog('edit', row)
}

// 异动撤销
const handleCancel = async (row: any) => {
  try {
    await useMessageBox().confirm('确定要撤销该条学籍异动吗？')
    await cancelObj([row.id])
    useMessage().success('撤销成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err?.msg || '撤销失败')
    }
  }
}

// 删除
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 handleExport = async () => {
  try {
    await makeExportStudentChangeTask(searchForm)
    useMessage().success('导出任务已创建，请在文件管理中下载')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  }
}

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

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

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

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

// 获取异动类型字典
const getTurnoverTypeDict = async () => {
  try {
    const res = await getDicts('turnover_type')
    if (res.data) {
      turnoverTypeList.value = Array.isArray(res.data) ? res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      })) : []
    }
  } catch (err) {
    turnoverTypeList.value = []
  }
}

// 获取转制类型字典
const getTurnYearDict = async () => {
  try {
    const res = await getDicts('turn_year_type')
    if (res.data) {
      turnYearList.value = Array.isArray(res.data) ? res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      })) : []
    }
  } catch (err) {
    turnYearList.value = []
  }
}

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

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

