<template>
	<div class="list-page">
		<div class="search-box">
			<el-input v-model="searchKeyword" class="search-input" placeholder="搜索实体" :suffix-icon="Search" />
			<div class="filters">
				<el-checkbox v-model="onlyChina" label="只看中国实体" />
			</div>
		</div>
		<div class="main">
			<div class="left">
				<div class="title">
					<div class="box"></div>
					<div class="text">科技领域</div>
				</div>
				<div class="checkbox-group">
					<el-checkbox v-for="(item, index) in techFields" :key="index" v-model="item.checked" :label="item.label"
						@change="handleFilterChange(item, techFields, 'tech')" />
				</div>
				<div class="title">
					<div class="box"></div>
					<div class="text">实体类型</div>
				</div>
				<div class="checkbox-group">
					<el-checkbox v-for="(item, index) in entityTypes" :key="index" v-model="item.checked" :label="item.label"
						@change="handleFilterChange(item, entityTypes, 'type')" />
				</div>
				<div class="title">
					<div class="box"></div>
					<div class="text">制裁时间</div>
				</div>
				<div class="checkbox-group">
					<el-checkbox v-for="(item, index) in sanctionTimes" :key="index" v-model="item.checked" :label="item.label"
						@change="handleFilterChange(item, sanctionTimes, 'time')" />
					<div v-if="sanctionTimes.find(i => i.value === 'custom' && i.checked)" class="custom-date-picker">
						<el-date-picker v-model="customDateRange" type="daterange" range-separator="-" start-placeholder="开始日期"
							end-placeholder="结束日期" />
					</div>
				</div>
			</div>
			<div class="right">
				<div class="title">
					<div class="left-wrapper">
						<div class="box"></div>
						<div class="text">实体清单</div>
					</div>
					<div class="right-wrapper">
						<div class="stats">
							<div class="dot"></div>
							<div class="count-text">共 <span class="highlight">{{ ruleCount.totalCount }}</span> 家</div>
							<div class="rule-text">(50%规则涉及<span class="highlight">{{ ruleCount.ruleCount }}</span>家)</div>
						</div>
						<div class="btn">
							<img src="../../../../assets/下载按钮.png" alt="" />
							<img src="../../../../assets/收藏按钮.png" alt="" />
						</div>
					</div>
				</div>
				<div class="right-table">
					<el-table :data="entityRows" table-layout="fixed" :row-class-name="tableRowClassName"
						:header-cell-style="{ background: '#fff' }">
						<el-table-column label="实体名称" min-width="200">
							<template #default="{ row }">
								<div class="entity-name-cell" @click="handleCompClick(row)">
									<el-image v-if="row.img" class="avatar" :src="row.img" alt=""></el-image>
									<div v-else class="avatar-undefined">
										{{
											(row.entityNameZh || row.entityName)?.match(
												/[\u4e00-\u9fa5a-zA-Z0-9]/
											)?.[0]
										}}
									</div>
									<CommonPrompt :content="row.entityNameZh || row.entityName" style="flex: 1; overflow: hidden" />
								</div>
							</template>
						</el-table-column>
						<el-table-column label="涉及领域" min-width="150">
							<template #default="{ row }">
								<div class="domain-cell">
									<el-tag v-for="tag in row.techDomains" :key="tag" class="domain-tag" effect="plain"
										:disable-transitions="true" :style="getTagStyle(tag)">
										{{ tag }}
									</el-tag>
								</div>
							</template>
						</el-table-column>
						<el-table-column prop="startTime" label="制裁时间" width="140" show-overflow-tooltip align="center" />
						<el-table-column label="50%规则子企业" min-width="280" show-overflow-tooltip align="right">
							<template #default="{ row }">
								<div class="rule-cell" v-if="row.ruleOrgCount > 0">
									<div class="rule-text" :title="row.ruleOrgList?.[0]?.orgName || ''">
										{{ row.ruleOrgList?.[0]?.orgName || '' }}...等
									</div>
									<el-link class="rule-link" type="primary" :underline="false" @click="handleRuleClick(row)">{{
										row.ruleOrgCount }}家 ></el-link>
								</div>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div class="tight-footer">
					<div class="total-text">共 {{ total }} 项</div>
					<el-pagination :current-page="currentPage" v-model:page-size="pageSize" :total="total"
						layout="prev, pager, next" prev-text="<" next-text=">" @current-change="handleCurrentChange" />
				</div>
			</div>
		</div>
	</div>
	<RuleSubsidiaryDialog v-model="ruleDialogVisible" :company-name="currentRuleCompany" :total-count="currentRuleCount"
		:data-list="currentRuleList" />
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { Search } from "@element-plus/icons-vue";
import defaultIcon from "../../../../../assets/icons/default-avatar.png";
import RuleSubsidiaryDialog from "./RuleSubsidiaryDialog.vue";
import { getExportControlList, get50PercentEntityCount } from "@/api/exportControlV2.0.js"
import CommonPrompt from '@/views/exportControl/commonPrompt/index.vue'

const router = useRouter();

// 跳转公司详情页
const handleCompClick = item => {
	console.log("item", item);
	window.sessionStorage.setItem('curTabName', item.entityNameZh || item.entityName)
	const route = router.resolve({
		name: "companyPages",
		params: {
			id: item.entityId
		}
	});
	window.open(route.href, "_blank");
};

const searchKeyword = ref("");
const onlyChina = ref(false);
const sanctionTime = ref("");

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const entityRows = computed(() => mainList.value);

const handleCurrentChange = (val) => {
	if (val === currentPage.value) return;
	currentPage.value = val;
	getExportControlListApi();
};

const getTagStyle = tag => {
	// 预设颜色池
	const colorPool = [
		{ color: "#CD4246", background: "rgba(255, 242, 240, 1)", borderColor: "rgba(255, 163, 158, 1)" }, // 红色
		{ color: "#0E78F1", background: "rgba(230, 244, 255, 1)", borderColor: "rgba(145, 206, 255, 1)" }, // 蓝色
		{ color: "#722ED1", background: "rgba(249, 240, 255, 1)", borderColor: "rgba(211, 173, 247, 1)" }, // 紫色
		{ color: "#13A8A8", background: "rgba(230, 255, 251, 1)", borderColor: "rgba(135, 232, 222, 1)" }, // 青色
		{ color: "#FA8C16", background: "rgba(255, 247, 230, 1)", borderColor: "rgba(255, 213, 145, 1)" }, // 橙色
		{ color: "#52C41A", background: "rgba(246, 255, 237, 1)", borderColor: "rgba(183, 235, 143, 1)" } // 绿色
	];

	// 使用简单的哈希算法将字符串映射到索引
	let hash = 0;
	for (let i = 0; i < tag.length; i++) {
		hash = tag.charCodeAt(i) + ((hash << 5) - hash);
	}

	// 确保索引为正数并取模
	const index = Math.abs(hash) % colorPool.length;

	return colorPool[index];
};

const tableRowClassName = ({ rowIndex }) => {
	return rowIndex % 2 === 0 ? "odd-row" : "";
};

// 左侧筛选数据
const techFields = ref([
	{ label: "全部领域", value: "all", checked: true },
	{ label: "人工智能", value: "1", checked: false },
	{ label: "生物科技", value: "2", checked: false },
	{ label: "新一代信息技术", value: "3", checked: false },
	{ label: "量子科技", value: "4", checked: false },
	{ label: "新能源", value: "5", checked: false },
	{ label: "集成电路", value: "6", checked: false },
	{ label: "海洋", value: "7", checked: false },
	{ label: "先进制造", value: "8", checked: false },
	{ label: "新材料", value: "9", checked: false },
	{ label: "航空航天", value: "10", checked: false },
	{ label: "深海", value: "11", checked: false },
	{ label: "极地", value: "12", checked: false },
	{ label: "太空", value: "13", checked: false },
	{ label: "核", value: "14", checked: false }
]);

const entityTypes = ref([
	{ label: "全部类型", value: "all", checked: true },
	{ label: "科研院校", value: "2", checked: false },
	{ label: "高校", value: "3", checked: false },
	{ label: "企业", value: "4", checked: false }
]);

const sanctionTimes = ref([
	{ label: "全部时间", value: "all", checked: true },
	{ label: "2025年", value: "2025", checked: false },
	{ label: "2024年", value: "2024", checked: false },
	{ label: "2023年", value: "2023", checked: false },
	{ label: "2022年", value: "2022", checked: false },
	{ label: "2021年", value: "2021", checked: false },
	{ label: "自定义", value: "custom", checked: false }
]);

const customDateRange = ref("");

const ruleDialogVisible = ref(false);
const currentRuleCompany = ref("");
const currentRuleCount = ref(0);
const currentRuleList = ref([]);

const handleRuleClick = (row) => {
	currentRuleCompany.value = row.entityNameZh || row.entityName;
	currentRuleCount.value = row.ruleOrgCount;
	currentRuleList.value = row.ruleOrgList || [];
	ruleDialogVisible.value = true;
};

// 筛选逻辑处理
const handleFilterChange = (item, list, type) => {
	// 如果点击的是"全部"
	if (item.value === 'all') {
		if (item.checked) {
			// 选中全部，取消其他所有
			list.forEach(i => {
				if (i.value !== 'all') i.checked = false;
			});
		} else {
			// 取消全部（通常不允许全部取消，至少得选一个，这里如果取消全部，就默认为全部选中）
			item.checked = true;
		}
	} else {
		// 点击的是具体项
		if (item.checked) {
			// 选中具体项，取消"全部"
			const allItem = list.find(i => i.value === 'all');
			if (allItem) allItem.checked = false;

			// 特殊处理制裁时间的自定义和其他年份互斥
			if (type === 'time') {
				if (item.value === 'custom') {
					list.forEach(i => {
						if (i.value !== 'custom' && i.value !== 'all') i.checked = false;
					});
				} else {
					const customItem = list.find(i => i.value === 'custom');
					if (customItem) customItem.checked = false;
				}
			}
		} else {
			// 取消具体项，检查是否还有选中的
			const anyChecked = list.some(i => i.checked);
			if (!anyChecked) {
				const allItem = list.find(i => i.value === 'all');
				if (allItem) allItem.checked = true;
			}
		}
	}

	// 重置页码并查询
	currentPage.value = 1;
	getExportControlListApi();
};

// 获取实体清单列表
const mainList = ref([]);
const isFetching = ref(false);
const ruleCount = ref(0);

let abortController = null;
const getExportControlListApi = async () => {
	// 取消上一轮未完成的请求
	if (abortController) {
		try { abortController.abort(); } catch { }
	}
	abortController = new AbortController();
	isFetching.value = true;
	// 处理科技领域筛选
	let techDomains = [];
	const allTech = techFields.value.find(item => item.value === 'all');
	if (!allTech || !allTech.checked) {
		techDomains = techFields.value
			.filter(item => item.checked && item.value !== 'all')
			.map(item => item.value);
	}

	// 处理实体类型筛选
	let typeIds = [];
	const allType = entityTypes.value.find(item => item.value === 'all');
	if (!allType || !allType.checked) {
		typeIds = entityTypes.value
			.filter(item => item.checked && item.value !== 'all')
			.map(item => Number(item.value));
	}

	// 处理制裁时间筛选
	let years = [];
	let startDate = undefined;
	let endDate = undefined;
	const allTime = sanctionTimes.value.find(item => item.value === 'all');

	if (!allTime || !allTime.checked) {
		years = sanctionTimes.value
			.filter(item => item.checked && item.value !== 'all' && item.value !== 'custom')
			.map(item => Number(item.value));

		const customTime = sanctionTimes.value.find(item => item.value === 'custom');
		if (customTime && customTime.checked && customDateRange.value && customDateRange.value.length === 2) {
			const start = new Date(customDateRange.value[0]);
			const end = new Date(customDateRange.value[1]);
			startDate = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')}`;
			endDate = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')}`;
		}
	}

	const data = {
		typeName: "实体清单",
		isCn: onlyChina.value,
		techDomains: techDomains.length > 0 ? techDomains : undefined,
		entityTypes: typeIds.length > 0 ? typeIds : undefined,
		years: years.length > 0 ? years : undefined,
		startDate,
		endDate,
		keyword: searchKeyword.value || undefined,
		pageNum: currentPage.value,
		pageSize: pageSize.value
	};

	try {
		const res = await getExportControlList(data, { signal: abortController.signal });
		// 50%规则涉及实体数
		const countRes = await get50PercentEntityCount(data);
		if (countRes.code === 200) {
			ruleCount.value = countRes.data;
		}
		if (res.code === 200) {
			mainList.value = res.data.content;
			total.value = res.data.totalElements;
		}
	} catch (error) {
		if (!error || (error.code !== 'ERR_CANCELED' && error.name !== 'CanceledError' && error.name !== 'AbortError')) {
			console.error(error);
		}
	} finally {
		isFetching.value = false;
		abortController = null;
	}
}

watch(onlyChina, () => {
	currentPage.value = 1;
	getExportControlListApi();
});

const searchDebounceTimer = ref(null);
watch(searchKeyword, () => {
	if (searchDebounceTimer.value) {
		clearTimeout(searchDebounceTimer.value);
	}
	searchDebounceTimer.value = setTimeout(() => {
		currentPage.value = 1;
		getExportControlListApi();
	}, 300);
});

onMounted(() => {
	getExportControlListApi();
});

watch(customDateRange, () => {
	if (sanctionTimes.value.find(item => item.value === 'custom' && item.checked)) {
		currentPage.value = 1;
		getExportControlListApi();
	}
});
</script>

<style scoped lang="scss">
* {
	margin: 0;
	padding: 0;
}

.list-page {
	width: 1601px;
	padding-bottom: 50px;
	margin: 0 auto;
	padding-top: 16px;

	.search-box {
		margin-bottom: 16px;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.search-input {
			width: 388px;
			height: 32px;

			:deep(.el-input__wrapper) {
				padding: 0 11px;
			}

			:deep(.el-input__inner) {
				font-size: 16px;
				font-weight: 400;
				font-family: "Microsoft YaHei";
				line-height: 24px;
				color: rgb(95, 101, 108);
			}
		}

		.filters {
			display: flex;
			align-items: center;

			.el-checkbox {
				margin-right: 20px;
				color: rgb(59, 65, 75);
			}

			.time-select {
				width: 160px;
				height: 32px;
			}
		}
	}

	.main {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: flex-start;

		.left {
			padding-bottom: 20px;
			width: 388px;
			height: auto;
			border-radius: 10px;
			box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
			background-color: #fff;

			.checkbox-group {
				display: flex;
				flex-wrap: wrap;
				padding: 0 0 0 24px;

				.el-checkbox {
					width: 50%;
					margin-right: 0;
					margin-bottom: 4px;
					font-size: 16px;
					font-weight: 400;
					font-family: "Microsoft YaHei";
					line-height: 24px;
					color: rgb(95, 101, 108);
				}

				.custom-date-picker {
					width: 100%;
					margin-top: 8px;
					padding-right: 24px;
					box-sizing: border-box;

					:deep(.el-date-editor) {
						width: 100%;
						height: 32px;
						box-shadow: none;
						border: 1px solid #dcdfe6;
						border-radius: 4px;
						padding: 0 10px;

						&:hover {
							border-color: #c0c4cc;
						}

						&.is-active {
							border-color: #409eff;
						}

						.el-range-input {
							font-size: 14px;
							font-family: "Microsoft YaHei";
							color: rgb(95, 101, 108);
						}

						.el-range-separator {
							color: rgb(95, 101, 108);
							line-height: 30px;
						}

						.el-input__icon {
							line-height: 32px;
							color: rgb(95, 101, 108);
						}
					}
				}
			}
		}

		.right {
			width: 1196px;
			height: auto;
			border-radius: 10px;
			box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
			background-color: #fff;

			.title {
				width: 100%;
				height: 56px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 14px 12px 16px 0;
				box-sizing: border-box;

				.left-wrapper {
					display: flex;
					align-items: center;

					.box {
						width: 8px;
						height: 20px;
						background-color: rgb(5, 95, 194);
						border-bottom-right-radius: 4px;
						border-top-right-radius: 4px;
						margin-right: 14px;
					}

					.text {
						font-size: 20px;
						font-weight: 700;
						font-family: "Microsoft YaHei";
						line-height: 26px;
						color: rgb(5, 95, 194);
					}
				}

				.right-wrapper {
					display: flex;
					align-items: center;

					.stats {
						display: flex;
						align-items: center;
						margin-right: 24px;

						.dot {
							width: 8px;
							height: 8px;
							background-color: #cd4246;
							border-radius: 50%;
							margin-right: 8px;
						}

						.count-text {
							font-size: 16px;
							font-weight: 700;
							color: #3b414b;
							font-family: "Microsoft YaHei";
							margin-right: 16px;

							.highlight {
								color: #cd4246;
								margin: 0 4px;
							}
						}

						.rule-text {
							font-size: 14px;
							color: #5f656c;
							font-family: "Microsoft YaHei";

							.highlight {
								color: #cd4246;
							}
						}
					}

					.btn {
						width: 60px;
						height: 28px;

						img {
							width: 28px;
							height: 28px;
							cursor: pointer;
						}

						img:first-child {
							margin-right: 4px;
						}
					}
				}
			}

			.right-table {
				padding: 5px 21px 0 21px;

				:deep(.el-table) {
					--el-table-header-bg-color: #fff;
					--el-table-border-color: transparent;
					--el-table-row-hover-bg-color: rgba(248, 249, 250, 1);
				}

				:deep(.el-table__inner-wrapper::before) {
					background-color: transparent;
				}

				:deep(.el-table__header-wrapper th) {
					height: 60px;
					background-color: #fff;
					font-size: 16px;
					font-weight: 700;
					color: rgba(59, 65, 75, 1);
					font-family: "Microsoft YaHei";
					border-bottom: 1px solid rgba(230, 231, 232, 1);
					border-top: 1px solid rgba(230, 231, 232, 1);
				}

				:deep(.el-table__header-wrapper .cell) {
					line-height: 22px;
				}

				:deep(.el-table__header-wrapper th:first-child .cell) {
					padding-left: 39px;
				}

				:deep(.el-table__row) {
					height: 64px;
				}

				:deep(.el-table__cell) {
					border-bottom: 0;
					font-size: 16px;
					font-weight: 400;
					color: rgb(95, 101, 108);
					font-family: "Microsoft YaHei";
				}

				:deep(.el-table__row .el-table__cell:first-child .cell) {
					padding-left: 39px;
				}

				:deep(.odd-row td.el-table__cell) {
					background-color: rgba(248, 249, 250, 1);
				}

				.entity-name-cell {
					display: flex;
					align-items: center;

					.avatar {
						width: 24px;
						height: 24px;
						margin-right: 8px;
						border-radius: 4px;
					}

					.avatar-undefined {
						width: 24px;
						height: 24px;
						margin-right: 8px;
						border-radius: 4px;
						background-color: #055fc2;
						color: #fff;
						display: flex;
						justify-content: center;
						align-items: center;
						font-size: 14px;
						font-weight: 500;
					}

					.name {
						font-size: 16px;
						font-weight: 700;
						color: rgba(59, 65, 75, 1);
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
				}

				.domain-cell {
					display: flex;
					align-items: center;
					gap: 8px;

					:deep(.el-tag) {
						height: auto;
						padding: 2px 8px;
						border-radius: 4px;
						font-size: 14px;
						font-weight: 400;
						font-family: "Microsoft YaHei";
						line-height: 20px;
						border: 1px solid;
					}
				}

				.rule-cell {
					display: flex;
					align-items: center;
					gap: 12px;

					.rule-text {
						flex: 1;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}

					.rule-link {
						font-size: 16px;
						font-weight: 400;
						color: rgb(5, 95, 194);
						cursor: pointer;
						white-space: nowrap;
					}
				}
			}

			.tight-footer {
				padding: 16px 24px;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.total-text {
					font-size: 14px;
					font-weight: 400;
					color: #5F656C;
					font-family: "Microsoft YaHei";
				}

				:deep(.el-pagination) {
					--el-pagination-button-bg-color: #fff;
					--el-pagination-hover-color: #0E78F1;
					--el-pagination-font-size: 14px;

					.el-pager li {
						border: 1px solid #DCDFE6;
						border-radius: 4px;
						margin: 0 4px;
						font-weight: 400;
						color: #5F656C;
						min-width: 32px;
						height: 32px;
						line-height: 30px;

						&.is-active {
							background-color: #0E78F1;
							color: #fff;
							border-color: #0E78F1;
						}

						&:hover:not(.is-active) {
							color: #0E78F1;
							border-color: #0E78F1;
						}
					}

					.btn-prev,
					.btn-next {
						border: 1px solid #DCDFE6;
						border-radius: 4px;
						padding: 0;
						margin: 0 4px;
						min-width: 32px;
						height: 32px;
						line-height: 30px;
						text-align: center;

						&:hover {
							color: #0E78F1;
							border-color: #0E78F1;
						}

						&[disabled] {
							border-color: #E4E7ED;
							color: #C0C4CC;
						}
					}
				}
			}
		}
	}
}

.title {
	width: 100%;
	height: 56px;
	display: flex;
	align-items: center;
	padding: 14px 12px 16px 0;

	.box {
		width: 8px;
		height: 16px;
		background-color: rgb(5, 95, 194);
		border-bottom-right-radius: 4px;
		border-top-right-radius: 4px;
		margin-right: 14px;
	}

	.text {
		font-size: 16px;
		font-weight: 700;
		font-family: "Microsoft YaHei";
		line-height: 24px;
		color: rgb(5, 95, 194);
	}
}
</style>
