<template>
	<div class="tab-index-container">
		<!-- 搜索表单 -->
		<search-form v-show="showSearch" :model="queryForm" ref="searchFormRef" @keyup-enter="getDataList">
			<template #default="{ visible }">
				<template v-if="visible">
					<el-form-item label="招生计划" prop="groupId">
						<el-select v-model="queryForm.groupId" filterable clearable placeholder="请选择招生计划" @change="chanMajor">
							<el-option v-for="item in planList" :key="item.id" :label="item.groupName" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="学院" prop="deptCode">
						<el-select v-model="queryForm.deptCode" filterable clearable placeholder="请选择学院">
							<el-option v-for="item in deptList" :key="item.deptCode" :label="item.deptName" :value="item.deptCode" />
						</el-select>
					</el-form-item>
					<el-form-item label="录取专业" prop="confirmedMajor">
						<el-select v-model="queryForm.confirmedMajor" filterable clearable placeholder="请选择录取专业">
							<el-option
								v-for="item in planMajorList"
								:key="item.majorCode"
								:label="item.majorName + '(' + item.learnYear + '年制)'"
								:value="item.majorCode"
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="唯一号/姓名/身份证号/学校名称" prop="search">
						<el-input v-model="queryForm.search" clearable placeholder="唯一号/姓名/身份证号/学校名称" />
					</el-form-item>
				</template>
				<template v-else>
					<el-form-item label="缴费状态" prop="paystatus">
						<el-select v-model="queryForm.paystatus" filterable clearable placeholder="请选择缴费状态">
							<el-option v-for="item in paystatusList" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="推送状态" prop="pushed">
						<el-select v-model="queryForm.pushed" filterable clearable placeholder="请选择推送状态">
							<el-option v-for="item in pushedList" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="报到状态" prop="backSchoolState">
						<el-select v-model="queryForm.backSchoolState" filterable clearable placeholder="请选择报到状态">
							<el-option v-for="item in backSchoolStateList" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				</template>
			</template>
			<template #actions>
				<el-form-item>
					<el-button type="primary" icon="Search" @click="getDataList">查询</el-button>
					<el-button icon="Refresh" class="ml10" @click="resetQuery">重置</el-button>
				</el-form-item>
			</template>
		</search-form>

		<!-- 操作按钮 -->
		<div class="action-buttons-wrapper mb15">
			<el-button type="warning" plain icon="Download" @click="handleExport"> 名单导出 </el-button>
			<el-button v-if="hasAuth('recruit_recruitstudentsignup_allCX')" type="primary" plain icon="Search" class="ml10" @click="updateAllFS">
				批量查询
			</el-button>
			<right-toolbar @queryTable="getDataList" class="ml10" style="float: right" v-model:showSearch="showSearch"></right-toolbar>
		</div>

		<!-- 表格 -->
		<div class="table-wrapper">
			<el-table
				ref="tableRef"
				:data="state.dataList"
				v-loading="state.loading"
				border
				stripe
				height="100%"
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
			>
				<el-table-column type="index" label="序号" width="60" align="center" />
				<el-table-column prop="serialNumber" label="唯一号" align="center" show-overflow-tooltip />
				<el-table-column prop="deptCode" label="学院" align="center" show-overflow-tooltip>
					<template #default="scope">
						<span v-if="scope.row.auditStatus == 20">
							{{ getDeptName(scope.row.deptCode) }}
						</span>
					</template>
				</el-table-column>
				<el-table-column prop="confirmedMajor" label="录取专业" align="center" show-overflow-tooltip>
					<template #default="scope">
						<span v-if="scope.row.auditStatus == 20">
							{{ getMajorName(scope.row.confirmedMajor) }}
						</span>
					</template>
				</el-table-column>
				<el-table-column prop="name" label="姓名" align="center" show-overflow-tooltip />
				<el-table-column prop="gender" label="性别" width="80" align="center" show-overflow-tooltip>
					<template #default="scope">
						<GenderTag :sex="scope.row.gender" />
					</template>
				</el-table-column>
				<el-table-column prop="idNumber" label="身份证号" width="190" align="center" show-overflow-tooltip />
				<el-table-column prop="parentTelOne" label="家长电话1" align="center" show-overflow-tooltip />
				<el-table-column prop="parentTelTwo" label="家长电话2" align="center" show-overflow-tooltip />
				<el-table-column prop="backSchoolState" label="报到状态" align="center" show-overflow-tooltip>
					<template #default="scope">
						<template v-if="getBackSchoolStateConfig(scope.row.backSchoolState)">
							<!-- 有备注信息时，使用 popover 包裹 ClickableTag -->
							<DetailPopover
								v-if="scope.row.backSchoolRemark"
								title="报到详情"
								:width="300"
								:items="[
									{
										label: '报到状态',
										layout: 'horizontal',
										content: getBackSchoolStateConfig(scope.row.backSchoolState)?.label,
									},
									{
										label: '备注信息',
										content: scope.row.backSchoolRemark,
										contentClass: 'reason-content',
									},
								]"
							>
								<template #reference>
									<ClickableTag
										:type="getBackSchoolStateConfig(scope.row.backSchoolState)?.type || 'info'"
										:left-icon="getBackSchoolStateConfig(scope.row.backSchoolState)?.icon"
									>
										{{ getBackSchoolStateConfig(scope.row.backSchoolState)?.label }}
									</ClickableTag>
								</template>
								<template #content-0>
									<ClickableTag
										:type="getBackSchoolStateConfig(scope.row.backSchoolState)?.type || 'info'"
										:left-icon="getBackSchoolStateConfig(scope.row.backSchoolState)?.icon"
										:right-icon="null"
									>
										{{ getBackSchoolStateConfig(scope.row.backSchoolState)?.label }}
									</ClickableTag>
								</template>
								<template #content-1>
									<div class="reason-content">
										<el-icon class="reason-icon"><Warning /></el-icon>
										<span>{{ scope.row.backSchoolRemark }}</span>
									</div>
								</template>
							</DetailPopover>
							<!-- 无备注时，直接显示 ClickableTag -->
							<ClickableTag
								v-else
								:type="getBackSchoolStateConfig(scope.row.backSchoolState)?.type || 'info'"
								:left-icon="getBackSchoolStateConfig(scope.row.backSchoolState)?.icon"
								:right-icon="null"
							>
								{{ getBackSchoolStateConfig(scope.row.backSchoolState)?.label }}
							</ClickableTag>
						</template>
						<span v-else class="empty-text">-</span>
					</template>
				</el-table-column>
				<el-table-column prop="paiedOffline" label="缴费状态" width="110" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-tag
							v-if="getStatusConfig(paystatusList, scope.row.paiedOffline)"
							:type="getStatusConfig(paystatusList, scope.row.paiedOffline)?.type"
						>
							{{ getStatusConfig(paystatusList, scope.row.paiedOffline)?.label }}
						</el-tag>
						<span v-else class="empty-text">{{ getStatusConfig(paystatusList, scope.row.paiedOffline)?.label || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="pushed" label="推送状态" width="110" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-tag :type="getStatusConfig(pushedList, scope.row.pushed)?.type">
							{{ getStatusConfig(pushedList, scope.row.pushed)?.label }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="300" align="center" fixed="right">
					<template #default="scope">
						<el-button
							v-if="
								hasAuth('recruit_recruitstudentsignup_show') &&
								scope.row.pushed == '1' &&
								scope.row.paiedOffline != '10' &&
								scope.row.clfPayCode != undefined &&
								scope.row.clfPayCode != ''
							"
							type="primary"
							link
							:icon="Tickets"
							@click="showPayCode(scope.row)"
						>
							支付二维码
						</el-button>
						<el-button v-if="hasAuth('recruit_recruitstudentsignup_back')" type="primary" link icon="EditPen" @click="handleCheckIn(scope.row)">
							报到
						</el-button>
						<el-button
							v-if="hasAuth('recruit_recruitstudentsignup_leaveSchool')"
							type="primary"
							link
							icon="EditPen"
							@click="handleLeaveSchool(scope.row, false)"
						>
							退档
						</el-button>
						<el-button v-if="hasAuth('recruit_leaveSchool_force')" type="primary" link icon="EditPen" @click="handleLeaveSchool(scope.row, true)">
							强制退档
						</el-button>
					</template>
				</el-table-column>
			</el-table>

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

		<!-- 支付二维码弹窗 -->
		<el-dialog v-model="dialogFormVisible" title="支付二维码" width="800px" @close="dialogFormVisible = false">
			<el-table :data="tableData" border>
				<el-table-column label="唯一号" prop="serialNumber" align="center" />
				<el-table-column label="姓名" prop="name" align="center" />
				<el-table-column label="家长手机号" prop="parentTelOne" align="center" />
				<el-table-column label="操作" align="center">
					<template #default>
						<el-button type="danger" icon="Search" @click="updateFS">立即查询</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div style="padding-top: 20px">
				<div id="payQrcode1" style="display: inline-block">
					{{ payQrcode1Msg }}
				</div>
				<!-- <vue-qr :text="payQrcode1" :size="200" v-if="showPrise1" style="display: inline-block"></vue-qr> -->

				<div id="payQrcode2" style="display: inline-block">
					{{ payQrcode2Msg }}
				</div>
				<!-- <vue-qr :text="payQrcode2" :size="200" v-if="showPrise2" style="display: inline-block"></vue-qr> -->

				<div id="payQrcode3" style="display: inline-block">
					{{ payQrcode3Msg }}
				</div>
				<!-- <vue-qr :text="payQrcode3" :size="200" v-if="showPrise3" style="display: inline-block"></vue-qr> -->
			</div>
			<span style="color: red; padding-top: 20px"
				>**
				此界面为查询学生缴款二维码，如有收不到微信推送，或手机号填错的，可直接在此扫码支付，支付成功后，请手动点击"立即查询"按钮，查询该生的缴费情况;因财政收费系统有一定的滞后性，如点击"立即查询"后任显示未交费，请稍后再继续查询，或重新点击"立即查询"按钮
				**</span
			>
		</el-dialog>

		<stu-check-in ref="stuCheckInRef" @reload="refreshChange" />
	</div>
</template>

<script setup lang="ts" name="backSchoolCheckinTabIndex">
import { ref, reactive, onMounted, nextTick, defineAsyncComponent, defineExpose } from 'vue';
import { useAuth } from '/@/hooks/auth';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { getList } from '/@/api/recruit/recruitstudentplangroup';
import { backSchoolStuPage, leaveSchool } from '/@/api/recruit/recruitstudentsignup';
import { getDeptList } from '/@/api/basic/basicclass';
import { listPlanByCondition as planMajor } from '/@/api/recruit/recruitstudentplan';
import { updateFs, updateAllFS as updateAllFSApi } from '/@/api/purchase/financenormalstu';
import { getDicts } from '/@/api/admin/dict';
import { PAY_STATUS_LIST, PUSHED_STATUS_LIST, getStatusConfig, getCheckInStatusConfig } from '/@/config/global';
import { CircleCheck, CircleClose, DocumentChecked, Warning, Clock, Tickets } from '@element-plus/icons-vue';

const StuCheckIn = defineAsyncComponent(() => import('./stu-check-in.vue'));
const GenderTag = defineAsyncComponent(() => import('/@/components/GenderTag/index.vue'));
const SearchForm = defineAsyncComponent(() => import('/@/components/SearchForm/index.vue'));
const ClickableTag = defineAsyncComponent(() => import('/@/components/ClickableTag/index.vue'));
const DetailPopover = defineAsyncComponent(() => import('/@/components/DetailPopover/index.vue'));
const { hasAuth } = useAuth();
// 消息提示 hooks
const message = useMessage();

// 表格引用
const tableRef = ref();
const searchFormRef = ref();
const stuCheckInRef = ref();

// 搜索表单显示状态
const showSearch = ref(true);

// 数据
const planList = ref<any[]>([]);
const planMajorList = ref<any[]>([]);
const deptList = ref<any[]>([]);
const backSchoolStateList = ref<any[]>([]);
const paystatusList = PAY_STATUS_LIST;
const pushedList = PUSHED_STATUS_LIST;

// 查询表单
const queryForm = reactive({
	groupId: '',
	deptCode: '',
	confirmedMajor: '',
	search: '',
	paystatus: '',
	pushed: '',
	backSchoolState: '',
	isOut: '1',
	auditStatus: '20',
});

// 弹窗状态
const dialogFormVisible = ref(false);
const tableData = ref<any[]>([]);
const payQrcode1 = ref('');
const showPrise1 = ref(false);
const payQrcode1Msg = ref('');
const payQrcode2 = ref('');
const payQrcode2Msg = ref('');
const showPrise2 = ref(false);
const payQrcode3 = ref('');
const payQrcode3Msg = ref('');
const showPrise3 = ref(false);

// 获取学院名称
const getDeptName = (deptCode: string) => {
	const item = deptList.value.find((item) => item.deptCode === deptCode);
	return item ? item.deptName : '';
};

// 获取专业名称
const getMajorName = (majorCode: string) => {
	const item = planMajorList.value.find((item) => item.majorCode === majorCode);
	return item ? item.majorName : '';
};

// 获取报到状态配置（用于 ClickableTag）
const getBackSchoolStateConfig = (value: string) => {
	return getCheckInStatusConfig(backSchoolStateList.value, value, {
		CircleCheck,
		CircleClose,
		DocumentChecked,
		Warning,
		Clock,
	});
};

// 表格状态
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: queryForm,
	pageList: async (params: any) => {
		const response = await backSchoolStuPage(params);
		return {
			data: {
				records: response.data.records,
				total: response.data.total,
			},
		};
	},
	createdIsNeed: false,
});

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

// 招生计划改变
const chanMajor = async () => {
	if (queryForm.groupId) {
		await getMajorList(queryForm.groupId);
	}
};

// 获取专业列表
const getMajorList = async (groupId: string) => {
	try {
		const data = await planMajor({ groupId });
		planMajorList.value = data.data || [];
	} catch (error) {
		// eslint-disable-next-line no-console
		console.error('获取专业列表失败', error);
	}
};

// 初始化
const init = async () => {
	try {
		// 查询报到状态字典
		const dictData = await getDicts('check_in_status');
		backSchoolStateList.value = dictData.data || [];

		// 查询二级学院信息
		const deptData = await getDeptList();
		deptList.value = deptData.data || [];

		// 获取招生计划列表
		const planData = await getList();
		planList.value = planData.data || [];
		if (planList.value.length > 0) {
			queryForm.groupId = planList.value[0].id;
			await getMajorList(queryForm.groupId);
		}

		getDataList();
	} catch (error) {
		// eslint-disable-next-line no-console
		console.error('初始化失败', error);
	}
};

// 打开报到窗口
const handleCheckIn = (row: any) => {
	nextTick(() => {
		stuCheckInRef.value?.init(row, state.pagination?.current || 1);
	});
};

// 刷新回调
const refreshChange = () => {
	getDataList();
};

// 批量查询
const updateAllFS = async () => {
	if (!queryForm.groupId) {
		message.warning('招生计划不能为空');
		return;
	}

	try {
		const plan = planList.value.find((e) => e.id === queryForm.groupId);
		if (!plan) return;

		const data = await updateAllFSApi({ year: plan.year, stuSource: '1' });
		if (data.data.code == '200') {
			message.success('正在更新所有缴费单状态,请稍后查看更新结果');
		}
	} catch (error: any) {
		// console.log(error)
	}
};

// 导出
const handleExport = async () => {
	if (!queryForm.groupId) {
		message.warning('招生计划不能为空');
		return;
	}

	try {
		await downBlobFile('/recruit/recruitstudentsignup/exportBackData', queryForm, '招生名单导出.xls');
	} catch (error: any) {
		message.error(error.msg || '导出失败');
	}
};

// 立即查询
const updateFS = async () => {
	if (tableData.value.length === 0) return;

	try {
		const serialNumber = tableData.value[0].serialNumber.substring(1, tableData.value[0].serialNumber.length);
		await updateFs({ serialNumber });
		message.success('已提交查询请求，请等待1分钟后重新查询');
		dialogFormVisible.value = false;
		getDataList();
	} catch (error: any) {
		message.error(error.msg || '查询失败');
	}
};

// 显示支付二维码
const showPayCode = (row: any) => {
	showPrise1.value = false;
	showPrise2.value = false;
	showPrise3.value = false;

	payQrcode1.value = '';
	payQrcode2.value = '';
	payQrcode3.value = '';

	if (row.clfPayCode && row.clfPayCode != '') {
		payQrcode1Msg.value = '材料费、代办费';
		showPrise1.value = true;
		payQrcode1.value = 'https://jscz.govpay.ccb.com/online/fsjf?PyF_BillNo=' + row.clfPayCode + '&Verf_CD=blank&Admn_Rgon_Cd=320400';
	} else {
		payQrcode1Msg.value = '';
		showPrise1.value = false;
	}

	if (row.xfPayCode && row.xfPayCode != '') {
		payQrcode2Msg.value = '学费';
		showPrise2.value = true;
		payQrcode2.value = 'https://jscz.govpay.ccb.com/online/fsjf?PyF_BillNo=' + row.xfPayCode + '&Verf_CD=blank&Admn_Rgon_Cd=320400';
	} else {
		payQrcode2Msg.value = '';
		showPrise2.value = false;
	}

	if (row.zdbPayCode && row.zdbPayCode != '') {
		payQrcode3Msg.value = '中德班学费';
		showPrise3.value = true;
		payQrcode3.value = 'https://jscz.govpay.ccb.com/online/fsjf?PyF_BillNo=' + row.zdbPayCode + '&Verf_CD=blank&Admn_Rgon_Cd=320400';
	} else {
		payQrcode3Msg.value = '';
		showPrise3.value = false;
	}

	tableData.value = [row];
	dialogFormVisible.value = true;
};

// 重置查询
const resetQuery = () => {
	searchFormRef.value?.resetFields();
	queryForm.groupId = '';
	queryForm.deptCode = '';
	queryForm.confirmedMajor = '';
	queryForm.search = '';
	queryForm.paystatus = '';
	queryForm.pushed = '';
	queryForm.backSchoolState = '';
	queryForm.isOut = '1';
	queryForm.auditStatus = '20';
	if (planList.value.length > 0) {
		queryForm.groupId = planList.value[0].id;
	}
	getDataList();
};

const handleLeaveSchool = (row: any, force: any) => {
	var str = force? '强制' : '';
	useMessageBox()
		.confirm('是否确认'+str+'办理退档操作？请谨慎操作')
		.then(() => {
			return leaveSchool({ 'id':row.id,'force':force });
		})
		.then(() => {
			message.success('操作成功');
			getDataList();
		});
};

// 暴露方法供父组件调用
defineExpose({
	init,
});

onMounted(() => {
	init();
});
</script>

<style lang="scss" scoped>
.tab-index-container {
	display: flex;
	flex-direction: column;
	height: 100%;
	overflow: hidden;
}

.action-buttons-wrapper {
	flex-shrink: 0;
}

.table-wrapper {
	flex: 1;
	overflow: hidden;
	min-height: 0;
	display: flex;
	flex-direction: column;
}

.table-wrapper :deep(.el-table) {
	flex: 1;
}

.pagination-wrapper {
	flex-shrink: 0;
	padding-top: 15px;
}

.empty-text {
	color: #909399;
}

.reason-content {
	display: flex;
	align-items: flex-start;
	gap: 8px;
	padding: 8px 12px;
	background-color: #fef0f0;
	border-radius: 4px;
	border-left: 3px solid #f56c6c;

	.reason-icon {
		color: #f56c6c;
		font-size: 16px;
		flex-shrink: 0;
		margin-top: 2px;
	}

	span {
		color: #f56c6c;
		font-size: 13px;
		line-height: 1.6;
		word-break: break-all;
		flex: 1;
	}
}
</style>
