<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="state.queryForm" ref="searchFormRef" :inline="true" @keyup.enter="getDataList" class="search-form">
          <el-form-item label="学期" prop="termId">
            <el-select 
              v-model="state.queryForm.termId" 
              placeholder="请选择学期" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in termList"
                :key="item.id"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="state.queryForm.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="grade">
            <el-select 
              v-model="state.queryForm.grade" 
              placeholder="请选择入学年份" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in gradeList"
                :key="item.year"
                :label="item.year"
                :value="item.year">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年级" prop="gradeCurr">
            <el-input-number 
              v-model="state.queryForm.gradeCurr" 
              placeholder="请输入年级"
              :min="1"
              :max="10"
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="班级" prop="classCode">
            <el-select 
              v-model="state.queryForm.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="checkStatus">
            <el-select 
              v-model="state.queryForm.checkStatus" 
              placeholder="请选择审核状态"
              clearable
              style="width: 200px">
              <el-option
                v-for="item in checkStatusList"
                :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="getDataList">查询</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="Plus" 
                type="primary" 
                @click="handleAdd">
                新增
              </el-button>
              <el-button 
                icon="Download" 
                type="success" 
                class="ml10" 
                :loading="exportLoading"
                @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 === 'gradeCurr'" #default="scope">
              <el-tag v-if="scope.row.gradeCurr !== undefined && scope.row.gradeCurr !== null" size="small" type="primary" effect="plain">
                {{ scope.row.gradeCurr }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 性别格式化-->
            <template v-else-if="col.prop === 'gender'" #default="scope">
              <GenderTag :sex="scope.row.gender" />
            </template>
            <!-- 学历格式化-->
            <template v-else-if="col.prop === 'education'" #default="scope">
              <el-tag v-if="scope.row.education" size="small" type="info" effect="plain">
                {{ formatEducation(scope.row.education) }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 专业层次格式化-->
            <template v-else-if="col.prop === 'majorLevel'" #default="scope">
              <el-tag v-if="scope.row.majorLevel" size="small" type="warning" effect="plain">
                {{ formatMajorLevel(scope.row.majorLevel) }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 金额格式化-->
            <template v-else-if="col.prop === 'money'" #default="scope">
              <el-tag v-if="scope.row.money !== undefined && scope.row.money !== null" size="small" type="success" effect="plain">
                ¥{{ scope.row.money }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 审核状态格式化 -->
            <template v-else-if="col.prop === 'checkStatus'" #default="scope">
              <StatusTag 
                :value="scope.row.checkStatus"
                :options="checkStatusList"
                :type-map="{ '0': { type: 'warning', effect: 'light' }, '1': { type: 'success', effect: 'light' } }"
              />
            </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="150" 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="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="TuitionFreeStu">
import { reactive, ref, onMounted, defineAsyncComponent, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, exportExcel, delObj, getDetail } from "/@/api/stuwork/tuitionfreestu";
import { getDeptList } from "/@/api/basic/basicclass";
import { getClassListByRole } from "/@/api/basic/basicclass";
import { getDicts } from "/@/api/admin/dict";
import { queryAllSchoolYear } from "/@/api/basic/basicyear";
import { useMessage, useMessageBox } from "/@/hooks/message";
import request from '/@/utils/request'
import axios from 'axios'
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import { 
  User, School, Trophy, Phone, Money, CircleCheck, List, 
  OfficeBuilding, Reading, UserFilled, Calendar, Sort, Grid, 
  CreditCard, Avatar, Setting, Menu, Search, Document
} from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'


// 异步组件
const GenderTag = defineAsyncComponent(() => import('/@/components/GenderTag/index.vue'))
const StatusTag = defineAsyncComponent(() => import('/@/components/StatusTag/index.vue'))

// 定义变量
const route = useRoute()
const searchFormRef = ref()
const columnControlRef = ref<any>()
const formDialogRef = ref()
const showSearch = ref(true)
const exportLoading = ref(false)
const termList = ref<any[]>([])
const deptList = ref<any[]>([])
const classList = ref<any[]>([])
const gradeList = ref<any[]>([])
const genderList = ref<any[]>([])
const educationList = ref<any[]>([])
const majorLevelList = ref<any[]>([])
const checkStatusList = ref<any[]>([
  { label: '未审核', value: '0' },
  { label: '已审核', value: '1' }
])

// 表格列配置
const tableColumns = [
  { prop: 'deptName', label: '学院', minWidth: 150 },
  { prop: 'majorName', label: '专业', minWidth: 150 },
  { prop: 'teacherName', label: '班主任', width: 100 },
  { prop: 'grade', label: '入学年份', width: 100 },
  { prop: 'gradeCurr', label: '年级', width: 80 },
  { prop: 'classNo', label: '班级', width: 120 },
  { prop: 'stuNo', label: '学号', width: 120 },
  { prop: 'realName', label: '姓名', width: 100 },
  { prop: 'gender', label: '性别', width: 80 },
  { prop: 'education', label: '学历', width: 100 },
  { prop: 'majorLevel', label: '层次', width: 100 },
  { prop: 'phone', label: '联系电话', width: 120 },
  { prop: 'money', label: '金额', width: 100 },
  { prop: 'checkStatus', label: '审核状态', width: 100 }
]

// 列配置映射
const columnConfigMap: Record<string, { icon: any }> = {
  deptName: { icon: OfficeBuilding },
  majorName: { icon: Reading },
  teacherName: { icon: UserFilled },
  grade: { icon: Calendar },
  gradeCurr: { icon: Sort },
  classNo: { icon: Grid },
  stuNo: { icon: CreditCard },
  realName: { icon: Avatar },
  gender: { icon: User },
  education: { icon: School },
  majorLevel: { icon: Trophy },
  phone: { icon: Phone },
  money: { icon: Money },
  checkStatus: { icon: CircleCheck }
}

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

// 表格样式
const tableStyle = {
  cellStyle: { padding: '8px 0' },
  headerCellStyle: { background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }
}

// 使用 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    termId: '',
    deptCode: '',
    grade: '',
    gradeCurr: undefined,
    classCode: '',
    checkStatus: ''
  },
  pageList: fetchList,
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true
})

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

// 格式化性别
const formatGender = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = genderList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

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

// 格式化层次
const formatMajorLevel = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = majorLevelList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 格式化审核状态
const formatCheckStatus = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = checkStatusList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  state.queryForm.termId = ''
  state.queryForm.deptCode = ''
  state.queryForm.grade = ''
  state.queryForm.gradeCurr = undefined
  state.queryForm.classCode = ''
  state.queryForm.checkStatus = ''
  getDataList()
}

// 新增
const handleAdd = () => {
  useMessage().info('功能开发中')
  // formDialogRef.value?.openDialog('add')
}

// 编辑
const handleEdit = (row: any) => {
  useMessage().info('功能开发中')
  // formDialogRef.value?.openDialog('edit', row.id)
}

// 删除
const handleDelete = async (row: any) => {
  try {
    const { confirm } = useMessageBox()
    await confirm(`确定要删除学号为 ${row.stuNo} 的学生记录吗？`)
    await delObj(row.id)
    useMessage().success('删除成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '删除失败')
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    exportLoading.value = true
    const res = await exportExcel(state.queryForm)
    const blob = new Blob([res.data as BlobPart])
    const fileName = `免学费学生_${new Date().getTime()}.xls`
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
    useMessage().success('导出成功')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 获取学期列表
const getTermList = async () => {
  try {
    const res = await request({
      url: '/stuwork/tuitionfreeterm/list',
      method: 'get'
    })
    if (res.data && Array.isArray(res.data)) {
      termList.value = res.data
    } else {
      termList.value = []
    }
  } catch (err) {
    termList.value = []
  }
}

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

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

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

// 获取性别字典
const getGenderDict = async () => {
  try {
    const res = await getDicts('sexy')
    if (res.data && Array.isArray(res.data)) {
      genderList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      genderList.value = []
    }
  } catch (err) {
    genderList.value = []
  }
}

// 获取学历字典
const getEducationDict = 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) {
    educationList.value = []
  }
}

// 获取层次字典
const getMajorLevelDict = async () => {
  try {
    const res = await getDicts('basic_major_level')
    if (res.data && Array.isArray(res.data)) {
      majorLevelList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      majorLevelList.value = []
    }
  } catch (err) {
    majorLevelList.value = []
  }
}

// 初始化
onMounted(() => {
  getTermList()
  getDeptListData()
  getClassListData()
  getGradeList()
  getGenderDict()
  getEducationDict()
  getMajorLevelDict()
  nextTick(() => {
    if (visibleColumns.value.length === 0) {
    }
  })
})
</script>

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