<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="teacherNo">
            <el-select 
              v-model="searchForm.teacherNo" 
              placeholder="请选择教师" 
              clearable
              filterable 
              style="width: 200px">
              <el-option
                v-for="item in teacherList"
                :key="item.teacherNo"
                :label="item.realName"
                :value="item.teacherNo">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系方式" prop="telPhone">
            <el-input 
              v-model="searchForm.telPhone" 
              placeholder="请输入联系方式" 
              clearable
              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" 
            @click="formDialogRef.openDialog()"
            v-auth="'stuwork_classmasterresume_add'">
            新 增
          </el-button>
          <right-toolbar  
            v-model:showSearch="showSearch" 
            :export="'stuwork_classmasterresume_export'"
            @exportExcel="exportExcel" 
            class="ml10 mr20" 
            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="序号" width="60" align="center">
          <template #header>
            <el-icon><List /></el-icon>
          </template>
        </el-table-column>
        <el-table-column 
          v-for="col in visibleColumnsSorted" 
          :key="col.prop"
          :prop="col.prop" 
          :label="col.label" 
          :width="col.width"
          :min-width="col.minWidth"
          :show-overflow-tooltip="col.showOverflowTooltip !== false"
          :align="col.align || 'center'">
          <template #header>
            <el-icon v-if="col.icon"><component :is="col.icon" /></el-icon>
            <span :style="{ marginLeft: col.icon ? '4px' : '0' }">{{ col.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" 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="handleViewDetail(scope.row)">
              查看履历详情
            </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)" />
    
    <!-- 履历详情  -->
    <DetailDialog ref="detailDialogRef" />
  </div>
</template>

<script setup lang="ts" name="ClassMasterResume">
import { ref, reactive, defineAsyncComponent, onMounted, nextTick, computed } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList } from "/@/api/stuwork/classmasterresume";
import request from "/@/utils/request";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 尝试直接导入看看是否能解决问题
import DetailDialog from './detail.vue';
import { List, User, CreditCard, Phone, Setting, Menu } from '@element-plus/icons-vue'

// 定义变量内容
const route = useRoute()
const formDialogRef = ref()
const searchFormRef = ref() 
const detailDialogRef = ref()
const columnControlRef = ref()
// 搜索变量 
const showSearch = ref(true) 
// 教师列表
const teacherList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'teacherNoVal', label: '教师', icon: User },
  { prop: 'teacherNo', label: '工号', icon: CreditCard },
  { prop: 'telPhone', label: '联系方式', icon: Phone }
]

// 当前显示的列
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)
  }
}

// 列变化处理
const handleColumnChange = (value: string[]) => {
  visibleColumns.value = value
  const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
  const storageKey = `table-columns-${routePath}`
  const selectableColumns = value.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}`
  localStorage.setItem(`${storageKey}-order`, JSON.stringify(order))
}

// 排序后的表格列
const visibleColumnsSorted = computed(() => {
  const columns = tableColumns.filter(col => {
    const key = col.prop || col.label
    return visibleColumns.value.includes(key)
  })
  
  if (columnOrder.value.length > 0) {
    const orderedColumns: any[] = []
    const unorderedColumns: any[] = []
    
    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 searchForm = reactive({
  teacherNo: '',
  telPhone: ''
})

// 配置 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 getTeacherList = async () => {
  try {
    const res = await request({
      url: '/professional/teacherbase/TeacherBaseList',
      method: 'get'
    })
    teacherList.value = res.data || []
  } catch (err) {
  }
}

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

// 重置
const handleReset = () => {
  searchFormRef.value?.formRef?.resetFields()
  searchForm.teacherNo = ''
  searchForm.telPhone = ''
  getDataList()
}

// 导出excel
const exportExcel = () => {
  downBlobFile(
    '/stuwork/classmasterresume/export', 
    searchForm, 
    '班主任履历.xlsx'
  )
}

// 查看履历详情
const handleViewDetail = async (row: any) => {
  
  if (!row.teacherNo) {
    return
  }
  
  // 确保组件已挂载
  await nextTick()
  
  if (detailDialogRef.value && typeof detailDialogRef.value.openDialog === 'function') {
    detailDialogRef.value.openDialog(row.teacherNo)
  } else {
  }
};

// 初始化
loadSavedConfig()
onMounted(() => {
  getTeacherList()
  // 调试：检查组件是否已挂载
  nextTick(() => {
  })
})
</script>

