<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="activityInfoId">
            <el-select 
              v-model="state.queryForm.activityInfoId" 
              placeholder="请选择活动主题" 
              clearable
              filterable
              style="width: 300px"
              @change="handleActivityChange">
              <el-option
                v-for="item in activityInfoList"
                :key="item.id"
                :label="item.activityTheme"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="子项目" prop="activityInfoSubId">
            <el-select 
              v-model="state.queryForm.activityInfoSubId" 
              placeholder="请选择子项目" 
              clearable
              filterable
              style="width: 300px">
              <el-option
                v-for="item in filteredSubList"
                :key="item.id"
                :label="item.subTitle"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学号/工号" prop="userName">
            <el-input 
              v-model="state.queryForm.userName" 
              placeholder="请输入学号/工号" 
              clearable
              style="width: 200px" />
          </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="Download" 
            type="primary" 
            class="ml10" 
            @click="handleExport"
            :loading="exportLoading">
            导出
          </el-button>
          <right-toolbar  
            v-model:showSearch="showSearch" 
            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">
        <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="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="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>
  </div>
</template>

<script setup lang="ts" name="ActivityInfoSubSignup">
import { reactive, ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj, exportExcel, getActivityInfoList, getActivityInfoSubList } from "/@/api/stuwork/activityinfosubsignup";
import { useMessage, useMessageBox } from "/@/hooks/message";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import { List, Trophy, Document, Files, CreditCard, Avatar, OfficeBuilding, Grid, UserFilled, Phone, Setting, Menu } from '@element-plus/icons-vue'
import { getTableConfigFromLocal, saveTableConfigToLocal, updateUserTableConfig } from '/@/api/admin/usertable'

// 定义变量内容
const route = useRoute()
const searchFormRef = ref()
const columnControlRef = ref()
const showSearch = ref(true)
const exportLoading = ref(false)
const activityInfoList = ref<any[]>([])
const subList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'activityTheme', label: '活动主题', icon: Trophy, minWidth: 200 },
  { prop: 'subTitle', label: '子项目', icon: Document, minWidth: 150 },
  { prop: 'remarks', label: '项目描述', icon: Files, minWidth: 200 },
  { prop: 'userName', label: '学号/工号', icon: CreditCard, width: 120 },
  { prop: 'realName', label: '姓名', icon: Avatar, width: 100 },
  { prop: 'deptName', label: '学院名称', icon: OfficeBuilding, minWidth: 150 },
  { prop: 'classNo', label: '班号', icon: Grid, width: 120 },
  { prop: 'classMasterName', label: '班主任', icon: UserFilled, width: 100 },
  { prop: 'phone', label: '联系电话', icon: Phone, width: 120 }
]

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

// 列变化处理
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
  })
  // 保存到本地统一存储
  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 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 tableStyle = {
  cellStyle: { padding: '8px 0' },
  headerCellStyle: { background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }
}

// 配置 useTable
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    activityInfoId: '',
    activityInfoSubId: '',
    userName: ''
  },
  pageList: fetchList,
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true // 页面加载时自动获取数据
})

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

// 根据活动主题过滤子项目列表
const filteredSubList = computed(() => {
  if (!state.queryForm.activityInfoId) {
    return subList.value
  }
  return subList.value.filter((item: any) => item.activityInfoId === state.queryForm.activityInfoId)
})

// 活动主题变化时，清空子项目选择并重新加载子项目列表
const handleActivityChange = async () => {
  state.queryForm.activityInfoSubId = ''
  if (state.queryForm.activityInfoId) {
    await getSubListData(state.queryForm.activityInfoId)
  } else {
    await getSubListData()
  }
}

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  state.queryForm.activityInfoId = ''
  state.queryForm.activityInfoSubId = ''
  state.queryForm.userName = ''
  getDataList()
}

// 删除
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 handleExport = async () => {
  exportLoading.value = true
  try {
    const res = await exportExcel(state.queryForm)
    // 创建 Blob 对象
    const blob = new Blob([res.data as BlobPart], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `活动报名表_${new Date().getTime()}.xlsx`
    document.body.appendChild(link)
    link.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(link)
    useMessage().success('导出成功')
  } catch (err: any) {
    useMessage().error(err.msg || '导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 获取活动主题列表
const getActivityInfoListData = async () => {
  try {
    const res = await getActivityInfoList()
    if (res.data && Array.isArray(res.data)) {
      activityInfoList.value = res.data
    } else {
      activityInfoList.value = []
    }
  } catch (err) {
    activityInfoList.value = []
  }
}

// 获取子项目列表
const getSubListData = async (activityInfoId?: string) => {
  try {
    const res = await getActivityInfoSubList(activityInfoId)
    if (res.data && Array.isArray(res.data)) {
      subList.value = res.data
    } else {
      subList.value = []
    }
  } catch (err) {
    subList.value = []
  }
}

// 初始化
loadSavedConfig()
onMounted(() => {
  getActivityInfoListData()
  getSubListData()
})
</script>

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

