<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">
              <el-button 
                icon="FolderAdd" 
                type="primary" 
                @click="formDialogRef.openDialog()">
                新 增
              </el-button>
              <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"
          @sort-change="sortChangeHandle"
          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>
              <template #header>
                <el-icon><component :is="columnConfigMap[col.prop]?.icon || Document" /></el-icon>
                <span style="margin-left: 4px">{{ col.label }}</span>
              </template>
              <!-- 假期模式列特殊模板 -->
              <template v-if="col.prop === 'isHoliday'" #default="scope">
                <StatusTag 
                  :value="scope.row.isHoliday"
                  :options="[{ label: '开启', value: '1' }, { label: '关闭', value: '0' }]"
                  :type-map="{ '1': { type: 'success', effect: 'light' }, '0': { type: 'info', effect: 'light' } }"
                />
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" align="center" fixed="right" width="280">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button 
                icon="Switch" 
                link 
                :type="scope.row.isHoliday === '1' ? 'warning' : 'success'"
                @click="handleToggleHoliday(scope.row)">
                {{ scope.row.isHoliday === '1' ? '关闭假期模式' : '开启假期模式' }}
              </el-button>
              <el-button 
                icon="View" 
                link 
                type="primary" 
                @click="handleViewDetail(scope.row)">
                查看详情
              </el-button>
              <el-button 
                icon="Edit" 
                link 
                type="primary" 
                @click="formDialogRef.openDialog(scope.row.id)">
                编辑
              </el-button>
              <el-button 
                icon="Delete" 
                link 
                type="danger" 
                @click="handleDelete([scope.row.id])">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

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

    <!-- 编辑、新增  -->
    <FormDialog ref="formDialogRef" @refresh="getDataList(false)" />
    
    <!-- 详情对话框 -->
    <el-dialog 
      title="门禁规则详情" 
      v-model="detailDialogVisible"
      :close-on-click-modal="false" 
      draggable
      width="800px">
      <div v-if="detailData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="规则名称">{{ detailData.ruleName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="绑定班级">{{ detailData.classNames || '-' }}</el-descriptions-item>
          <el-descriptions-item label="假期模式">
            {{ detailData.isHoliday === '1' ? '开启' : '关闭' }}
          </el-descriptions-item>
        </el-descriptions>
        <!-- 这里可以根据需要展示更多详情信息 -->
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup lang="ts" name="EntranceRule">
import { ref, reactive, defineAsyncComponent, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs, getObj, openHoliday } from "/@/api/stuwork/entrancerule";
import { useMessage, useMessageBox } from "/@/hooks/message";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
import { List, Document, Grid, CircleCheck, Setting, Menu } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumnControl'
import '/@/styles/modern-page.scss'
import { defineAsyncComponent as defineStatusTag } from 'vue'
const StatusTag = defineStatusTag(() => import('/@/components/StatusTag/index.vue'))

// 定义变量内容
const route = useRoute()
const formDialogRef = ref()
const columnControlRef = ref<any>()
// 搜索变量
const showSearch = ref(false) // 没有搜索条件，隐藏搜索区域
const detailDialogVisible = ref(false)
const detailData = ref<any>(null)

// 表格列配置
const tableColumns = [
  { prop: 'ruleName', label: '规则名称' },
  { prop: 'classNames', label: '绑定班级' },
  { prop: 'isHoliday', label: '假期模式' }
]

// 列配置映射（用于图标）
const columnConfigMap: Record<string, { icon: any }> = {
  ruleName: { icon: Document },
  classNames: { icon: Grid },
  isHoliday: { icon: CircleCheck }
}

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

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

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

// 删除
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 handleToggleHoliday = async (row: any) => {
  const action = row.isHoliday === '1' ? '关闭' : '开启'
  try {
    await useMessageBox().confirm(`确定要${action}假期模式吗？`)
  } catch {
    return
  }

  try {
    await openHoliday({
      id: row.id,
      isHoliday: row.isHoliday === '1' ? '0' : '1'
    })
    useMessage().success(`${action}成功`)
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg || `${action}失败`)
  }
}

// 查看详情
const handleViewDetail = async (row: any) => {
  try {
    const res = await getObj({ id: row.id })
    if (res.data) {
      detailData.value = res.data
      detailDialogVisible.value = true
    }
  } catch (err: any) {
    useMessage().error(err.msg || '获取详情失败')
  }
}

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