<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="batchNo">
						<el-input v-model="searchForm.batchNo" placeholder="请输入批次号" clearable style="width: 180px" />
					</el-form-item>
					<el-form-item label="学号" prop="stuNo">
						<el-input v-model="searchForm.stuNo" placeholder="请输入学号" clearable style="width: 150px" />
					</el-form-item>
					<el-form-item label="姓名" prop="systemRealName">
						<el-input v-model="searchForm.systemRealName" placeholder="请输入姓名" clearable style="width: 120px" />
					</el-form-item>
					<el-form-item label="异常类型" prop="exceptionType">
						<el-select v-model="searchForm.exceptionType" placeholder="请选择异常类型" clearable style="width: 150px">
							<el-option label="姓名不一致" value="1" />
							<el-option label="身份证不一致" value="2" />
							<el-option label="学籍号不一致" value="3" />
							<el-option label="毕业院校不一致" value="4" />
							<el-option label="系统有学籍无" value="5" />
							<el-option label="学籍有系统无" value="6" />
						</el-select>
					</el-form-item>
					<el-form-item label="复核状态" prop="reviewStatus">
						<el-select v-model="searchForm.reviewStatus" placeholder="请选择复核状态" clearable style="width: 120px">
							<el-option label="待复核" value="0" />
							<el-option label="已复核" value="1" />
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" 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"><DocumentChecked /></el-icon>
							学籍比对异常数据
						</span>
						<div class="header-actions">
							<el-upload :show-file-list="false" :before-upload="beforeUpload" :http-request="handleImport" accept=".xlsx,.xls" class="upload-btn">
								<el-button type="primary" icon="Upload" :loading="importLoading">导入比对</el-button>
							</el-upload>
							<el-button type="success" icon="Download" @click="handleDownloadTemplate">下载模板</el-button>
							<el-button type="warning" icon="Download" @click="handleExport">导出异常</el-button>
							<el-button type="info" icon="Bell" @click="handleSend" :disabled="!searchForm.batchNo">下发班主任</el-button>
							<right-toolbar v-model:showSearch="showSearch" class="ml10" @queryTable="getDataList" />
						</div>
					</div>
				</template>

				<!-- 统计卡片 -->
				<el-row :gutter="16" class="stat-row">
					<el-col :span="4">
						<el-statistic title="总异常数" :value="statistics.total" />
					</el-col>
					<el-col :span="4">
						<el-statistic title="待复核" :value="statistics.pending" />
					</el-col>
					<el-col :span="4">
						<el-statistic title="已复核" :value="statistics.reviewed" />
					</el-col>
				</el-row>

				<!-- 表格 -->
				<el-table
					:data="dataList"
					v-loading="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 #default="{ $index }">
							{{ (page.currentPage - 1) * page.pageSize + $index + 1 }}
						</template>
					</el-table-column>
					<el-table-column prop="batchNo" label="批次号" width="160" align="center" />
					<el-table-column prop="stuNo" label="学号" width="120" align="center" />
					<el-table-column label="姓名" width="160" align="center">
						<template #default="{ row }">
							<div>
								<span v-if="row.systemRealName">{{ row.systemRealName }}</span>
								<span v-if="row.systemRealName && row.enrollRealName && row.systemRealName !== row.enrollRealName" class="text-danger">
									/ {{ row.enrollRealName }}
								</span>
								<span v-else-if="row.enrollRealName && !row.systemRealName">{{ row.enrollRealName }}</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="身份证号" width="200" align="center">
						<template #default="{ row }">
							<div>
								<div v-if="row.systemIdCard">系统：{{ row.systemIdCard }}</div>
								<div v-if="row.enrollIdCard && row.enrollIdCard !== row.systemIdCard" class="text-warning">学籍：{{ row.enrollIdCard }}</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="学籍号" width="200" align="center">
						<template #default="{ row }">
							<div>
								<div v-if="row.systemEnrollNo">系统：{{ row.systemEnrollNo }}</div>
								<div v-if="row.nationalEnrollNo && row.nationalEnrollNo !== row.systemEnrollNo" class="text-warning">
									全国：{{ row.nationalEnrollNo }}
								</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="className" label="班级" width="150" />
					<el-table-column prop="classMasterName" label="班主任" width="100" align="center" />
					<el-table-column prop="exceptionType" label="异常类型" width="140" align="center">
						<template #default="{ row }">
							<el-tag :type="getExceptionTagType(row.exceptionType)" size="small">
								{{ getExceptionTypeName(row.exceptionType) }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="exceptionDesc" label="异常说明" min-width="250" show-overflow-tooltip />
					<el-table-column prop="reviewStatus" label="复核状态" width="100" align="center">
						<template #default="{ row }">
							<el-tag :type="row.reviewStatus === '1' ? 'success' : 'warning'" size="small">
								{{ row.reviewStatus === '1' ? '已复核' : '待复核' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="reviewResult" label="复核结果" width="150" show-overflow-tooltip />
					<el-table-column label="操作" width="120" align="center" fixed="right">
						<template #default="{ row }">
							<el-button v-if="row.reviewStatus === '0'" icon="Edit" link type="primary" @click="handleReview(row)"> 复核 </el-button>
						</template>
					</el-table-column>
					<template #empty>
						<el-empty description="暂无数据" :image-size="120" />
					</template>
				</el-table>

				<!-- 分页 -->
				<el-pagination
					v-model:current-page="page.currentPage"
					v-model:page-size="page.pageSize"
					:page-sizes="[10, 20, 50, 100]"
					:total="page.total"
					layout="total, sizes, prev, pager, next, jumper"
					class="pagination"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</el-card>
		</div>

		<!-- 复核弹窗 -->
		<el-dialog v-model="reviewDialogVisible" title="学籍信息复核" width="600px" :close-on-click-modal="false">
			<el-descriptions :column="2" border>
				<el-descriptions-item label="学号">{{ reviewData.stuNo }}</el-descriptions-item>
				<el-descriptions-item label="系统姓名">{{ reviewData.systemRealName }}</el-descriptions-item>
				<el-descriptions-item label="学籍姓名">{{ reviewData.enrollRealName }}</el-descriptions-item>
				<el-descriptions-item label="班级">{{ reviewData.className }}</el-descriptions-item>
				<el-descriptions-item label="系统身份证">{{ reviewData.systemIdCard }}</el-descriptions-item>
				<el-descriptions-item label="学籍身份证">{{ reviewData.enrollIdCard }}</el-descriptions-item>
				<el-descriptions-item label="系统学籍号">{{ reviewData.systemEnrollNo }}</el-descriptions-item>
				<el-descriptions-item label="全国学籍号">{{ reviewData.nationalEnrollNo }}</el-descriptions-item>
				<el-descriptions-item label="异常类型" :span="2">
					<el-tag :type="getExceptionTagType(reviewData.exceptionType)">
						{{ getExceptionTypeName(reviewData.exceptionType) }}
					</el-tag>
				</el-descriptions-item>
				<el-descriptions-item label="异常说明" :span="2">{{ reviewData.exceptionDesc }}</el-descriptions-item>
			</el-descriptions>
			<el-form :model="reviewForm" label-width="80px" class="review-form">
				<el-form-item label="复核结果">
					<el-radio-group v-model="reviewForm.reviewResult">
						<el-radio label="信息无误">信息无误</el-radio>
						<el-radio label="需修改系统">需修改系统</el-radio>
						<el-radio label="需修改学籍">需修改学籍</el-radio>
						<el-radio label="其他问题">其他问题</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="reviewDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitReview" :loading="reviewLoading">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="EnrollCompare">
import { reactive, ref, onMounted, computed } from 'vue';
import { fetchList, importData, exportData, sendToClassMaster, submitReview as submitReviewApi, downloadTemplate } from '/@/api/basic/enrollcompare';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { Search, DocumentChecked, Upload, Download, Bell, Edit } from '@element-plus/icons-vue';

// 定义变量内容
const searchFormRef = ref();
const showSearch = ref(true);
const loading = ref(false);
const importLoading = ref(false);
const reviewLoading = ref(false);
const dataList = ref<any[]>([]);
const reviewDialogVisible = ref(false);
const reviewData = ref<any>({});
const reviewForm = reactive({
	id: '',
	reviewResult: '信息无误',
});

// 统计数据
const statistics = reactive({
	total: 0,
	pending: 0,
	reviewed: 0,
});

// 分页
const page = reactive({
	currentPage: 1,
	pageSize: 20,
	total: 0,
});

// 搜索表单
const searchForm = reactive({
	batchNo: '',
	stuNo: '',
	systemRealName: '',
	exceptionType: '',
	reviewStatus: '',
});

// 表格样式
const tableStyle = {
	cellStyle: { textAlign: 'center' },
	headerCellStyle: {
		textAlign: 'center',
		background: 'var(--el-table-row-hover-bg-color)',
		color: 'var(--el-text-color-primary)',
	},
};

// 获取异常类型名称
const getExceptionTypeName = (type: string) => {
	const map: Record<string, string> = {
		'1': '姓名不一致',
		'2': '身份证不一致',
		'3': '学籍号不一致',
		'4': '毕业院校不一致',
		'5': '系统有学籍无',
		'6': '学籍有系统无',
	};
	return map[type] || type;
};

// 获取异常类型标签颜色
const getExceptionTagType = (type: string) => {
	const map: Record<string, string> = {
		'1': 'danger',
		'2': 'danger',
		'3': 'warning',
		'4': 'info',
		'5': 'warning',
		'6': 'warning',
	};
	return map[type] || 'info';
};

// 查询
const handleSearch = () => {
	page.currentPage = 1;
	getDataList();
};

// 重置
const handleReset = () => {
	searchFormRef.value?.resetFields();
	getDataList();
};

// 分页
const handleSizeChange = (val: number) => {
	page.pageSize = val;
	getDataList();
};

const handleCurrentChange = (val: number) => {
	page.currentPage = val;
	getDataList();
};

// 获取数据列表
const getDataList = async () => {
	loading.value = true;
	try {
		const res = await fetchList({
			current: page.currentPage,
			size: page.pageSize,
			...searchForm,
		});
		if (res.data && res.data.records) {
			dataList.value = res.data.records;
			page.total = res.data.total;

			// 计算统计数据
			statistics.total = res.data.total;
			statistics.pending = dataList.value.filter((item: any) => item.reviewStatus === '0').length;
			statistics.reviewed = dataList.value.filter((item: any) => item.reviewStatus === '1').length;
		} else {
			dataList.value = [];
			page.total = 0;
		}
	} catch (err: any) {
		useMessage().error(err.msg || '获取数据失败');
	} finally {
		loading.value = false;
	}
};

// 上传前验证
const beforeUpload = (file: File) => {
	const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
	if (!isExcel) {
		useMessage().error('只能上传Excel文件');
		return false;
	}
	return true;
};

// 导入比对
const handleImport = async (options: any) => {
	importLoading.value = true;
	try {
		const res = await importData(options.file);
		useMessage().success(res.msg || '导入比对成功');
		// 自动填充批次号
		if (res.data) {
			searchForm.batchNo = '';
		}
		getDataList();
	} catch (err: any) {
		useMessage().error(err.msg || '导入失败');
	} finally {
		importLoading.value = false;
	}
};

// 下载模板
const handleDownloadTemplate = async () => {
	try {
		const res = await downloadTemplate();
		const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
		const url = window.URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;
		link.download = '全国学籍导入模板.xlsx';
		link.click();
		window.URL.revokeObjectURL(url);
	} catch (err: any) {
		useMessage().error(err.msg || '下载失败');
	}
};

// 导出
const handleExport = async () => {
	try {
		const res = await exportData(searchForm);
		const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
		const url = window.URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;
		link.download = '学籍比对异常数据.xlsx';
		link.click();
		window.URL.revokeObjectURL(url);
	} catch (err: any) {
		useMessage().error(err.msg || '导出失败');
	}
};

// 下发班主任
const handleSend = async () => {
	if (!searchForm.batchNo) {
		useMessage().warning('请先选择批次号');
		return;
	}
	try {
		await useMessageBox().confirm('确定要将该批次异常数据下发至班主任复核吗？');
		await sendToClassMaster(searchForm.batchNo);
		useMessage().success('下发成功');
	} catch (err: any) {
		if (err !== 'cancel') {
			useMessage().error(err.msg || '下发失败');
		}
	}
};

// 复核
const handleReview = (row: any) => {
	reviewData.value = row;
	reviewForm.id = row.id;
	reviewForm.reviewResult = '信息无误';
	reviewDialogVisible.value = true;
};

// 提交复核
const submitReview = async () => {
	reviewLoading.value = true;
	try {
		await submitReviewApi(reviewForm.id, reviewForm.reviewResult);
		useMessage().success('复核成功');
		reviewDialogVisible.value = false;
		getDataList();
	} catch (err: any) {
		useMessage().error(err.msg || '复核失败');
	} finally {
		reviewLoading.value = false;
	}
};

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

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

.stat-row {
	margin-bottom: 16px;
}

.upload-btn {
	display: inline-block;
	margin-right: 10px;
}

.text-danger {
	color: var(--el-color-danger);
}

.text-warning {
	color: var(--el-color-warning);
}

.review-form {
	margin-top: 16px;
}
</style>
