<template>
	<div class="main main-association">
		<div class="left">
			<!-- ... 左侧代码保持不变 ... -->
			<AnalysisBox title="制裁历程">
				<div class="left-main">
					<div class="date-picker-box">
						<el-date-picker
							v-model="dateRange"
							type="daterange"
							range-separator="--"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							value-format="YYYY-MM-DD"
							style="width: 100%"
							:clearable="false"
							@change="handleDateChange"
						/>
					</div>
					<div class="list-header">
						<el-checkbox v-model="isAllSelected" :indeterminate="indeterminate" @change="handleCheckAllChange">
							全选
						</el-checkbox>
						<div class="count">共{{ sanctionList.length }}次制裁</div>
					</div>
					<div class="list-content" v-loading="loading">
						<div class="list-item" v-for="item in sanctionList" :key="item.id" @click="handleSanctionSelect(item.id)">
							<el-checkbox v-model="item.checked" @change="val => handleCheckOneChange(val, item)" @click.stop>
								<div class="item-label">
									<div class="item-left">{{ item.date }}-{{ "SDN清单更新" }}</div>
									<div class="item-right">{{ item.count }}{{ item.unit }}</div>
								</div>
							</el-checkbox>
						</div>
					</div>
					<el-button type="primary" @click="handleAssociationClick" style="height: 36px">
						多投融资限制举措关联分析
						<el-icon><Right /></el-icon>
					</el-button>
				</div>
			</AnalysisBox>
		</div>
		<div class="right">
			<AnalysisBox title="投融资限制举措关系图">
				<div class="right-main">
					<div class="relation-empty" v-if="selectedSanctionIds.length == 0">
						<el-empty :image="emptyImg" :image-size="200">
							<template #description>
								<div class="empty">请在左侧勾选多次投融资限制制裁后点击“开始分析”查看结果</div>
							</template>
						</el-empty>
					</div>
					<div class="relation-content" v-else>
						<!-- 修改点：绑定转换后的 graphNodes 和 graphLinks -->
						<GraphChart :nodes="graphNodes" :links="graphLinks" />
					</div>
				</div>
			</AnalysisBox>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted, computed } from "vue";
import defaultTitle from "../../../assets/default-icon2.png";
import GraphChart from "@/components/base/GraphChart/index.vue";
import emptyImg from "../assets/empty.png";
import markIcon from "../assets/icon-mark.png";
import { getSanRecord, getRecordRelation } from "@/api/finance";
import { useRoute } from "vue-router";

const route = useRoute();
const colors = {
	// 相似
	similarity: {
		fontColor: "rgba(5, 95, 194)",
		color: "rgb(231, 243, 255)"
	},
	// 继承
	inheritance: {
		fontColor: "rgba(19, 168, 168)",
		color: "rgba(230, 255, 251, 1)"
	},
	// 冲突
	conflict: {
		fontColor: "rgb(206, 79, 81)",
		color: "rgba(5, 95, 194)"
	}
};

// ... 其他原有变量保持不变 ...
const selectedSanctionIds = ref([]);
const isAllSelected = computed({
	get() {
		return sanctionList.value.length > 0 && sanctionList.value.every(item => item.checked);
	},
	set(val) {}
});

const handleCheckAllChange = val => {
	sanctionList.value.forEach(item => {
		item.checked = val;
	});
	updateSelectedIds();
};

const handleCheckOneChange = (val, item) => {
	item.checked = val;
	updateSelectedIds();
};

const updateSelectedIds = () => {
	selectedSanctionIds.value = sanctionList.value.filter(item => item.checked).map(item => item.id);
	if (selectedSanctionIds.value.length === 1) {
		currentSanctionId.value = selectedSanctionIds.value[0];
	}
};

const indeterminate = computed(() => {
	const checkedCount = sanctionList.value.filter(item => item.checked).length;
	return checkedCount > 0 && checkedCount < sanctionList.value.length;
});

const recordRelation = ref({ noRelationVertices: [], relationVoList: [] });

// 【新增】计算属性：处理图表数据
const graphNodes = computed(() => {
	const nodesMap = new Map();

	// 1. 处理无关联节点 (noRelationVertices)
	if (recordRelation.value.noRelationVertices) {
		recordRelation.value.noRelationVertices.forEach(node => {
			if (!nodesMap.has(node.id)) {
				nodesMap.set(node.id, {
					id: node.id,
					name: node.name,
					// 可以根据需要添加 category 或其他样式属性
					itemStyle: {
						color: "#91cc75" // 例如：无关联节点用绿色区分
					}
				});
			}
		});
	}

	// 2. 处理关联节点 (relationVoList 中的 fromVertex 和 toVertex)
	if (recordRelation.value.relationVoList) {
		recordRelation.value.relationVoList.forEach(rel => {
			const from = rel.fromVertex;
			const to = rel.toVertex;

			if (from && !nodesMap.has(from.id)) {
				nodesMap.set(from.id, {
					id: from.id,
					name: from.name,
					itemStyle: {
						color: "#5470c6" // 例如：有关联节点用蓝色
					}
				});
			}

			if (to && !nodesMap.has(to.id)) {
				nodesMap.set(to.id, {
					id: to.id,
					name: to.name,
					itemStyle: {
						color: "#5470c6"
					}
				});
			}
		});
	}

	return Array.from(nodesMap.values());
});

const graphLinks = computed(() => {
	if (!recordRelation.value.relationVoList) return [];

	return recordRelation.value.relationVoList.map(rel => {
		return {
			source: rel.fromVertex.id,
			target: rel.toVertex.id,
			// 将 edgeInfo 挂载到 data 上，以便在 formatter 中访问
			label: {
				formatter: rel.edgeInfo ? rel.edgeInfo.value : ""
			}
		};
	});
});

const handleAssociationClick = () => {
	console.log("handleAssociationClick", selectedSanctionIds.value);
	fetchRecordRelation();
};

const fetchRecordRelation = async () => {
	if (selectedSanctionIds.value.length === 0) {
		return;
	}
	try {
		const res = await getRecordRelation(selectedSanctionIds.value);
		console.log("getRecordRelation", res);
		if (!!res) {
			recordRelation.value = res;
		} else {
			recordRelation.value = { noRelationVertices: [], relationVoList: [] };
		}
	} catch (error) {
		console.error("获取制裁记录关联信息失败:", error);
		recordRelation.value = { noRelationVertices: [], relationVoList: [] };
	}
};

const loading = ref(false);
const currentPage = ref(1);

const fetchSanRecord = async () => {
	loading.value = true;
	const params = {
		startDate: dateRange.value && dateRange.value[0] ? dateRange.value[0] : "",
		endDate: dateRange.value && dateRange.value[1] ? dateRange.value[1] : "",
		sanTypeId: sanTypeId.value || 1
	};
	try {
		const res = await getSanRecord(params);
		if (res && res.length > 0) {
			sanctionList.value = res
				.map(item => ({
					id: item.sanRecordId,
					date: item.sanRecordDate,
					title: item.sanRecordName,
					count: item.cnEntitiesNum,
					unit: "家中国实体"
				}))
				.reverse();

			if (sanctionList.value.length > 0) {
				currentSanctionId.value = sanctionList.value[0].id;
			}
		} else {
			sanctionList.value = [];
		}
	} catch (error) {
		console.error("获取选择制裁数据失败:", error);
		sanctionList.value = [];
	} finally {
		loading.value = false;
	}
};

const handleDateChange = () => {
	fetchSanRecord();
};

const handleSanctionSelect = id => {
	currentSanctionId.value = id;
};

const dateRange = ref(["2025-01-01", "2025-12-31"]);
const sanctionList = ref([]);
const currentSanctionId = ref(5);

const sanTypeId = ref("");
onMounted(() => {
	sanTypeId.value = route.query.sanTypeId || "";
	fetchSanRecord();
});
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
.main {
	width: 100%;
	padding-top: 12px;
	padding-bottom: 50px;
	display: flex;
	justify-content: space-between;

	.left {
		width: 480px;
		height: 828px;

		.left-main {
			margin-top: 11px;
			padding: 0 22px 0 23px;
			display: flex;
			flex-direction: column;
			height: calc(100% - 25px);

			.date-picker-box {
				margin-bottom: 16px;
			}

			.list-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16px;
				font-size: 14px;
				color: #666;

				.count {
					font-size: 16px;
					font-weight: 400;
					font-family: "Microsoft YaHei";
					color: rgb(95, 101, 108);
				}
			}

			.list-content {
				flex: 1;
				overflow-y: auto;
				padding-bottom: 20px;

				&::-webkit-scrollbar {
					width: 6px;
				}

				&::-webkit-scrollbar-thumb {
					background: #ccc;
					border-radius: 3px;
				}

				.list-item {
					border: 1px solid rgb(234, 236, 238);
					border-radius: 4px;
					margin-bottom: 8px;
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 15px 16px;
					cursor: pointer;
					transition: all 0.3s;
					position: relative;
					background: #fff;
					.item-label {
						display: flex;
						justify-content: space-between;
						align-items: center;
						width: 100%;
					}

					.item-left {
						width: 260px;
						font-weight: 700;
						color: rgb(59, 65, 75);
						font-size: 16px;
						font-family: "Microsoft YaHei";
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						margin-right: 10px;
					}

					.item-right {
						color: rgb(132, 136, 142);
						font-size: 16px;
						font-weight: 400;
						font-family: "Microsoft YaHei";
						flex-shrink: 0;
					}

					&:hover {
						border-color: #055fc2;
					}

					&.active {
						border-color: rgb(5, 95, 194);
						background-color: rgba(246, 250, 255, 1);

						.item-left,
						.item-right {
							color: rgb(5, 95, 194);
						}

						&::after {
							content: "";
							position: absolute;
							right: 0;
							top: 10px;
							bottom: 10px;
							width: 4px;
							background-color: rgb(5, 95, 194);
						}
					}
				}
			}
		}
	}

	.right {
		width: 1105px;
		height: 828px;

		.right-main {
			margin-top: 11px;
			height: calc(100% - 10px);
			padding: 0 16px 16px 16px;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			.relation-empty {
				display: flex;
				justify-content: center;
				align-items: center;
				height: 300px;
				width: 300px;
				.empty {
					font-size: 16px;
					font-weight: 400;
					font-family: Source Han Sans CN;
					color: rgb(132, 136, 142);
					line-height: 30px;
				}
			}
			.relation-content {
				width: 100%;
				height: 100%;
			}
		}
	}
}
.main-association {
	justify-content: flex-start !important;
	gap: 16px;
}
</style>
