<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-column label="操作" width="180" align="center" fixed="right">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button link type="primary" icon="Trophy" @click="handleAward(scope.row)">评优</el-button>
              <el-button link type="success" icon="View" @click="handleViewRecord(scope.row)">记录</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 评优对话框 -->
    <el-dialog
      title="学生评优"
      v-model="awardDialogVisible"
      :width="500"
      :close-on-click-modal="false"
      draggable>
      <el-form :model="awardForm" label-width="80px">
        <el-form-item label="学号">
          <el-input v-model="awardForm.stuNo" disabled />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="awardForm.realName" disabled />
        </el-form-item>
        <el-form-item label="奖项">
          <el-select
            v-model="awardForm.ruleName"
            multiple
            placeholder="请选择奖项"
            filterable
            style="width: 100%">
            <el-option
              v-for="item in rewardRuleList"
              :key="item.id"
              :label="item.ruleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="awardDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAwardSubmit" :loading="awardLoading">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 评优记录对话框 -->
    <el-dialog
      title="评优记录"
      v-model="recordDialogVisible"
      :width="600"
      :close-on-click-modal="false"
      draggable>
      <div v-if="currentRow" class="record-header">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="学号">{{ currentRow.stuNo }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ currentRow.realName }}</el-descriptions-item>
          <el-descriptions-item label="学年">{{ queryForm.schoolYear || '-' }}</el-descriptions-item>
          <el-descriptions-item label="学期">{{ formatSchoolTerm(queryForm.schoolTerm) }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <el-table
        :data="rewardRecordList"
        v-loading="recordLoading"
        stripe
        border
        style="margin-top: 15px;">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="ruleId" label="奖项ID" align="center" />
        <el-table-column prop="ruleName" label="奖项名称" align="center">
          <template #default="scope">
            {{ getRuleNameById(scope.row.ruleId) || scope.row.ruleId || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="评选时间" align="center" width="180">
          <template #default="scope">
            {{ parseTime(scope.row.createTime, dateTimeFormat) }}
          </template>
        </el-table-column>
      </el-table>
      <template #empty>
        <el-empty description="暂无评优记录" :image-size="80" />
      </template>
      <template #footer>
        <el-button @click="recordDialogVisible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="RewardStudent">
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { fetchList, exportExcel, updateStuAward, getStuRewardList, getRewardRuleList } 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, Setting, View } 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 awardDialogVisible = ref(false)
const awardLoading = ref(false)
const awardForm = reactive({
  stuNo: '',
  realName: '',
  schoolYear: '',
  schoolTerm: '',
  ruleName: [] as string[]
})
const rewardRuleList = ref<any[]>([])

// 评优记录相关
const recordDialogVisible = ref(false)
const recordLoading = ref(false)
const currentRow = ref<any>(null)
const rewardRecordList = 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 = []
  }
}

// 获取奖项规则列表
const getRewardRuleListData = async () => {
  try {
    const res = await getRewardRuleList()
    if (res.data && Array.isArray(res.data)) {
      rewardRuleList.value = res.data
    } else {
      rewardRuleList.value = []
    }
  } catch (err) {
    rewardRuleList.value = []
  }
}

// 根据ruleId获取奖项名称
const getRuleNameById = (ruleId: string) => {
  const rule = rewardRuleList.value.find(item => item.id === ruleId)
  return rule ? rule.ruleName : null
}

// 打开评优对话框
const handleAward = (row: any) => {
  if (!queryForm.schoolYear || !queryForm.schoolTerm) {
    useMessage().warning('请先选择学年 and 学期')
    return
  }
  awardForm.stuNo = row.stuNo
  awardForm.realName = row.realName
  awardForm.schoolYear = queryForm.schoolYear
  awardForm.schoolTerm = queryForm.schoolTerm
  // 如果已有奖项，设置默认值
  awardForm.ruleName = row.ruleName && Array.isArray(row.ruleName) ? [...row.ruleName] : []
  awardDialogVisible.value = true
}

// 提交评优
const handleAwardSubmit = async () => {
  awardLoading.value = true
  try {
    await updateStuAward(awardForm)
    useMessage().success('评优成功')
    awardDialogVisible.value = false
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg || '评优失败')
  } finally {
    awardLoading.value = false
  }
}

// 查看评优记录
const handleViewRecord = async (row: any) => {
  if (!queryForm.schoolYear || !queryForm.schoolTerm) {
    useMessage().warning('请先选择学年 and 学期')
    return
  }
  currentRow.value = row
  recordDialogVisible.value = true
  recordLoading.value = true
  rewardRecordList.value = []
  try {
    const res = await getStuRewardList(row.stuNo, queryForm.schoolYear, queryForm.schoolTerm)
    if (res.data && Array.isArray(res.data)) {
      rewardRecordList.value = res.data
    } else {
      rewardRecordList.value = []
    }
  } catch (err: any) {
    useMessage().error(err.msg || '获取记录失败')
    rewardRecordList.value = []
  } finally {
    recordLoading.value = false
  }
}

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

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

.record-header {
  margin-bottom: 10px;
}
</style>

