<template>
	<div class="data-statistics">
		<div class="nav">
			<div class="nav-item" @click="handleToDataLibrary">
				<div class="item-position"></div>
				<div class="content">
					<div class="info">
						<div class="title">中国实体数量</div>
					</div>
					<div class="number">
						<span class="num">{{ totalCount.cnCount }}</span>
						<span class="unit">家</span>
					</div>
				</div>
			</div>
			<div class="nav-item" @click="handleToDataLibrary1">
				<div class="item-position"></div>
				<div class="content">
					<div class="info">
						<div class="title">中国实体数量</div>
						<div class="subtitle">50%规则涉及</div>
					</div>
					<div class="number">
						<span class="num">{{ totalCount.cn50RuleCount }}</span>
						<span class="unit">家</span>
					</div>
				</div>
			</div>
			<div class="nav-item" @click="handleToDataLibrary2">
				<div class="item-position"></div>
				<div class="content">
					<div class="info">
						<div class="title">涉及领域</div>
					</div>
					<div class="number">
						<span class="num">{{ totalCount.techDomainCount }}</span>
						<span class="unit">个</span>
					</div>
				</div>
			</div>
		</div>
		<div class="main">
			<div class="main-item">
				<AnalysisBox title="制裁实体领域分布情况">
					<!-- <div class="echarts" ref="domainChartRef"></div> -->
					<!-- <div class="bottom">
						<div class="ai">
							<div class="left">
								<img :src="ai" alt="" class="icon1" />
								<div class="text">美国对中国的制裁集中在半导体、人工智能等领域。</div>
							</div>
							<div class="right">
								<img :src="right" alt="" class="icon2" />
							</div>
						</div>
					</div> -->
					<EChart
						:option="domainChartOption"
						autoresize
						:style="{ height: '300px', padding: '0 20px' }"
						@chart-click="handleToDataLibrary3"
					/>
					<div class="data-origin-box">
						<div class="data-origin-icon">
							<img :src="tipsIcon" alt="" />
						</div>
						<div class="data-origin-text">数据来源：美国商务部官网</div>
					</div>
					<div class="ai-pane">
						<!-- <AiButton />
						<AiPane :aiContent="domainChart.interpretation" /> -->
						<AiButton @mouseenter="handleShowAiPane('domainChart')" />
						<AiPane
							v-if="aiPaneVisible?.domainChart"
							:aiContent="overviewAiContent.domainChart"
							@mouseleave="handleHideAiPane('domainChart')"
						/>
					</div>
				</AnalysisBox>
			</div>
			<div class="main-item">
				<AnalysisBox title="制裁实体类型分布情况">
					<EChart
						:option="typeChartOption"
						autoresize
						:style="{ height: '300px', padding: '0 20px' }"
						@chart-click="handleToDataLibrary4"
					/>
					<div class="data-origin-box">
						<div class="data-origin-icon">
							<img :src="tipsIcon" alt="" />
						</div>
						<div class="data-origin-text">数据来源：美国商务部官网</div>
					</div>
					<div class="ai-pane">
						<!-- <AiButton />
						<AiPane :aiContent="typeChart.interpretation" /> -->
						<AiButton @mouseenter="handleShowAiPane('typeChart')" />
						<AiPane
							v-if="aiPaneVisible?.typeChart"
							:aiContent="overviewAiContent.typeChart"
							@mouseleave="handleHideAiPane('typeChart')"
						/>
					</div>
				</AnalysisBox>
			</div>
			<div class="main-item">
				<AnalysisBox title="制裁实体国家地区分布情况">
					<div class="country-list">
						<div
							class="list-item"
							v-for="(item, index) in countryDistribution"
							:key="index"
							@click="handleToDataLibrary5(item)"
						>
							<img :src="flag" alt="" class="flag" />
							<div class="country-name">{{ item.name }}</div>
							<div class="progress-bar-container">
								<div
									class="progress-bar"
									:style="{
										width: item.width,
										background: item.gradient
									}"
								></div>
							</div>
							<div class="count" :class="{ highlight: index === 0 }">{{ item.count }}家</div>
						</div>
					</div>
					<div class="data-origin-box">
						<div class="data-origin-icon">
							<img :src="tipsIcon" alt="" />
						</div>
						<div class="data-origin-text">数据来源：美国商务部官网</div>
					</div>
					<div class="ai-pane">
						<!-- <AiButton />
						<AiPane :aiContent="countryDistributionChart.interpretation" /> -->
						<AiButton @mouseenter="handleShowAiPane('countryDistributionChart')" />
						<AiPane
							v-if="aiPaneVisible?.countryDistributionChart"
							:aiContent="overviewAiContent.countryDistributionChart"
							@mouseleave="handleHideAiPane('countryDistributionChart')"
						/>
					</div>
				</AnalysisBox>
			</div>
			<div class="main-item">
				<AnalysisBox title="制裁实体各省分布情况">
					<div class="map-wrapper">
						<div class="map-chart" ref="mapChartRef"></div>
						<div class="rank-list">
							<div
								class="rank-item"
								v-for="(item, index) in regionDistribution"
								:key="index"
								@click="handleToDataLibrary6(item)"
							>
								<div class="rank-index" :class="'rank-' + (index + 1)">{{ index + 1 }}</div>
								<div class="rank-name">{{ item.name }}</div>
								<div class="rank-bar-bg">
									<div
										class="rank-bar-fill"
										:style="{
											width: (maxRegionCount > 0 ? (item.count / maxRegionCount) * 100 : 0) + '%',
											background: getBarColor(index)
										}"
									></div>
								</div>
								<div class="rank-value">{{ item.count }}家</div>
							</div>
						</div>
					</div>
					<div class="data-origin-box">
						<div class="data-origin-icon">
							<img :src="tipsIcon" alt="" />
						</div>
						<div class="data-origin-text">数据来源：美国商务部官网</div>
					</div>
					<div class="ai-pane">
						<!-- <AiButton />
						<AiPane :aiContent="regionDistributionChart.interpretation" /> -->
						<AiButton @mouseenter="handleShowAiPane('regionDistributionChart')" />
						<AiPane
							v-if="aiPaneVisible?.regionDistributionChart"
							:aiContent="overviewAiContent.regionDistributionChart"
							@mouseleave="handleHideAiPane('regionDistributionChart')"
						/>
					</div>
				</AnalysisBox>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";
import chinaJson from "../../../utils/China.json";
import tipsIcon from "../../../assets/icons/info-icon.png";
import ai from "./assets/ai.png";
import right from "./assets/right.png";
import flag from "../../assets/default-icon2.png";
import AiButton from "@/components/base/Ai/AiButton/index.vue";
import AiPane from "@/components/base/Ai/AiPane/index.vue";
import EChart from "@/components/Chart/index.vue";
import { useRouter, useRoute } from "vue-router";
import {
	getSingleSanctionTotalCount,
	getSingleSanctionDomainCount,
	getSingleSanctionEntityTypeCount,
	getSingleSanctionEntityCountryCount,
	getSingleSanctionEntityRegionCount
} from "@/api/exportControlV2.0";
import { getChartAnalysis } from "@/api/aiAnalysis/index";

import { useChartInterpretation } from "@/views/exportControl/utils/common";
const domainChart = useChartInterpretation();
const typeChart = useChartInterpretation();
const countryDistributionChart = useChartInterpretation();
const regionDistributionChart = useChartInterpretation();

const route = useRoute();
// 单次制裁-数据统计-制裁实体地域分布情况
const regionDistribution = ref([]);
const maxRegionCount = ref(0);
// 单次制裁-数据统计-制裁实体地域分布情况-请求
const getRegionData = async () => {
	if (!sanRecordId.value) return;
	try {
		const params = { sanRecordId: sanRecordId.value, sanTypeId: route.query.sanTypeId || "1" };
		if (regionTime.value && regionTime.value !== "all") {
			params.startDate = `${regionTime.value}-01-01`;
			params.endDate = `${regionTime.value}-12-31`;
		}
		const res = await getSingleSanctionEntityRegionCount(params);
		if (res.code === 200) {
			regionDistribution.value = res.data || [];
			maxRegionCount.value = Math.max(...regionDistribution.value.map(item => item.count), 0);
			regionDistributionChartData.value = res.data || [];
			initMapChart();
			// regionDistributionChart.interpret({ type: "柱状图", name: "进入本次实体清单的中国实体各省分布情况", data: res.data });
		}
	} catch (error) {
		console.log(error);
	}
};

// 单次制裁-数据统计-制裁实体国家分布情况
const countryDistribution = ref([]);
// 单次制裁-数据统计-制裁实体国家分布情况-请求
const getCountryCount = async () => {
	if (!sanRecordId.value) return;
	try {
		const params = { sanRecordId: sanRecordId.value, sanTypeId: sanTypeId.value };
		const res = await getSingleSanctionEntityCountryCount(params);
		if (res.code === 200) {
			const rawData = res.data || [];
			// 找出最大值用于计算比例
			const maxCount = Math.max(...rawData.map(item => item.count), 0);

			countryDistribution.value = rawData.map((item, index) => {
				// 计算宽度，最大值对应 80%
				const width = maxCount > 0 ? (item.count / maxCount) * 80 + "%" : "0%";

				// 根据索引分配渐变色
				let gradient = "";
				if (index === 0) {
					gradient = "linear-gradient(90deg, rgba(205, 66, 70, 0) 0%, rgba(205, 66, 70, 1) 100%)";
				} else if (index === 1 || index === 2) {
					gradient = "linear-gradient(90deg, rgba(255, 172, 77, 0) 0%, rgba(255, 172, 77, 1) 100%)";
				} else {
					gradient = "linear-gradient(90deg, rgba(5, 95, 194, 0) 0%, rgba(5, 95, 194, 1) 100%)";
				}

				return {
					...item,
					width,
					gradient
				};
			});
			countryDistributionChartData.value = res.data || [];
			// countryDistributionChart.interpret({
			// 	type: "柱状图",
			// 	name: "进入本次实体清单的实体国家地区分布情况",
			// 	data: res.data
			// });
		}
	} catch (error) {
		console.log(error);
	}
};

// 单次制裁-数据统计-制裁实体类型分布情况
const entityTypeCount = ref([]);
// 单次制裁-数据统计-制裁实体类型分布情况-请求
const getEntityTypeCount = async () => {
	if (!sanRecordId.value) return;
	try {
		const params = { sanRecordId: sanRecordId.value, sanTypeId: sanTypeId.value };
		if (typeTime.value && typeTime.value !== "all") {
			params.startDate = `${typeTime.value}-01-01`;
			params.endDate = `${typeTime.value}-12-31`;
		}
		const res = await getSingleSanctionEntityTypeCount(params);
		if (res.code === 200) {
			entityTypeCount.value = res.data || [];
			// typeChart.interpret({ type: "饼图", name: "进入本次实体清单的中国实体类型分布情况", data: entityTypeCount.value });
			initTypeChart();
		}
	} catch (error) {
		console.log(error);
	}
};

// 单次制裁-数据统计-制裁实体领域分布情况
const domainCount = ref([]);
// 单次制裁-数据统计-制裁实体领域分布情况-请求
const getDomainCount = async () => {
	if (!sanRecordId.value) return;
	try {
		const params = { sanRecordId: sanRecordId.value, sanTypeId: sanTypeId.value };
		if (domainTime.value && domainTime.value !== "all") {
			params.startDate = `${domainTime.value}-01-01`;
			params.endDate = `${domainTime.value}-12-31`;
		}
		const res = await getSingleSanctionDomainCount(params);
		if (res.code === 200) {
			domainCount.value = res.data || [];
			initDomainChart();
			// domainChart.interpret({ type: "饼图", name: "进入本次实体清单的中国实体领域分布情况", data: domainCount.value });
		}
	} catch (error) {
		console.log(error);
	}
};

// 单次制裁-数据统计-总量统计
const totalCount = ref({});
// 单次制裁-数据统计-总量统计-请求
const getTotalCount = async () => {
	if (!sanRecordId.value) return;
	try {
		const res = await getSingleSanctionTotalCount(route.query.sanTypeId, sanRecordId.value);
		console.log("统计", res);

		if (res.code === 200) {
			totalCount.value = res.data || {};
		}
	} catch (error) {
		console.log(error);
	}
};

const router = useRouter();
const sanRecordId = ref("");
const getUrlParams = () => {
	const urlParams = new URLSearchParams(window.location.search);
	sanRecordId.value = urlParams.get("id") || "";
};

const regionTime = ref("all");
const domainTime = ref("all");
const typeTime = ref("all");

watch(domainTime, () => {
	getDomainCount();
});

watch(typeTime, () => {
	getEntityTypeCount();
});
watch(regionTime, () => {
	getRegionData();
});

const timeOptions = [{ label: "全部时间", value: "all" }];
// 生成2000-2025年的选项
for (let i = 2025; i >= 2000; i--) {
	timeOptions.push({ label: `${i}年`, value: `${i}` });
}

const mapChartRef = ref(null);
const domainChartRef = ref(null);
const typeChartRef = ref(null);

const getBarColor = index => {
	if (index === 0) return "linear-gradient(90deg, rgba(255, 77, 79, 0) 0%, rgba(255, 77, 79, 1) 100%)";
	if (index === 1 || index === 2) return "linear-gradient(90deg, rgba(255, 172, 77, 0) 0%, rgba(255, 172, 77, 1) 100%)";
	return "linear-gradient(90deg, rgba(5, 95, 194, 0) 0%, rgba(5, 95, 194, 1) 100%)";
};

const initMapChart = () => {
	if (!mapChartRef.value) return;
	// 销毁旧实例
	const oldChart = echarts.getInstanceByDom(mapChartRef.value);
	if (oldChart) {
		oldChart.dispose();
	}
	const chart = echarts.init(mapChartRef.value);
	echarts.registerMap("china", chinaJson);

	const scatterData = regionDistribution.value.map(item => {
		return {
			name: item.name,
			value: [item.lon, item.lat, item.count]
		};
	});

	const option = {
		tooltip: {
			show: false
		},
		geo: {
			map: "china",
			roam: true,
			center: [105, 36],
			zoom: 1.6,
			top: "10%",
			bottom: "10%",
			label: {
				normal: {
					show: false
				}
			},
			itemStyle: {
				areaColor: "#eff6ff",
				borderColor: "#8cbaff",
				borderWidth: 1
			},
			emphasis: {
				itemStyle: {
					areaColor: "#dbeafe"
				}
			}
		},
		series: [
			{
				type: "scatter",
				coordinateSystem: "geo",
				data: scatterData,
				symbolSize: 8,
				itemStyle: {
					color: "#ff4d4f",
					shadowBlur: 10,
					shadowColor: "rgba(255, 77, 79, 0.5)"
				},
				tooltip: {
					show: true,
					formatter: params => {
						return `${params.name} ${params.value[2]}家`;
					}
				}
			}
		]
	};

	chart.setOption(option);

	chart.on("click", function (params) {
		const param = {
			selectedProvince: params.name,
			selectedDate: JSON.stringify([route.query.date, route.query.date])
		};
		const curRoute = router.resolve({
			path: "/dataLibrary/dataEntityList",
			query: param
		});
		window.open(curRoute.href, "_blank");
	});

	window.addEventListener("resize", () => {
		chart.resize();
	});
};

const domainChartOption = ref({
	tooltip: {
		trigger: "item",
		formatter: "{b}: {c} ({d}%)"
	},
	color: [
		"#60acfc", // 集成电路 - 蓝色
		"#feb64d", // 人工智能 - 橙色
		"#5bc49f", // 通信网络 - 青色
		"#959cf3", // 量子科技 - 淡蓝紫
		"#ff7c7c", // 先进制造 - 红色
		"#b689ea", // 新材料 - 紫色
		"#32d3eb" // 航空航天 - 浅蓝
	],
	series: [
		{
			name: "制裁实体领域分布",
			type: "pie",
			radius: [65, 81],
			center: ["50%", "50%"],
			startAngle: 90,
			data: [],
			label: {
				show: true,
				alignTo: "edge",
				minMargin: 5,
				edgeDistance: 10,
				formatter: params => {
					return "{name|" + params.name + "} \n {value|" + params.value + "家 " + params.percent + "%}";
				},
				rich: {
					name: {
						fontSize: 18,
						fontWeight: 700,
						color: "rgb(59, 65, 75)",
						padding: [10, 0, 10, 0],
						fontFamily: "Microsoft YaHei",
						lineHeight: 22
					},
					value: {
						fontSize: 16,
						fontWeight: 400,
						color: "rgb(95, 101, 108)",
						fontFamily: "Microsoft YaHei",
						lineHeight: 22,
						padding: [10, 0, 10, 0]
					}
				}
			},
			labelLine: {
				show: true,
				length: 15,
				length2: 0,
				maxSurfaceAngle: 80,
				lineStyle: {
					width: 1.1
				}
			},
			// labelLayout: function (params) {
			// 	const isLeft = params.labelRect.x < params.viewWidth / 2;
			// 	const points = params.labelLinePoints;
			// 	// Update the end point.
			// 	points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
			// 	return {
			// 		labelLinePoints: points
			// 	};
			// },
			labelLayout: function (params) {
				// hideOverlap: true
				const points = params.labelLinePoints;
				const isLeft = params.labelRect.x < params.rect.x + params.rect.width / 2;

				// 调整指示线终点到 label 垂直中心
				const labelCenterY = params.labelRect.y + params.labelRect.height / 2;
				points[2][1] = labelCenterY;

				// 调整指示线终点到 label 水平边缘
				points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;

				return {
					labelLinePoints: points
				};
			},
			itemStyle: {
				borderWidth: 0
			}
		}
	]
});
const initDomainChart = () => {
	// if (!domainChartRef.value) return;
	// // 销毁旧实例，防止内存泄漏或状态残留
	// const oldChart = echarts.getInstanceByDom(domainChartRef.value);
	// if (oldChart) {
	// 	oldChart.dispose();
	// }
	// const chart = echarts.init(domainChartRef.value);

	const data = domainCount.value.map(item => ({
		value: item.count,
		name: item.name
	}));
	domainChartOption.value.series[0].data = data;

	// const option = {
	// 	tooltip: {
	// 		trigger: "item",
	// 		formatter: "{b}: {c} ({d}%)"
	// 	},
	// 	color: [
	// 		"#60acfc", // 集成电路 - 蓝色
	// 		"#feb64d", // 人工智能 - 橙色
	// 		"#5bc49f", // 通信网络 - 青色
	// 		"#959cf3", // 量子科技 - 淡蓝紫
	// 		"#ff7c7c", // 先进制造 - 红色
	// 		"#b689ea", // 新材料 - 紫色
	// 		"#32d3eb" // 航空航天 - 浅蓝
	// 	],
	// 	series: [
	// 		{
	// 			name: "制裁实体领域分布",
	// 			type: "pie",
	// 			radius: [65, 81],
	// 			center: ["50%", "50%"],
	// 			startAngle: 90,
	// 			data: data,
	// 			label: {
	// 				show: true,
	// 				alignTo: "edge",
	// 				minMargin: 5,
	// 				edgeDistance: 10,
	// 				formatter: params => {
	// 					return "{name|" + params.name + "} \n {value|" + params.value + "家 " + params.percent + "%}";
	// 				},
	// 				rich: {
	// 					name: {
	// 						fontSize: 18,
	// 						fontWeight: 700,
	// 						color: "rgb(59, 65, 75)",
	// 						padding: [10, 0, 10, 0],
	// 						fontFamily: "Microsoft YaHei",
	// 						lineHeight: 22
	// 					},
	// 					value: {
	// 						fontSize: 16,
	// 						fontWeight: 400,
	// 						color: "rgb(95, 101, 108)",
	// 						fontFamily: "Microsoft YaHei",
	// 						lineHeight: 22,
	// 						padding: [10, 0, 10, 0]
	// 					}
	// 				}
	// 			},
	// 			labelLine: {
	// 				show: true,
	// 				length: 15,
	// 				length2: 0,
	// 				maxSurfaceAngle: 80,
	// 				lineStyle: {
	// 					width: 1.1
	// 				}
	// 			},
	// 			labelLayout: function (params) {
	// 				const isLeft = params.labelRect.x < chart.getWidth() / 2;
	// 				const points = params.labelLinePoints;
	// 				// Update the end point.
	// 				points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
	// 				return {
	// 					labelLinePoints: points
	// 				};
	// 			},
	// 			itemStyle: {
	// 				borderWidth: 0
	// 			}
	// 		}
	// 	]
	// };

	// chart.setOption(option);

	// window.addEventListener("resize", () => {
	// 	chart.resize();
	// });
};

const typeChartOption = ref({
	tooltip: {
		trigger: "item",
		formatter: "{b}: {c} ({d}%)"
	},
	color: [
		"#3B82F6", // 企业 - 蓝色
		"#feb64d", // 高校 - 橙色
		"#ff9f9f" // 科研院所 - 粉红
	],
	series: [
		{
			name: "制裁实体类型分布",
			type: "pie",
			radius: [73.5, 89.5],
			center: ["50%", "50%"],
			startAngle: -90,
			data: [],
			label: {
				show: true,
				alignTo: "edge",
				minMargin: 5,
				edgeDistance: 10,
				formatter: params => {
					return "{name|" + params.name + "}\n{value|" + params.value + "家 " + params.percent + "%}";
				},
				rich: {
					name: {
						fontSize: 18,
						fontWeight: 700,
						color: "rgb(59, 65, 75)",
						padding: [0, 0, 5, 0],
						fontFamily: "Microsoft YaHei",
						lineHeight: 26
					},
					value: {
						fontSize: 16,
						fontWeight: 400,
						color: "rgb(95, 101, 108)",
						fontFamily: "Microsoft YaHei",
						lineHeight: 24,
						padding: [5, 0, 0, 0]
					}
				}
			},
			labelLine: {
				show: true,
				length: 15,
				length2: 0,
				maxSurfaceAngle: 80,
				lineStyle: {
					width: 1
				}
			},
			// labelLayout: function (params) {
			// 	const isLeft = params.labelRect.x < params.viewWidth / 2;
			// 	const points = params.labelLinePoints;
			// 	// Update the end point.
			// 	points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
			// 	return {
			// 		labelLinePoints: points
			// 	};
			// },
			labelLayout: function (params) {
				// hideOverlap: true
				const points = params.labelLinePoints;
				const isLeft = params.labelRect.x < params.rect.x + params.rect.width / 2;

				// 调整指示线终点到 label 垂直中心
				const labelCenterY = params.labelRect.y + params.labelRect.height / 2;
				points[2][1] = labelCenterY;

				// 调整指示线终点到 label 水平边缘
				points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;

				return {
					labelLinePoints: points
				};
			},
			itemStyle: {
				borderWidth: 0
			}
		}
	]
});
const initTypeChart = () => {
	// if (!typeChartRef.value) return;
	// // 销毁旧实例，防止内存泄漏或状态残留
	// const oldChart = echarts.getInstanceByDom(typeChartRef.value);
	// if (oldChart) {
	// 	oldChart.dispose();
	// }
	// const chart = echarts.init(typeChartRef.value);

	const data = entityTypeCount.value.map(item => ({
		value: item.count,
		name: item.name
	}));
	typeChartOption.value.series[0].data = data;

	// const option = {
	// 	tooltip: {
	// 		trigger: "item",
	// 		formatter: "{b}: {c} ({d}%)"
	// 	},
	// 	color: [
	// 		"#3B82F6", // 企业 - 蓝色
	// 		"#feb64d", // 高校 - 橙色
	// 		"#ff9f9f" // 科研院所 - 粉红
	// 	],
	// 	series: [
	// 		{
	// 			name: "制裁实体类型分布",
	// 			type: "pie",
	// 			radius: [73.5, 89.5],
	// 			center: ["50%", "50%"],
	// 			startAngle: -90,
	// 			data: data,
	// 			label: {
	// 				show: true,
	// 				alignTo: "edge",
	// 				minMargin: 5,
	// 				edgeDistance: 10,
	// 				formatter: params => {
	// 					return "{name|" + params.name + "}\n{value|" + params.value + "家 " + params.percent + "%}";
	// 				},
	// 				rich: {
	// 					name: {
	// 						fontSize: 18,
	// 						fontWeight: 700,
	// 						color: "rgb(59, 65, 75)",
	// 						padding: [0, 0, 5, 0],
	// 						fontFamily: "Microsoft YaHei",
	// 						lineHeight: 26
	// 					},
	// 					value: {
	// 						fontSize: 16,
	// 						fontWeight: 400,
	// 						color: "rgb(95, 101, 108)",
	// 						fontFamily: "Microsoft YaHei",
	// 						lineHeight: 24,
	// 						padding: [5, 0, 0, 0]
	// 					}
	// 				}
	// 			},
	// 			labelLine: {
	// 				show: true,
	// 				length: 15,
	// 				length2: 0,
	// 				maxSurfaceAngle: 80,
	// 				lineStyle: {
	// 					width: 1
	// 				}
	// 			},
	// 			labelLayout: function (params) {
	// 				const isLeft = params.labelRect.x < chart.getWidth() / 2;
	// 				const points = params.labelLinePoints;
	// 				// Update the end point.
	// 				points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
	// 				return {
	// 					labelLinePoints: points
	// 				};
	// 			},
	// 			itemStyle: {
	// 				borderWidth: 0
	// 			}
	// 		}
	// 	]
	// };

	// chart.setOption(option);

	// window.addEventListener("resize", () => {
	// 	chart.resize();
	// });
};
const sanTypeId = ref("");

// 制裁实体领域分布情况
const handleToDataLibrary3 = val => {
	// console.log('val', val);
	const params = {
		domains: val.name,
		isCnEntityOnly: true,
		selectedDate: JSON.stringify([route.query.date, route.query.date])
	};
	const curRoute = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: params
	});
	window.open(curRoute.href, "_blank");
};

// 制裁实体类型分布情况
const handleToDataLibrary4 = val => {
	// console.log('val', val);
	const params = {
		selectedEntityType: val.name,
		isCnEntityOnly: true,
		selectedDate: JSON.stringify([route.query.date, route.query.date])
	};
	const curRoute = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: params
	});
	window.open(curRoute.href, "_blank");
};

// 制裁实体国家地区分布情况
const handleToDataLibrary5 = item => {
	const params = {
		selectedCountryId: item.id,
		isCnEntityOnly: true,
		selectedDate: JSON.stringify([route.query.date, route.query.date])
	};
	const curRoute = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: params
	});
	window.open(curRoute.href, "_blank");
};

// 制裁实体各省分布情况
const handleToDataLibrary6 = item => {
	console.log("item", item);
	const params = {
		selectedProvince: item.name,
		isCnEntityOnly: true,
		selectedDate: JSON.stringify([route.query.date, route.query.date])
	};
	const curRoute = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: params
	});
	window.open(curRoute.href, "_blank");
};

// 跳转到数据资源库
const handleToDataLibrary = () => {
	const dateStr = route.query.date ? route.query.date : "";
	const curRoute = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: {
			isCnEntityOnly: true,
			selectedDate: JSON.stringify([dateStr, dateStr])
		}
	});
	window.open(curRoute.href, "_blank");
};

const handleToDataLibrary1 = () => {
	const dateStr = route.query.date ? route.query.date : "";
	const curRoute = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: {
			isCnEntityOnly: true,
			isHalfRule: true,
			selectedDate: JSON.stringify([dateStr, dateStr])
		}
	});
	window.open(curRoute.href, "_blank");
};

const handleToDataLibrary2 = () => {
	const dateStr = route.query.date ? route.query.date : "";
	const curRoute = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: {
			isCnEntityOnly: true,
			selectedDate: JSON.stringify([dateStr, dateStr])
		}
	});
	window.open(curRoute.href, "_blank");
};

const requestAiPaneContent = async key => {
	if (!key || aiPaneLoading.value[key] || aiPaneFetched.value[key]) return;
	aiPaneLoading.value = { ...aiPaneLoading.value, [key]: true };
	overviewAiContent.value = { ...overviewAiContent.value, [key]: "智能总结生成中..." };

	try {
		const payload = buildAiChartPayload(key);
		const res = await getChartAnalysis(
			{ text: JSON.stringify(payload) },
			{
				onChunk: chunk => {
					const current = overviewAiContent.value[key];
					const base = current === "智能总结生成中..." ? "" : current;
					overviewAiContent.value = {
						...overviewAiContent.value,
						[key]: base + chunk
					};
				}
			}
		);
		const list = res?.data;
		const first = Array.isArray(list) ? list[0] : null;
		const interpretation = first?.解读 || first?.["解读"];
		// 流式已渲染过内容，最终用解析出的解读覆盖（保证显示格式统一）
		if (interpretation) {
			overviewAiContent.value = {
				...overviewAiContent.value,
				[key]: interpretation
			};
		}
		aiPaneFetched.value = { ...aiPaneFetched.value, [key]: true };
	} catch (error) {
		console.error("获取图表解读失败", error);
		overviewAiContent.value = { ...overviewAiContent.value, [key]: "智能总结生成失败" };
	} finally {
		aiPaneLoading.value = { ...aiPaneLoading.value, [key]: false };
	}
};

const domainChartData = ref([]);
const typeChartData = ref([]);
const countryDistributionChartData = ref([]);
const regionDistributionChartData = ref([]);

const aiPaneVisible = ref({
	domainChart: false,
	typeChart: false,
	countryDistributionChart: false,
	regionDistributionChart: false
});

const overviewAiContent = ref({
	domainChart: "智能总结生成中...",
	typeChart: "智能总结生成中...",
	countryDistributionChart: "智能总结生成中...",
	regionDistributionChart: "智能总结生成中..."
});

const aiPaneFetched = ref({
	domainChart: false,
	typeChart: false,
	countryDistributionChart: false,
	regionDistributionChart: false
});

const aiPaneLoading = ref({
	domainChart: false,
	typeChart: false,
	countryDistributionChart: false,
	regionDistributionChart: false
});

const chartLoading = ref({
	domainChart: false,
	typeChart: false,
	countryDistributionChart: false,
	regionDistributionChart: false
});

const buildAiChartPayload = key => {
	if (key === "domainChart") {
		return { type: "饼图", name: "进入本次实体清单的中国实体领域分布情况", data: domainCount.value };
	}

	if (key === "typeChart") {
		return { type: "饼图", name: "进入本次实体清单的中国实体类型分布情况", data: entityTypeCount.value };
	}

	if (key === "countryDistributionChart") {
		return {
			type: "柱状图",
			name: "进入本次实体清单的实体国家地区分布情况",
			data: countryDistributionChartData.value
		};
	}

	if (key === "regionDistributionChart") {
		return {
			type: "柱状图",
			name: "进入本次实体清单的中国实体各省分布情况",
			data: regionDistributionChartData.value
		};
	}

	return { type: "", name: "", data: [] };
};

const handleShowAiPane = key => {
	aiPaneVisible.value = {
		...aiPaneVisible.value,
		[key]: true
	};
	requestAiPaneContent(key);
};

const handleHideAiPane = key => {
	aiPaneVisible.value = {
		...aiPaneVisible.value,
		[key]: false
	};
};

onMounted(() => {
	// 获取路由参数id
	sanTypeId.value = route.query.sanTypeId;
	console.log("页面接收到的 sanTypeId:", sanTypeId.value);
	// 获取url参数
	getUrlParams();
	// 单次制裁-数据统计-总量统计-请求
	getTotalCount();
	// 单次制裁-数据统计-制裁实体领域分布情况-请求
	getDomainCount();
	// 单次制裁-数据统计-制裁实体类型分布情况-请求
	getEntityTypeCount();
	// 单次制裁-数据统计-制裁实体国家分布情况-请求
	getCountryCount();
	// 单次制裁-数据统计-制裁实体地域分布情况-请求
	getRegionData();

	initMapChart();
	// initDomainChart(); // 移到 getDomainCount 回调中初始化
	// initTypeChart(); // 移到 getEntityTypeCount 回调中初始化
});
</script>

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

.data-statistics {
	width: 1601px;
	margin: 0 auto;
	padding-top: 16px;
	padding-bottom: 16px;

	.nav {
		width: 100%;
		display: flex;
		justify-content: space-between;
		margin-bottom: 16px;

		.nav-item {
			width: 521px;
			height: 80px;
			border-radius: 10px;
			background-color: #fff;
			box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
			position: relative;
			cursor: pointer;

			&:hover {
				background: var(--color-primary-2);
			}

			.item-position {
				position: absolute;
				top: 14px;
				left: 0;
				width: 8px;
				height: 52px;
				background-color: rgb(5, 95, 194);
				border-top-right-radius: 4px;
				border-bottom-right-radius: 4px;
			}

			.content {
				height: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-left: 30px;
				padding-right: 40px;
				box-sizing: border-box;

				.info {
					display: flex;
					flex-direction: column;
					justify-content: center;

					.title {
						font-size: 20px;
						font-weight: 700;
						color: rgb(59, 65, 75);
						font-family: "Microsoft YaHei";
						line-height: 26px;
					}

					.subtitle {
						font-size: 16px;
						font-weight: 400;
						color: rgb(95, 101, 108);
						font-family: "Microsoft YaHei";
						margin-top: 5px;
						line-height: 24px;
					}
				}

				.number {
					display: flex;
					align-items: baseline;

					.num {
						font-size: 32px;
						font-weight: 700;
						color: #cd4246;
						font-family: "Microsoft YaHei";
						margin-right: 2px;
					}

					.unit {
						font-size: 32px;
						font-weight: 700;
						color: #cd4246;
						font-family: "Microsoft YaHei";
					}
				}
			}
		}
	}

	.main {
		width: 100%;
		height: 828px;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		align-content: space-between;

		.main-item {
			width: 792px;
			height: 406px;
			// background-color: #fff;
			// box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
			// border-radius: 10px;

			.country-list {
				overflow: auto;
				width: 100%;
				height: 280px;
				padding: 0 20px;
				margin-bottom: 20px;
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				justify-content: center;

				.list-item {
					display: flex;
					align-items: center;
					margin-bottom: 16px;
					cursor: pointer;

					&:hover {
						background: var(--color-primary-2);
					}

					&:last-child {
						margin-bottom: 0;
					}

					.flag {
						width: 24px;
						height: 24px;
						border-radius: 50%;
						margin-right: 12px;
						object-fit: cover;
					}

					.country-name {
						width: 80px;
						font-size: 16px;
						font-weight: 400;
						color: rgb(59, 65, 75);
						font-family: "Microsoft YaHei";
						margin-right: 12px;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.progress-bar-container {
						flex: 1;
						height: 8px;
						margin-right: 16px;

						.progress-bar {
							height: 100%;
							border-radius: 4px;
						}
					}

					.count {
						font-size: 16px;
						font-weight: 400;
						color: rgb(59, 65, 75);
						font-family: "Microsoft YaHei";
						min-width: 40px;
						text-align: right;

						&.highlight {
							color: #cd4246;
							font-weight: 700;
							font-size: 20px;
						}
					}
				}
			}

			.echarts {
				width: 100%;
				height: 280px;
				padding: 0 20px 0 20px;
				margin-bottom: 20px;
			}

			.bottom {
				width: 100%;
				height: 40px;
				padding: 0 19px 0 17px;
				box-sizing: border-box;

				.ai {
					width: 100%;
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;
					background-color: rgba(246, 250, 255, 1);
					border-radius: 4px;
					border: 1px solid rgba(231, 243, 255, 1);
					padding: 6px 12px;

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

						.icon1 {
							width: 19px;
							height: 20px;
							margin-right: 13px;
						}

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

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

						.icon2 {
							width: 24px;
							height: 24px;
						}
					}
				}
			}
		}
	}
}

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

	.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-group {
		margin-left: auto;
		display: flex;
		align-items: center;

		.toggle-btns {
			display: flex;
			gap: 8px;
			margin-right: 20px;

			.t-btn {
				height: 28px;
				padding: 1px 8px;
				border: 1px solid transparent;
				border-radius: 4px;
				font-size: 16px;
				font-weight: 400;
				line-height: 24px;
				font-family: "Microsoft YaHei";
				color: rgb(59, 65, 75);
				cursor: pointer;
				box-sizing: border-box;
				border: 1px solid rgb(230, 231, 232);

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

		.btn {
			margin-left: 0;
		}

		.time-select {
			width: 120px;
			height: 28px;
			margin-right: 14px;

			:deep(.el-input__wrapper) {
				height: 28px;
				min-height: 28px;
				padding: 0 8px;
				box-shadow: 0 0 0 1px #dcdfe6 inset;
			}

			:deep(.el-input__inner) {
				height: 28px;
				line-height: 28px;
				font-size: 14px;
			}
		}
	}

	.btn {
		width: 92px;
		height: 28px;
		margin-left: auto;

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

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

.map-wrapper {
	width: 100%;
	height: 280px;
	display: flex;
	padding: 0 20px 0 20px;
	margin-bottom: 20px;
	box-sizing: border-box;

	.map-chart {
		flex: 1;
		height: 100%;
	}

	.rank-list {
		flex: 1;
		height: 100%;
		overflow-y: auto;
		padding-left: 20px;
		box-sizing: border-box;

		.rank-item {
			height: 36px;
			display: flex;
			align-items: center;
			margin-bottom: 4px;
			font-size: 14px;
			color: #333;
			cursor: pointer;

			&:hover {
				background-color: rgba(0, 0, 0, 0.02);
			}

			.rank-index {
				width: 24px;
				height: 24px;
				line-height: 24px;
				text-align: center;
				border-radius: 50%;
				background-color: #e6f4ff;
				color: #1677ff;
				margin-right: 16px;
				font-size: 12px;
				flex-shrink: 0;

				&.rank-1,
				&.rank-2,
				&.rank-3 {
					background-color: #e6f4ff;
					color: #1677ff;
				}
			}

			.rank-name {
				width: 70px;
				margin-right: 10px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				flex-shrink: 0;
				font-size: 16px;
				font-weight: 400;
				font-family: "Microsoft YaHei";
				line-height: 24px;
				color: rgb(59, 65, 75);
			}

			.rank-bar-bg {
				flex: 1;
				height: 6px;
				background-color: transparent;
				border-radius: 3px;
				margin-right: 10px;
				position: relative;

				.rank-bar-fill {
					height: 100%;
					border-radius: 3px;
				}
			}

			.rank-value {
				min-width: 40px;
				text-align: right;
				color: #666;
				flex-shrink: 0;
			}
		}
	}
}

.data-origin-box {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: flex-start;
	padding: 22px;

	.data-origin-icon {
		width: 16px;
		height: 16px;
		font-size: 0px;
		margin-right: 8px;

		img {
			width: 100%;
			height: 100%;
		}
	}

	.data-origin-text {
		font-family: Source Han Sans CN;
		font-size: 14px;
		color: var(--text-primary-50-color);
	}
}

.ai-pane {
	position: absolute;
	right: 0px;
	bottom: 15px;
	z-index: 2;

	:deep(.ai-pane-wrapper) {
		display: none;
	}

	:deep(.ai-button-wrapper) {
		display: flex;
	}

	&:hover {
		width: 100%;
		bottom: 0px;

		:deep(.ai-pane-wrapper) {
			display: block;
		}

		:deep(.ai-button-wrapper) {
			display: none;
		}
	}
}
</style>
