<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="classCode">
            <el-select 
              v-model="searchForm.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="realName">
            <el-input 
              v-model="searchForm.realName" 
              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="punlishMonth">
            <el-date-picker
              v-model="searchForm.punlishMonth"
              type="month"
              placeholder="请选择处分月份"
              format="YYYY-MM"
              value-format="YYYY-MM"
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="处分等级" prop="punlishLevel">
            <el-select 
              v-model="searchForm.punlishLevel" 
              placeholder="请选择处分等级" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in punlishLevelList"
                :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 === 'punlishStartDate'" #default="scope">
              <span>{{ scope.row.punlishStartDate ? formatDate(scope.row.punlishStartDate) : '-' }}</span>
            </template>
            <!-- 处分结束日期 -->
            <template v-else-if="col.prop === 'punlishEndDate'" #default="scope">
              <span>{{ scope.row.punlishEndDate ? formatDate(scope.row.punlishEndDate) : '-' }}</span>
            </template>
            <!-- 处分等级 -->
            <template v-else-if="col.prop === 'punlishLevel'" #default="scope">
              <el-tag size="small" type="danger" effect="plain">
                {{ formatPunlishLevel(scope.row.punlishLevel) }}
              </el-tag>
            </template>
            <!-- 状态 -->
            <template v-else-if="col.prop === 'publishStatus'" #default="scope">
              <StatusTag 
                :value="scope.row.publishStatus"
                :options="[{ label: '已发布', value: '1' }, { label: '已撤销', value: '2' }, { label: '已取消', value: '3' }]"
                :type-map="{ '1': { type: 'danger', effect: 'light' }, '2': { type: 'success', effect: 'light' }, '3': { type: 'info', effect: 'light' } }"
              />
            </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="250" align="center" fixed="right">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button 
                icon="Document" 
                link 
                type="primary" 
                @click="handleReport(scope.row)">
                处分报告
              </el-button>
              <el-button 
                icon="CircleClose" 
                link 
                type="warning" 
                @click="handleCancel(scope.row)">
                撤销处分
              </el-button>
              <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="StuPunlish">
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj, exportData, revokePunishment, getDetail } from "/@/api/stuwork/stupunlish";
import { queryAllSchoolYear } from "/@/api/basic/basicyear";
import { getDicts } from "/@/api/admin/dict";
import { getDeptListByLevelTwo } from "/@/api/basic/basicdept";
import { getClassListByRole } 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, Avatar, CreditCard, Warning, Document, CircleCheck, Setting, Menu, Search } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

import { defineAsyncComponent } from 'vue'
const StatusTag = defineAsyncComponent(() => import('/@/components/StatusTag/index.vue'))

// 定义变量
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 punlishLevelList = ref<any[]>([])
const publishStatusList = ref<any[]>([])
const formDialogRef = ref()

// 表格列配置
const tableColumns = [
  { prop: 'schoolYear', label: '学年' },
  { prop: 'schoolTerm', label: '学期' },
  { prop: 'deptName', label: '学院' },
  { prop: 'classNo', label: '班级' },
  { prop: 'stuRealName', label: '姓名' },
  { prop: 'stuNo', label: '学号' },
  { prop: 'punlishStartDate', label: '处分开始日期', width: 180 },
  { prop: 'punlishEndDate', label: '结束日期', width: 180 },
  { prop: 'punlishLevel', label: '处分等级' },
  { prop: 'punlishContent', label: '处分内容', minWidth: 150 },
  { prop: 'publishStatus', label: '发布状态' }
]

// 列配置映射
const columnConfigMap: Record<string, { icon: any }> = {
  schoolYear: { icon: Calendar },
  schoolTerm: { icon: Clock },
  deptName: { icon: OfficeBuilding },
  classNo: { icon: Grid },
  stuRealName: { icon: Avatar },
  stuNo: { icon: CreditCard },
  punlishStartDate: { icon: Calendar },
  punlishEndDate: { icon: Calendar },
  punlishLevel: { icon: Warning },
  punlishContent: { icon: Document },
  publishStatus: { icon: CircleCheck }
}

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

// 搜索表单
const searchForm = reactive({
  schoolYear: '',
  schoolTerm: '',
  deptCode: '',
  classCode: '',
  realName: '',
  stuNo: '',
  punlishMonth: '',
  punlishLevel: '',
  punlishMonthArray: [] as string[]
})

// 使用 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: searchForm,
  pageList: async (params: any) => {
    // 处理处分月份参数 API
    const queryParams = { ...params }
    if (queryParams.punlishMonth) {
      queryParams.punlishMonth = [queryParams.punlishMonth]
    } else {
      delete queryParams.punlishMonth
    }
    delete queryParams.punlishMonthArray
    return await fetchList(queryParams)
  },
  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 formatPunlishLevel = (value: string) => {
  if (!value) return '-'
  const item = punlishLevelList.value.find((item: any) => item.value === value)
  return item ? item.label : value
}

// 格式化发布状态
const formatPublishStatus = (value: string) => {
  if (!value) return '-'
  const item = publishStatusList.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.classCode = ''
  searchForm.realName = ''
  searchForm.stuNo = ''
  searchForm.punlishMonth = ''
  searchForm.punlishLevel = ''
  getDataList()
}

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

// 删除
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 handleReport = (row: any) => {
  useMessage().info('功能开发中')
  // TODO: 实现处分报告
}

// 撤销处分
const handleCancel = async (row: any) => {
  const { confirm } = useMessageBox()
  try {
    await confirm('确定要撤销该处分吗？')
    
    // 获取详情数据
    const res = await getDetail(row.id)
    if (!res.data) {
      useMessage().error('获取数据失败')
      return
    }
    
    // 将 publishStatus 设置为 "0" 表示撤销
    const updateData = {
      ...res.data,
      publishStatus: '0'
    }
    
    await revokePunishment(updateData)
    useMessage().success('撤销成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '撤销失败')
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    const params: any = { ...searchForm }
    // 处理处分月份参数 API
    if (params.punlishMonth) {
      params.punlishMonth = [params.punlishMonth]
    } else {
      delete params.punlishMonth
    }
    delete params.punlishMonthArray
    const res = await exportData(params)
    // 下载文件
    const blob = new Blob([res.data])
    const elink = document.createElement('a')
    elink.download = '学生处分.xlsx'
    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 || '导出失败')
  }
}

// 获取学年列表
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 getClassListByRole()
    if (res.data) {
      classList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    classList.value = []
  }
}

// 获取处分等级字典
const getPunlishLevelDict = async () => {
  try {
    const res = await getDicts('punlish_level')
    if (res.data) {
      punlishLevelList.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) {
    punlishLevelList.value = []
  }
}

// 获取发布状态字典
const getPublishStatusDict = async () => {
  try {
    const res = await getDicts('publish_status')
    if (res.data) {
      publishStatusList.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) {
    publishStatusList.value = []
  }
}

// ???
onMounted(() => {
  getSchoolYearList()
  getSchoolTermDict()
  getDeptListData()
  getClassListData()
  getPunlishLevelDict()
  getPublishStatusDict()
  nextTick(() => {
    if (visibleColumns.value.length === 0) {
    }
  })
})
</script>

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