<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="queryForm" ref="searchFormRef" :inline="true" @keyup.enter="getDataList" class="search-form">
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="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="classCode">
            <el-select 
              v-model="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="schoolYear">
            <el-select 
              v-model="queryForm.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="queryForm.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>
            <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="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="dataList" 
          v-loading="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 }}
            </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 || OfficeBuilding" /></el-icon>
                <span style="margin-left: 4px">{{ col.label }}</span>
              </template>
            <!-- 平均操行分格式化 -->
            <template v-if="col.prop === 'averageConduct'" #default="scope">
              <el-tag v-if="scope.row.averageConduct !== null && scope.row.averageConduct !== undefined" size="small" type="success" effect="plain">
                {{ scope.row.averageConduct.toFixed(2) }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 平均学习成绩格式化 -->
            <template v-else-if="col.prop === 'averageScore'" #default="scope">
              <el-tag v-if="scope.row.averageScore !== null && scope.row.averageScore !== undefined" size="small" type="primary" effect="plain">
                {{ scope.row.averageScore.toFixed(2) }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 规则名称格式化 -->
            <template v-else-if="col.prop === 'ruleName'" #default="scope">
              <el-tag v-if="scope.row.ruleName && Array.isArray(scope.row.ruleName) && scope.row.ruleName.length > 0" size="small" type="warning" effect="light">
                {{ scope.row.ruleName.join('、') }}
              </el-tag>
              <span v-else>-</span>
            </template>
            <!-- 更新时间格式化 -->
            <template v-else-if="col.prop === 'upDateTime'" #default="scope">
              <span>{{ parseTime(scope.row.upDateTime, dateTimeFormat) }}</span>
            </template>
            </el-table-column>
          </template>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts" name="RewardStudent">
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { fetchList, exportExcel } from "/@/api/stuwork/rewardstudent";
import { getDeptList } from "/@/api/basic/basicclass";
import { queryAllSchoolYear } from "/@/api/basic/basicyear";
import { getClassListByRole } from "/@/api/basic/basicclass";
import { getDicts } from "/@/api/admin/dict";
import { useMessage } from "/@/hooks/message";
import { parseTime } from "/@/utils/formatTime";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import { List, OfficeBuilding, Grid, CreditCard, Avatar, DataAnalysis, Warning, Trophy, Clock, Menu, Search, Document } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

const dateTimeFormat = '{y}-{m}-{d} {h}:{i}:{s}'

// 定义变量
const route = useRoute()
const searchFormRef = ref()
const columnControlRef = ref<any>()
const showSearch = ref(true)
const loading = ref(false)
const dataList = ref<any[]>([])
const schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const deptList = ref<any[]>([])
const classList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'departName', label: '学院名称' },
  { prop: 'classNo', label: '班级' },
  { prop: 'stuNo', label: '学号' },
  { prop: 'realName', label: '姓名' },
  { prop: 'averageConduct', label: '平均操行分' },
  { prop: 'averageScore', label: '平均学习成绩' },
  { prop: 'violation', label: '违规情况', minWidth: 150 },
  { prop: 'ruleName', label: '奖励规则', minWidth: 200 },
  { prop: 'upDateTime', label: '更新时间', width: 180 }
]

// 列配置映射
const columnConfigMap: Record<string, { icon: any }> = {
  departName: { icon: OfficeBuilding },
  classNo: { icon: Grid },
  stuNo: { icon: CreditCard },
  realName: { icon: Avatar },
  averageConduct: { icon: DataAnalysis },
  averageScore: { icon: DataAnalysis },
  violation: { icon: Warning },
  ruleName: { icon: Trophy },
  upDateTime: { icon: Clock }
}

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

// 查询表单
const queryForm = reactive({
  deptCode: '',
  classCode: '',
  schoolYear: '',
  schoolTerm: ''
})

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

// 格式化学期
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 getDataList = async () => {
  loading.value = true
  try {
    const res = await fetchList(queryForm)
    if (res.data && Array.isArray(res.data)) {
      dataList.value = res.data
    } else {
      dataList.value = []
    }
  } catch (err: any) {
    useMessage().error(err.msg || '查询失败')
    dataList.value = []
  } finally {
    loading.value = false
  }
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  queryForm.deptCode = ''
  queryForm.classCode = ''
  queryForm.schoolYear = ''
  queryForm.schoolTerm = ''
  getDataList()
}

// 导出
const handleExport = async () => {
  try {
    loading.value = true
    const res = await exportExcel(queryForm)
    
    // 创建 blob
    const blob = new Blob([res], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 设置文件名
    const fileName = `奖励学生_${new Date().getTime()}.xlsx`
    link.setAttribute('download', fileName)
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    
    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    useMessage().success('导出成功')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  } finally {
    loading.value = false
  }
}

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

// 获取学期字典
const getSchoolTermDict = 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 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 = []
  }
}

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

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

