<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索表单 -->
      <el-row v-show="showSearch">
        <el-form :model="searchForm" ref="searchFormRef" :inline="true" @keyup.enter="handleSearch">
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="searchForm.deptCode" 
              placeholder="请选择学院" 
              clearable
              filterable
              style="width: 200px"
              @change="handleDeptChange"> 
              <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="assessmentCategory">
            <el-select 
              v-model="searchForm.assessmentCategory" 
              placeholder="请选择考核项目" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in assessmentCategoryList"
                :key="item.id"
                :label="item.category"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考核指标" prop="assessmentPoint">
            <el-select 
              v-model="searchForm.assessmentPoint" 
              placeholder="请选择考核指标" 
              clearable
              filterable
              style="width: 200px">
              <el-option
                v-for="item in assessmentPointList"
                :key="item.id"
                :label="item.pointName"
                :value="item.id">
              </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 filteredClassList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select 
              v-model="searchForm.type" 
              placeholder="请选择类型" 
              clearable
              style="width: 200px">
              <el-option label="加分" value="1" />
              <el-option label="减分" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              placeholder="选择开始时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              placeholder="选择结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 200px" />
          </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-row>

      <!-- 操作按钮 -->
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button 
            icon="FolderAdd" 
            type="primary" 
            class="ml10" 
            @click="formDialogRef.openDialog()">
            新 增
          </el-button>
          <el-button 
            icon="Upload" 
            type="success" 
            class="ml10" 
            @click="handleImport">
            导 入
          </el-button>
          <el-button 
            icon="Download" 
            type="warning" 
            class="ml10" 
            @click="handleExport">
            导 出
          </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"
        @sort-change="sortChangeHandle">
        <el-table-column type="index" label="序号" 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>
            <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 === 'assessmentCategory'" #default="scope">
              <span>{{ getAssessmentCategoryName(scope.row.assessmentCategory) || '-' }}</span>
            </template>
            <!-- 考核指标列特殊模板 -->
            <template v-else-if="col.prop === 'assessmentPoint'" #default="scope">
              <span>{{ getAssessmentPointName(scope.row.assessmentPoint) || '-' }}</span>
            </template>
            <!-- 类型列特殊模板 -->
            <template v-else-if="col.prop === 'type'" #default="scope">
              <el-tag size="small" :type="scope.row.type === '1' ? 'success' : scope.row.type === '2' ? 'danger' : 'info'" effect="plain">
                {{ scope.row.type === '1' ? '加分' : scope.row.type === '2' ? '减分' : '-' }}
              </el-tag>
            </template>
            <!-- 分数列特殊模板 -->
            <template v-else-if="col.prop === 'score'" #default="scope">
              <el-tag v-if="scope.row.score !== undefined && scope.row.score !== null" size="small" :type="scope.row.score >= 0 ? 'success' : 'danger'" effect="plain">
                {{ scope.row.score }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template #header>
            <el-icon><Setting /></el-icon>
            <span style="margin-left: 4px">操作</span>
          </template>
          <template #default="scope">
            <el-button 
              icon="Edit" 
              text 
              type="primary" 
              @click="handleAppeal(scope.row)">
              申诉
            </el-button>
            <el-button 
              icon="Edit" 
              text 
              type="primary" 
              @click="formDialogRef.openDialog(scope.row.id)">
              编辑
            </el-button>
            <el-button 
              icon="Delete" 
              text 
              type="danger" 
              @click="handleDelete([scope.row.id])">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 编辑、新增  -->
    <FormDialog ref="formDialogRef" @refresh="getDataList(false)" />
    
    <!-- 导入对话框 -->
    <upload-excel
      ref="uploadExcelRef"
      :title="'导入班主任考核'"
      :url="'/stuwork/classmasterevaluation/importData'"
      :temp-url="templateUrl"
      @refreshDataList="getDataList" />
    
    <!-- 申诉对话框 -->
    <el-dialog 
      title="申诉" 
      v-model="appealDialogVisible"
      :close-on-click-modal="false" 
      draggable
      width="600px">
      <el-form :model="appealForm" label-width="100px">
        <el-form-item label="考核记录">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="班号">{{ appealForm.virtualClassNo || '-' }}</el-descriptions-item>
            <el-descriptions-item label="班主任">{{ appealForm.realName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="考核项目">{{ getAssessmentCategoryName(appealForm.assessmentCategory) || '-' }}</el-descriptions-item>
            <el-descriptions-item label="考核指标">{{ getAssessmentPointName(appealForm.assessmentPoint) || '-' }}</el-descriptions-item>
            <el-descriptions-item label="类型">
              {{ appealForm.type === '1' ? '加分' : appealForm.type === '2' ? '减分' : '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="分数">{{ appealForm.score || '-' }}</el-descriptions-item>
            <el-descriptions-item label="考核日期">{{ appealForm.recordDate || '-' }}</el-descriptions-item>
            <el-descriptions-item label="情况说明" :span="2">{{ appealForm.remarks || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-form-item>
        <el-form-item label="申诉理由">
          <el-input
            v-model="appealForm.appealReason"
            type="textarea"
            :rows="4"
            placeholder="请输入申诉理由"
            maxlength="500"
            show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="appealDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAppeal">提 交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ClassMasterEvaluation">
import { ref, reactive, defineAsyncComponent, computed, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs, exportData } from "/@/api/stuwork/classmasterevaluation";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { getDeptList } from '/@/api/basic/basicclass'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { getList as getAssessmentCategoryList } from '/@/api/stuwork/assessmentcategory'
import { getList as getAssessmentPointList } from '/@/api/stuwork/assessmentpoint'
import TableColumnControl from '/@/components/TableColumnControl/index.vue'

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
import { List, Grid, UserFilled, Tickets, DataAnalysis, Collection, Calendar, User, Document, Setting, Menu } from '@element-plus/icons-vue'
import { getTableConfigFromLocal, saveTableConfigToLocal, updateUserTableConfig } from '/@/api/admin/usertable'

// 定义变量内容
const route = useRoute()
const formDialogRef = ref()
const columnControlRef = ref<any>()
const searchFormRef = ref()
const uploadExcelRef = ref()
// 搜索变量
const showSearch = ref(true)
const deptList = ref<any[]>([])
const classList = ref<any[]>([])
const assessmentCategoryList = ref<any[]>([])
const assessmentPointList = ref<any[]>([])
const appealDialogVisible = ref(false)
// 模板文件URL - 标记为 assets 文件夹下的文件
const templateUrl = ref('assets/file/班主任考核导入模板.xlsx')
const appealForm = reactive({
  id: '',
  virtualClassNo: '',
  realName: '',
  assessmentCategory: '',
  assessmentPoint: '',
  type: '',
  score: '',
  recordDate: '',
  remarks: '',
  appealReason: ''
})

// 表格列配置
const tableColumns = [
  { prop: 'virtualClassNo', label: '班号' },
  { prop: 'realName', label: '班主任' },
  { prop: 'assessmentCategory', label: '考核项目' },
  { prop: 'assessmentPoint', label: '考核指标' },
  { prop: 'type', label: '类型' },
  { prop: 'score', label: '分数' },
  { prop: 'recordDate', label: '考核日期' },
  { prop: 'createBy', label: '考核人' },
  { prop: 'remarks', label: '情况说明' }
]

// 列配置映射（用于图标）
const columnConfigMap: Record<string, { icon: any }> = {
  virtualClassNo: { icon: Grid },
  realName: { icon: UserFilled },
  assessmentCategory: { icon: Tickets },
  assessmentPoint: { icon: DataAnalysis },
  type: { icon: Collection },
  score: { icon: DataAnalysis },
  recordDate: { icon: Calendar },
  createBy: { icon: User },
  remarks: { icon: Document }
}

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

// 从本地统一存储加载配置
const loadSavedConfig = () => {
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  const savedConfig = getTableConfigFromLocal(storageKey)
  
  if (savedConfig && savedConfig.visibleColumns) {
    const validColumns = tableColumns.map(col => col.prop || col.label)
    const filteredSaved = savedConfig.visibleColumns.filter((col: string) => validColumns.includes(col))
    visibleColumns.value = filteredSaved.length > 0 ? filteredSaved : validColumns
  } else {
    visibleColumns.value = tableColumns.map(col => col.prop || col.label)
  }
  
  if (savedConfig && savedConfig.columnOrder) {
    const validColumns = tableColumns.map(col => col.prop || col.label)
    columnOrder.value = savedConfig.columnOrder.filter((key: string) => validColumns.includes(key))
    validColumns.forEach(key => {
      if (!columnOrder.value.includes(key)) {
        columnOrder.value.push(key)
      }
    })
  } 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
  })
  // 保存到本地统一存储
  saveTableConfigToLocal(storageKey, { visibleColumns: selectableColumns })
  // 异步保存到后端
  updateUserTableConfig(storageKey, { visibleColumns: selectableColumns }).catch(() => {})
}

// 监听列排序变化
const handleColumnOrderChange = (order: string[]) => {
  columnOrder.value = order
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  // 保存到本地统一存储
  saveTableConfigToLocal(storageKey, { columnOrder: order })
  // 异步保存到后端
  updateUserTableConfig(storageKey, { columnOrder: order }).catch(() => {})
}

// 搜索表单
const searchForm = reactive({
  deptCode: '',
  assessmentCategory: '',
  assessmentPoint: '',
  classCode: '',
  type: '',
  startTime: '',
  endTime: ''
})

// 根据学院筛选班级列表
const filteredClassList = computed(() => {
  if (!searchForm.deptCode) {
    return classList.value
  }
  return classList.value.filter((item: any) => item.deptCode === searchForm.deptCode)
})

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: searchForm,
  pageList: fetchList,
  props: {
    item: 'records',
    totalCount: 'total'
  }
})

// table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)

// 学院选择变化
const handleDeptChange = () => {
  // 清空班号选择
  searchForm.classCode = ''
}

// 查询
const handleSearch = () => {
  getDataList()
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  searchForm.deptCode = ''
  searchForm.assessmentCategory = ''
  searchForm.assessmentPoint = ''
  searchForm.classCode = ''
  searchForm.type = ''
  searchForm.startTime = ''
  searchForm.endTime = ''
  getDataList()
}

// 删除
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('确定要删除选中的记录吗？')
  } catch {
    return
  }

  try {
    await delObjs(ids)
    useMessage().success('删除成功')
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg || '删除失败')
  }
}

// 导入
const handleImport = () => {
  if (uploadExcelRef.value) {
    uploadExcelRef.value.show()
  }
}

// 导出
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 handleAppeal = (row: any) => {
  appealDialogVisible.value = true
  Object.assign(appealForm, {
    id: row.id || '',
    virtualClassNo: row.virtualClassNo || '',
    realName: row.realName || '',
    assessmentCategory: row.assessmentCategory || '',
    assessmentPoint: row.assessmentPoint || '',
    type: row.type || '',
    score: row.score || '',
    recordDate: row.recordDate || '',
    remarks: row.remarks || '',
    appealReason: ''
  })
}

// 提交申诉
const submitAppeal = async () => {
  if (!appealForm.appealReason || appealForm.appealReason.trim() === '') {
    useMessage().warning('请输入申诉理由')
    return
  }
  
  try {
    // TODO: 调用申诉接口
    useMessage().success('申诉提交成功')
    appealDialogVisible.value = false
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg || '申诉提交失败')
  }
}


// 获取学院列表
const getDeptListData = async () => {
  try {
    const res = await getDeptList()
    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 getAssessmentCategoryListData = async () => {
  try {
    const res = await getAssessmentCategoryList()
    if (res.data) {
      assessmentCategoryList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    assessmentCategoryList.value = []
  }
}

// 获取考核指标列表
const getAssessmentPointListData = async () => {
  try {
    const res = await getAssessmentPointList()
    if (res.data) {
      assessmentPointList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    assessmentPointList.value = []
  }
}

// 根据考核项目ID获取名称
const getAssessmentCategoryName = (id: any) => {
  if (!id) return ''
  const category = assessmentCategoryList.value.find(item => String(item.id) === String(id))
  return category ? category.category : ''
}

// 根据考核指标ID获取名称
const getAssessmentPointName = (id: any) => {
  if (!id) return ''
  const point = assessmentPointList.value.find(item => String(item.id) === String(id))
  return point ? point.pointName : ''
}

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