<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="leaveType">
            <el-select 
              v-model="searchForm.leaveType" 
              placeholder="请选择请假类型" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in leaveTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="住宿类型" prop="goOrStay">
            <el-select 
              v-model="searchForm.goOrStay" 
              placeholder="请选择住宿类型" 
              clearable
              style="width: 200px">
              <el-option label="走读" value="0" />
              <el-option label="住宿" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否住宿" prop="stayDorm">
            <el-select 
              v-model="searchForm.stayDorm" 
              placeholder="请选择是否住宿" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in yesNoList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班主任审核" prop="classAudit">
            <el-select 
              v-model="searchForm.classAudit" 
              placeholder="请选择班主任审核" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in auditTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学生科审核" prop="deptAudit">
            <el-select 
              v-model="searchForm.deptAudit" 
              placeholder="请选择学生科审核" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in auditTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学工处审核" prop="schoolAudit">
            <el-select 
              v-model="searchForm.schoolAudit" 
              placeholder="请选择学工处审核" 
              clearable
              style="width: 200px">
              <el-option
                v-for="item in auditTypeList"
                :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 === 'startTime'" #default="scope">
              <span>{{ scope.row.startTime ? formatDateTime(scope.row.startTime) : '-' }}</span>
            </template>
            <!-- 请假结束时间列特殊模板-->
            <template v-else-if="col.prop === 'endTime'" #default="scope">
              <span>{{ scope.row.endTime ? formatDateTime(scope.row.endTime) : '-' }}</span>
            </template>
            <!-- 请假类型列特殊模板-->
            <template v-else-if="col.prop === 'leaveType'" #default="scope">
              <el-tag size="small" type="info" effect="plain">
                {{ formatLeaveType(scope.row.leaveType) }}
              </el-tag>
            </template>
            <!-- 是否住宿列特殊模板-->
            <template v-else-if="col.prop === 'stayDorm'" #default="scope">
              <StatusTag 
                :value="scope.row.stayDorm"
                :options="[{ label: '是', value: '1' }, { label: '否', value: '0' }]"
                :type-map="{ '1': { type: 'success', effect: 'light' }, '0': { type: 'info', effect: 'light' } }"
              />
            </template>
            <!-- 是否发热列特殊模板-->
            <template v-else-if="col.prop === 'isFever'" #default="scope">
              <StatusTag 
                :value="scope.row.isFever"
                :options="[{ label: '是', value: '1' }, { label: '否', value: '0' }]"
                :type-map="{ '1': { type: 'danger', effect: 'light' }, '0': { type: 'success', effect: 'light' } }"
              />
            </template>
            <!-- 班主任审核列特殊模板 -->
            <template v-else-if="col.prop === 'classAudit'" #default="scope">
              <StatusTag 
                :value="scope.row.classAudit"
                :options="[{ label: '待审核', value: '0' }, { label: '通过', value: '1' }, { label: '驳回', value: '2' }]"
                :type-map="{ '0': { type: 'warning', effect: 'light' }, '1': { type: 'success', effect: 'light' }, '2': { type: 'danger', effect: 'light' } }"
              />
            </template>
            <!-- 学生科审核列特殊模板 -->
            <template v-else-if="col.prop === 'deptAudit'" #default="scope">
              <StatusTag 
                :value="scope.row.deptAudit"
                :options="[{ label: '待审核', value: '0' }, { label: '通过', value: '1' }, { label: '驳回', value: '2' }]"
                :type-map="{ '0': { type: 'warning', effect: 'light' }, '1': { type: 'success', effect: 'light' }, '2': { type: 'danger', effect: 'light' } }"
              />
            </template>
            <!-- 学工处审批列特殊模板 -->
            <template v-else-if="col.prop === 'schoolAudit'" #default="scope">
              <StatusTag 
                :value="scope.row.schoolAudit"
                :options="[{ label: '待审核', value: '0' }, { label: '通过', value: '1' }, { label: '驳回', value: '2' }]"
                :type-map="{ '0': { type: 'warning', effect: 'light' }, '1': { type: 'success', effect: 'light' }, '2': { type: 'danger', effect: 'light' } }"
              />
            </template>
          </el-table-column>
        </template>
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button 
                icon="CircleClose" 
                link 
                type="warning" 
                @click="handleCancel(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="StuLeaveApply">
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, exportData, cancelObj } from "/@/api/stuwork/stuleaveapply";
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, Avatar, Collection, Document, House, Warning, CircleCheck, EditPen, 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 leaveTypeList = ref<any[]>([])
const yesNoList = ref<any[]>([])
const auditTypeList = ref<any[]>([])
const formDialogRef = ref()

// 表格列配置
const tableColumns = [
  { prop: 'schoolYear', label: '学年' },
  { prop: 'schoolTerm', label: '学期' },
  { prop: 'deptName', label: '学院' },
  { prop: 'realName', label: '姓名' },
  { prop: 'startTime', label: '请假开始时间', width: 180 },
  { prop: 'endTime', label: '请假结束时间', width: 180 },
  { prop: 'leaveType', label: '请假类型' },
  { prop: 'reason', label: '请假事由', minWidth: 150 },
  { prop: 'stayDorm', label: '是否住宿' },
  { prop: 'isFever', label: '是否发热' },
  { prop: 'classAudit', label: '班主任审核' },
  { prop: 'deptAudit', label: '学生科审核' },
  { prop: 'schoolAudit', label: '学工处审核' },
  { prop: 'remarks', label: '备注', minWidth: 150 },
  { prop: 'rejectReason', label: '驳回原因', minWidth: 150 }
]

// 列配置映射（用于图标）
const columnConfigMap: Record<string, { icon: any }> = {
  schoolYear: { icon: Calendar },
  schoolTerm: { icon: Clock },
  deptName: { icon: OfficeBuilding },
  realName: { icon: Avatar },
  startTime: { icon: Calendar },
  endTime: { icon: Calendar },
  leaveType: { icon: Collection },
  reason: { icon: Document },
  stayDorm: { icon: House },
  isFever: { icon: Warning },
  classAudit: { icon: CircleCheck },
  deptAudit: { icon: CircleCheck },
  schoolAudit: { icon: CircleCheck },
  remarks: { icon: EditPen },
  rejectReason: { icon: Warning }
}

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

// 搜索表单
const searchForm = reactive({
  schoolYear: '',
  schoolTerm: '',
  deptCode: '',
  classCode: '',
  realName: '',
  leaveType: '',
  goOrStay: '',
  stayDorm: '',
  classAudit: '',
  deptAudit: '',
  schoolAudit: ''
})

// 配置 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 formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  // 如果包含时间部分，只显示日期和时间
  if (dateTime.includes(' ')) {
    return dateTime.split('.')[0] // 移除毫秒部分
  }
  return dateTime
}

// 格式化请假类型
const formatLeaveType = (value: string) => {
  if (!value) return '-'
  const item = leaveTypeList.value.find((item: any) => item.value === value)
  return item ? item.label : value
}

// 格式化是否
const formatYesNo = (value: string | null) => {
  if (value === null || value === undefined || value === '') return '-'
  const item = yesNoList.value.find((item: any) => item.value === value)
  return item ? item.label : (value === '1' || value === 'true' ? '是' : '否')
}

// 格式化审核类型
const formatAuditType = (value: string) => {
  if (!value) return '-'
  const item = auditTypeList.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.leaveType = ''
  searchForm.goOrStay = ''
  searchForm.stayDorm = ''
  searchForm.classAudit = ''
  searchForm.deptAudit = ''
  searchForm.schoolAudit = ''
  getDataList()
}

// 撤销
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 handleExport = async () => {
  try {
    const res = await exportData(searchForm)
    // 处理返回的文件流
    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 getLeaveTypeDict = async () => {
  try {
    const res = await getDicts('leave_type')
    if (res.data) {
      leaveTypeList.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) {
    leaveTypeList.value = []
  }
}

// 获取是否字典
const getYesNoDict = async () => {
  try {
    const res = await getDicts('yes_no')
    if (res.data) {
      yesNoList.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) {
    yesNoList.value = []
  }
}

// 获取审核类型字典
const getAuditTypeDict = async () => {
  try {
    const res = await getDicts('class_audit_type')
    if (res.data) {
      auditTypeList.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) {
    auditTypeList.value = []
  }
}

// 初始化
onMounted(() => {
  getSchoolYearList()
  getSchoolTermDict()
  getDeptListData()
  getClassListData()
  getLeaveTypeDict()
  getYesNoDict()
  getAuditTypeDict()
})
</script>

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

