<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="state.queryForm" 
          ref="searchFormRef" 
          :inline="true" 
          @keyup.enter="getDataList"
          class="search-form">
          <el-form-item label="活动主题" prop="activityInfoId">
            <el-select 
              v-model="state.queryForm.activityInfoId" 
              placeholder="请选择活动主题" 
              clearable
              filterable
              style="width: 300px">
              <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>
            <el-button type="primary" icon="Search" @click="getDataList">查询</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"><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" 
              :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>
              <!-- 开始时间列特殊模板 -->
              <template v-if="col.prop === 'startTime'" #default="scope">
                <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
              <!-- 结束时间列特殊模板 -->
              <template v-else-if="col.prop === 'endTime'" #default="scope">
                <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
              <!-- 报名人数限制列特殊模板 -->
              <template v-else-if="col.prop === 'maxNum'" #default="scope">
                <el-tag v-if="scope.row.maxNum !== undefined && scope.row.maxNum !== null" size="small" type="success" effect="plain" round>
                  {{ scope.row.maxNum }}
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </template>
          <el-table-column prop="remarks" label="活动说明" show-overflow-tooltip align="center" min-width="200">
            <template #header>
              <el-icon><EditPen /></el-icon>
              <span style="margin-left: 4px">活动说明</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="Edit"
                link
                type="primary"
                @click="handleSignUp(scope.row)">
                报名
              </el-button>
              <el-button
                icon="Delete"
                link
                type="danger"
                @click="handleDelete(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>
  </div>
</template>

<script setup lang="ts" name="ActivityInfoSub">
import { reactive, ref, onMounted } from 'vue'
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObj, getActivityInfoList, signUp } from "/@/api/stuwork/activityinfosub";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { parseTime } from "/@/utils/formatTime";
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
import { List, Trophy, Document, Files, Calendar, UserFilled, EditPen, Setting, Menu, Search } from '@element-plus/icons-vue'
import { useTableColumnControl } from '/@/hooks/tableColumn'

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

// 表格列配置
const tableColumns = [
  { prop: 'activityTheme', label: '活动主题', icon: Trophy, minWidth: 200 },
  { prop: 'subTitle', label: '子项目名称', icon: Document, minWidth: 150 },
  { prop: 'projectDescription', label: '项目描述', icon: Files, minWidth: 200 },
  { prop: 'startTime', label: '开始时间', icon: Calendar, width: 180 },
  { prop: 'endTime', label: '结束时间', icon: Calendar, width: 180 },
  { prop: 'maxNum', label: '报名人数限制', icon: UserFilled, width: 120 }
]

// 使用表格列控制 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: {
    activityInfoId: ''
  },
  pageList: fetchList,
  props: {
    item: 'records',
    totalCount: 'total'
  },
  createdIsNeed: true
})

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

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields()
  state.queryForm.activityInfoId = ''
  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 handleSignUp = async (row: any) => {
  const { confirm } = useMessageBox()
  try {
    await confirm(`确定要报名参加【${row.subTitle || '该活动'}】吗？`)
    state.loading = true
    await signUp({
      activityInfoId: row.activityInfoId,
      id: row.id,
      remarks: ''
    })
    useMessage().success('报名成功')
    getDataList()
  } catch (err: any) {
    if (err !== 'cancel') {
      useMessage().error(err.msg || '报名失败')
    }
  } finally {
    state.loading = 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 = []
  }
}

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

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