<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="searchFormRef" :inline="true" @keyup.enter="getDataList">
          <el-form-item label="学年" prop="schoolYear">
            <el-select 
              v-model="state.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="state.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 label="是否达标" prop="isDb">
            <el-select 
              v-model="state.queryForm.isDb" 
              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="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="classNo">
            <el-select 
              v-model="state.queryForm.classNo" 
              placeholder="请选择班级" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classNo">
              </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-row>

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button 
            icon="Plus" 
            type="primary" 
            class="ml10" 
            @click="handleInit">
            初始化
          </el-button>
          <right-toolbar  
            v-model:showSearch="showSearch" 
            class="ml10"
            style="float: right;"
            @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>
      </el-row>

      <!-- 表格 -->
      <el-table 
        :data="state.dataList" 
        v-loading="state.loading"
        border 
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle">
        <el-table-column type="index" label="序号" width="60" align="center">
          <template #header>
            <el-icon><List /></el-icon>
          </template>
        </el-table-column>
        <template v-for="col in sortedTableColumns" :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 === 'count'" #default="scope">
              <el-tag v-if="scope.row.count" size="small" type="success" effect="plain">
                {{ scope.row.count }}
              </el-tag>
              <span v-else>0</span>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #header>
            <el-icon><Setting /></el-icon>
            <span style="margin-left: 4px">操作</span>
          </template>
          <template #default="scope">
            <el-button 
              icon="View" 
              text 
              type="primary" 
              @click="handleViewRecord(scope.row)">
              查看上传记录
            </el-button>
            <el-button 
              icon="Delete" 
              text 
              type="danger" 
              @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination 
        @size-change="sizeChangeHandle" 
        @current-change="currentChangeHandle" 
        v-bind="state.pagination" />
    </div>

    <!-- 初始化弹窗 -->
    <init-dialog ref="initDialogRef" @refresh="getDataList" />
    
    <!-- 查看上传记录弹窗 -->
    <record-dialog ref="recordDialogRef" />
  </div>
</template>

<script setup lang="ts" name="ClassTheme">
import { reactive, ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj } from "/@/api/stuwork/classtheme";
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, useMessageBox } from "/@/hooks/message";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import InitDialog from './init.vue'
import RecordDialog from './record.vue'
import { List, Calendar, Clock, OfficeBuilding, Grid, Upload, EditPen, Setting, Menu } from '@element-plus/icons-vue'

// 定义变量内容
const route = useRoute()
const initDialogRef = ref()
const columnControlRef = ref<any>()
const recordDialogRef = ref()
const searchFormRef = ref()
const showSearch = ref(true)
const schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const deptList = ref<any[]>([])
const classList = ref<any[]>([])
const yesNoList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'schoolYear', label: '学年' },
  { prop: 'schoolTerm', label: '学期' },
  { prop: 'deptName', label: '学院' },
  { prop: 'classNo', label: '班级' },
  { prop: 'count', label: '上传次数' },
  { prop: 'remarks', label: '备注', minWidth: 200 }
]

// 列配置映射（用于图标）
const columnConfigMap: Record<string, { icon: any }> = {
  schoolYear: { icon: Calendar },
  schoolTerm: { icon: Clock },
  deptName: { icon: OfficeBuilding },
  classNo: { icon: Grid },
  count: { icon: Upload },
  remarks: { icon: EditPen }
}

// 当前显示的列
const visibleColumns = ref<string[]>([])
// 列排序顺序
const columnOrder = ref<string[]>([])

// 立即从 localStorage 加载配置
const loadSavedConfig = () => {
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  const saved = localStorage.getItem(storageKey)
  if (saved) {
    try {
      const savedColumns = JSON.parse(saved)
      const validColumns = tableColumns.map(col => col.prop || col.label)
      const filteredSaved = savedColumns.filter((col: string) => validColumns.includes(col))
      visibleColumns.value = filteredSaved.length > 0 ? filteredSaved : validColumns
    } catch (e) {
      visibleColumns.value = tableColumns.map(col => col.prop || col.label)
    }
  } else {
    visibleColumns.value = tableColumns.map(col => col.prop || col.label)
  }
  
  const orderKey = `${storageKey}-order`
  const savedOrder = localStorage.getItem(orderKey)
  if (savedOrder) {
    try {
      const parsedOrder = JSON.parse(savedOrder)
      const validColumns = tableColumns.map(col => col.prop || col.label)
      columnOrder.value = parsedOrder.filter((key: string) => validColumns.includes(key))
      validColumns.forEach(key => {
        if (!columnOrder.value.includes(key)) {
          columnOrder.value.push(key)
        }
      })
    } catch (e) {
      columnOrder.value = tableColumns.map(col => col.prop || col.label)
    }
  } else {
    columnOrder.value = tableColumns.map(col => col.prop || col.label)
  }
}

loadSavedConfig()

// 排序后的表格列
const sortedTableColumns = computed(() => {
  const columns = tableColumns.filter(col => {
    const key = col.prop || col.label
    return visibleColumns.value.includes(key)
  })
  
  if (columnOrder.value.length > 0) {
    const orderedColumns: typeof tableColumns = []
    const unorderedColumns: typeof tableColumns = []
    
    columnOrder.value.forEach(key => {
      const col = columns.find(c => (c.prop || c.label) === key)
      if (col) {
        orderedColumns.push(col)
      }
    })
    
    columns.forEach(col => {
      const key = col.prop || col.label
      if (!columnOrder.value.includes(key)) {
        unorderedColumns.push(col)
      }
    })
    
    return [...orderedColumns, ...unorderedColumns]
  }
  
  return columns
})

// 列显示控制函数
const checkColumnVisible = (prop: string): boolean => {
  if (visibleColumns.value.length === 0) {
    return true
  }
  return visibleColumns.value.includes(prop)
}

// 监听列变化
const handleColumnChange = (columns: string[]) => {
  visibleColumns.value = columns
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  const selectableColumns = columns.filter(col => {
    const column = tableColumns.find(c => (c.prop || c.label) === col)
    return column && !column.alwaysShow && !column.fixed
  })
  localStorage.setItem(storageKey, JSON.stringify(selectableColumns))
}

// 监听列排序变化
const handleColumnOrderChange = (order: string[]) => {
  columnOrder.value = order
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}-order`
  localStorage.setItem(storageKey, JSON.stringify(order))
}

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    schoolYear: '',
    schoolTerm: '',
    isDb: '',
    deptCode: '',
    classNo: ''
  },
  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 handleReset = () => {
  searchFormRef.value?.resetFields()
  state.queryForm.schoolYear = ''
  state.queryForm.schoolTerm = ''
  state.queryForm.isDb = ''
  state.queryForm.deptCode = ''
  state.queryForm.classNo = ''
  getDataList()
}

// 初始化
const handleInit = () => {
  initDialogRef.value?.openDialog()
}

// 查看上传记录
const handleViewRecord = (row: any) => {
  recordDialogRef.value?.openDialog(row)
}

// 删除
const handleDelete = async (row: any) => {
  const { confirm } = useMessageBox()
  try {
    await confirm('确定要删除该主题班会课教案吗？')
    await delObj([row.id])
    useMessage().success('删除成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '删除失败')
    }
  }
}

// 获取学年列表
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 getYesNoDict = async () => {
  try {
    const res = await getDicts('yes_no')
    if (res.data && Array.isArray(res.data)) {
      yesNoList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      yesNoList.value = []
    }
  } catch (err) {
    yesNoList.value = []
  }
}

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

<style scoped lang="scss">
</style>
