<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"
							@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" 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">
							<el-button icon="Download" type="primary" @click="handleExport" :loading="exportLoading"> 导出 </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"
							: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>
					</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="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="ActivityInfoSubSignup">
import { reactive, ref, onMounted, computed } from 'vue';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObj, getActivityInfoList, getActivityInfoSubList } from '/@/api/stuwork/activityinfosubsignup';
import { makeExportActivitySignUpDetailTask } from '/@/api/stuwork/file';
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,
	Search,
	Document as DocIcon,
} from '@element-plus/icons-vue';
import { useTableColumnControl } from '/@/hooks/tableColumn';

// 定义变量内容
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 },
];

// 使用表格列控制 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: '',
		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 {
		await makeExportActivitySignUpDetailTask(state.queryForm);
		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 = [];
	}
};

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

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