<template>
  <div class="modern-page-container">
    <div class="page-wrapper">
      <!-- 内容卡片 -->
      <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">
              <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 === 'unionType'" #default="scope">
                <el-tag size="small" type="info" effect="plain" round>
                  {{ formatUnionType(scope.row.unionType) }}
                </el-tag>
              </template>
              <!-- 排序列特殊模板 -->
              <template v-else-if="col.prop === 'sort'" #default="scope">
                <el-tag v-if="scope.row.sort !== undefined && scope.row.sort !== null" size="small" type="primary" effect="plain" round>
                  {{ scope.row.sort }}
                </el-tag>
                <span v-else>-</span>
              </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="EditPen" 
                link
                type="primary" 
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" :image-size="120">
            </el-empty>
          </template>
        </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="StuUnion">
import { reactive, ref, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList } from "/@/api/stuwork/stuunion";
import { useMessage } from "/@/hooks/message";
import { getDicts } from "/@/api/admin/dict";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import FormDialog from './form.vue'
import { 
  List, OfficeBuilding, Collection, Location, UserFilled, Sort, Setting, Menu, Calendar, Document 
} from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

// 定义变量内容
const formDialogRef = ref()
const columnControlRef = ref<any>()
const showSearch = ref(false)
const unionTypeList = ref<any[]>([])

// 表格列配置
const tableColumns = [
  { prop: 'unionName', label: '学生会名称', icon: OfficeBuilding, minWidth: 200 },
  { prop: 'unionType', label: '类型', icon: Collection, width: 120 },
  { prop: 'address', label: '联系地址', icon: Location, minWidth: 200 },
  { prop: 'maintainer', label: '负责人', icon: UserFilled, width: 120 },
  { prop: 'sort', label: '排序', icon: Sort, width: 80 }
]

// 列配置映射（用于图标）
const columnConfigMap: Record<string, { icon: any }> = {
  unionName: { icon: OfficeBuilding },
  unionType: { icon: Collection },
  address: { icon: Location },
  maintainer: { icon: UserFilled },
  sort: { icon: Sort }
}

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

// 表格样式
const tableStyle = {
  cellStyle: { padding: '8px 0' },
  headerCellStyle: { background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }
}

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

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

// 格式化类型
const formatUnionType = (value: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  const dictItem = unionTypeList.value.find(item => item.value == value)
  return dictItem ? dictItem.label : value
}

// 编辑
const handleEdit = (row: any) => {
  formDialogRef.value?.openDialog('edit', row)
}

// 获取类型字典
const getUnionTypeDict = async () => {
  try {
    const res = await getDicts('union_type')
    if (res.data && Array.isArray(res.data)) {
      unionTypeList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    } else {
      unionTypeList.value = []
    }
  } catch (err) {
    unionTypeList.value = []
  }
}

// 初始化
onMounted(() => {
  getUnionTypeDict()
})
</script>

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