<template>
  <div class="modern-page-container">
    <div class="page-wrapper">
      <!-- 搜索表单卡片 -->
      <el-card v-show="showSearch" class="search-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Search /></el-icon>
              筛选条件
            </span>
          </div>
        </template>
        <el-form :model="searchForm" ref="searchFormRef" :inline="true" @keyup.enter="handleSearch" class="search-form">
          <el-form-item label="规则名称" prop="ruleName">
            <el-input
              v-model="searchForm.ruleName"
              placeholder="请输入规则名称"
              clearable
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="异动类型" prop="turnoverType">
            <el-select
              v-model="searchForm.turnoverType"
              placeholder="请选择异动类型"
              clearable
              style="width: 200px">
              <el-option
                v-for="item in turnoverTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用" prop="isActive">
            <el-select
              v-model="searchForm.isActive"
              placeholder="请选择状态"
              clearable
              style="width: 200px">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </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-card>

      <!-- 内容卡片 -->
      <el-card class="content-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon class="title-icon"><Setting /></el-icon>
              异动规则配置列表
            </span>
            <div class="header-actions">
              <el-button
                icon="Plus"
                type="primary"
                v-auth="'stuwork_stuturnoverrule_add'"
                @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"
          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 || Document" /></el-icon>
                <span style="margin-left: 4px">{{ col.label }}</span>
              </template>
              <!-- 异动类型列特殊模板 -->
              <template v-if="col.prop === 'turnoverType'" #default="scope">
                <el-tag size="small" type="warning" effect="plain">
                  {{ formatTurnoverType(scope.row.turnoverType) }}
                </el-tag>
              </template>
              <!-- 是否启用列特殊模板 -->
              <template v-else-if="col.prop === 'isActive'" #default="scope">
                <el-tag size="small" :type="scope.row.isActive === '1' ? 'success' : 'danger'" effect="plain">
                  {{ scope.row.isActive === '1' ? '启用' : '禁用' }}
                </el-tag>
              </template>
              <!-- 天数相关列 -->
              <template v-else-if="col.prop === 'minIntervalDays'" #default="scope">
                <span>{{ scope.row.minIntervalDays ?? '-' }} 天</span>
              </template>
              <template v-else-if="col.prop === 'maxDurationDays'" #default="scope">
                <span>{{ scope.row.maxDurationDays ?? '-' }} 天</span>
              </template>
              <template v-else-if="col.prop === 'remindDays'" #default="scope">
                <span>{{ scope.row.remindDays ?? '-' }} 天</span>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="160" align="center" fixed="right">
            <template #header>
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 4px">操作</span>
            </template>
            <template #default="scope">
              <el-button
                icon="Edit"
                link
                type="primary"
                v-auth="'stuwork_stuturnoverrule_edit'"
                @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                icon="Delete"
                link
                type="danger"
                v-auth="'stuwork_stuturnoverrule_del'"
                @click="handleDelete(scope.row)">
                删除
              </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>

    <!-- 新增/编辑表单弹窗 -->
    <form-dialog ref="formDialogRef" @refresh="getDataList" />
  </div>
</template>

<script setup lang="ts" name="StuTurnoverRule">
import { reactive, ref, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj } from "/@/api/stuwork/stuturnoverrule";
import { getDicts } from "/@/api/admin/dict";
import { useMessage, useMessageBox } from "/@/hooks/message";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import FormDialog from './form.vue'
import { List, Setting, Document, Collection, Menu, Search, Clock } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

// 定义变量内容
const route = useRoute()
const searchFormRef = ref()
const columnControlRef = ref<any>()
const showSearch = ref(true)
const turnoverTypeList = ref<any[]>([])
const formDialogRef = ref()

// 表格列配置
const tableColumns = [
  { prop: 'ruleName', label: '规则名称', minWidth: 150 },
  { prop: 'turnoverType', label: '异动类型', width: 120 },
  { prop: 'minIntervalDays', label: '最短间隔', width: 100 },
  { prop: 'maxDurationDays', label: '最长持续', width: 100 },
  { prop: 'remindDays', label: '提醒天数', width: 100 },
  { prop: 'sort', label: '排序', width: 80 },
  { prop: 'isActive', label: '状态', width: 80 },
  { prop: 'ruleDescription', label: '规则描述', minWidth: 200 },
  { prop: 'remarks', label: '备注', minWidth: 150 }
]

// 列配置映射（用于图标显示）
const columnConfigMap: Record<string, { icon: any }> = {
  ruleName: { icon: Document },
  turnoverType: { icon: Collection },
  minIntervalDays: { icon: Clock },
  maxDurationDays: { icon: Clock },
  remindDays: { icon: Clock },
  sort: { icon: Setting },
  isActive: { icon: Setting },
  ruleDescription: { icon: Document },
  remarks: { icon: Document }
}

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

// 搜索表单
const searchForm = reactive({
  ruleName: '',
  turnoverType: '',
  isActive: ''
})

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

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

// 格式化异动类型
const formatTurnoverType = (value: string) => {
  if (!value) return '-'
  const item = turnoverTypeList.value.find((item: any) => item.value === value)
  return item ? item.label : value
}

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

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  searchForm.ruleName = ''
  searchForm.turnoverType = ''
  searchForm.isActive = ''
  getDataList()
}

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

// 删除
const handleDelete = async (row: any) => {
  try {
    await useMessageBox().confirm('确定要删除该异动规则吗？')
    await delObj([row.id])
    useMessage().success('删除成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '删除失败')
    }
  }
}

// 获取异动类型字典
const getTurnoverTypeDict = async () => {
  try {
    const res = await getDicts('turnover_type')
    if (res.data) {
      turnoverTypeList.value = Array.isArray(res.data) ? res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      })) : []
    }
  } catch (err) {
    turnoverTypeList.value = []
  }
}

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

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