<template>
	<div class="data-statistics">
		<div class="nav">
			<div class="nav-item">
				<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">
				<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">
				<div class="item-position"></div>
				<div class="content">
					<div class="info">
						<div class="title">{{ currentYear }}年新增</div>
					</div>
					<div class="number">
						<span class="num">{{ totalCount.latestYearCount }}</span>
						<span class="unit">家</span>
					</div>
				</div>
			</div>
			<div class="nav-item">
				<div class="item-position"></div>
				<div class="content">
					<div class="info">
						<div class="title">近期制裁新增</div>
						<!-- <div class="subtitle">{{ totalCount.latestTime }}</div> -->
					</div>
					<div class="number">
						<span class="num">{{ totalCount.latestTimeCount }}</span>
						<span class="unit">家</span>
					</div>
				</div>
			</div>
		</div>
		<div class="main">
			<div class="main-item">
				<!-- <div class="title-com">
					<div class="box"></div>
					<div class="text">制裁实体数量变化情况</div>
					<div class="right-group">
						<div class="toggle-btns">
							<div
								class="t-btn"
								:class="{ active: activeTab === 'year' }"
								@click="handleTabChange('year')"
							>
								按年度
							</div>
							<div
								class="t-btn"
								:class="{ active: activeTab === 'sanction' }"
								@click="handleTabChange('sanction')"
							>
								按制裁
							</div>
						</div>
						<div class="btn">
							<img src="../../assets/数据库按钮.png" alt="" />
							<img src="../../assets/下载按钮.png" alt="" />
							<img src="../../assets/收藏按钮.png" alt="" />
						</div>
					</div>
				</div>
				<div class="echarts" ref="sanctionCountChartRef"></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> -->
				<AnalysisBox title="制裁实体数量变化情况">
					<template #header-btn>
						<div class="toggle-btns">
							<div class="t-btn" :class="{ active: activeTab === 'year' }" @click="handleTabChange('year')">
								按年度
							</div>
							<div class="t-btn" :class="{ active: activeTab === 'sanction' }" @click="handleTabChange('sanction')">
								按制裁
							</div>
						</div>
					</template>
					<!-- <div class="echarts" ref="sanctionCountChartRef"></div> -->
					<EChart
						:option="sanctionCountChartOption"
						autoresize
						:style="{ height: '300px', padding: '0 20px' }"
						@chart-click="handleBarChartClick"
					/>
					<!-- <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> -->
					<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="sanctionCountChart.interpretation" />
					</div>
				</AnalysisBox>
			</div>
			<div class="main-item">
				<AnalysisBox title="制裁实体各省分布情况">
					<template #header-btn>
						<el-select v-model="regionTime" class="time-select" placeholder="请选择" @change="getRegionCountData">
							<el-option v-for="item in timeOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
					<div class="map-wrapper">
						<div class="map-chart" ref="mapChartRef"></div>
						<div class="rank-list">
							<div
								class="rank-item"
								v-for="(item, index) in rankData"
								:key="index"
								@click="handleClickRankChart(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: (item.value / maxRankValue) * 100 + '%',
											background: getBarColor(index)
										}"
									></div>
								</div>
								<div class="rank-value">{{ item.value }}家</div>
							</div>
						</div>
					</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> -->
					<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="rankChart.interpretation" />
					</div>
				</AnalysisBox>
			</div>
			<div class="main-item">
				<AnalysisBox title="制裁实体领域分布情况">
					<template #header-btn>
						<el-select v-model="domainTime" class="time-select" placeholder="请选择" @change="getDomainCountData">
							<el-option v-for="item in timeOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
					<!-- <div class="echarts" ref="domainChartRef"></div> -->
					<EChart
						:option="domainChartOption"
						autoresize
						:style="{ height: '300px', padding: '0 20px' }"
						@chart-click="handlePieChartClick"
					/>
					<!-- <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> -->
					<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" />
					</div>
				</AnalysisBox>
			</div>
			<div class="main-item">
				<AnalysisBox title="制裁实体类型分布情况">
					<template #header-btn>
						<el-select v-model="typeTime" class="time-select" placeholder="请选择" @change="getTypeCountData">
							<el-option v-for="item in timeOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
					<!-- <div class="echarts" ref="typeChartRef"></div> -->
					<EChart
						:option="typeChartOption"
						autoresize
						:style="{ height: '300px', padding: '0 20px' }"
						@chart-click="handlePieChartClick1"
					/>
					<!-- <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> -->
					<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" />
					</div>
				</AnalysisBox>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import * as echarts from "echarts";
import chinaJson from "../../../utils/China.json";
import ai from "./assets/ai.png";
import right from "./assets/right.png";
import {
	getTotalCount,
	getSanctionCountChange,
	getRegionCount,
	getTechDomainCount,
	getEntityTypeCount
} from "@/api/exportControlV2.0";
import EChart from "@/components/Chart/index.vue";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import tipsIcon from "../../../assets/icons/info-icon.png";
import AiButton from "@/components/base/Ai/AiButton/index.vue";
import AiPane from "@/components/base/Ai/AiPane/index.vue";
import { useChartInterpretation } from "@/views/exportControl/utils/common";
const sanctionCountChart = useChartInterpretation();
const domainChart = useChartInterpretation();
const typeChart = useChartInterpretation();
const rankChart = useChartInterpretation();

const route = useRoute();
const router = useRouter();
// 实体清单-数据统计-制裁实体类型分布情况
const typeData = ref([]);
const getTypeCountData = async () => {
	// 参数
	const param = {};
	param.sanTypeId = sanTypeId.value;

	if (typeTime.value !== "all") {
		param.startDate = `${typeTime.value}-01-01`;
		param.endDate = `${typeTime.value}-12-31`;
	}

	try {
		const res = await getEntityTypeCount(param);
		if (res && res.code === 200) {
			const data = res.data || [];
			typeData.value = data.map(item => ({
				name: item.name,
				value: item.count || item.value
			}));
			typeChart.interpret({ type: "饼图", name: "制裁实体类型分布情况", data: data });
			updateTypeChart();
		}
	} catch (error) {
		console.error("获取实体清单-数据统计-制裁实体类型分布情况失败:", error);
	}
};

// 实体清单-数据统计-制裁实体领域分布情况
const domainData = ref([]);
const getDomainCountData = async () => {
	// 参数
	const param = {};
	param.sanTypeId = sanTypeId.value;

	if (domainTime.value !== "all") {
		param.startDate = `${domainTime.value}-01-01`;
		param.endDate = `${domainTime.value}-12-31`;
	}

	try {
		const res = await getTechDomainCount(param);
		if (res && res.code === 200) {
			const data = res.data || [];
			domainData.value = data.map(item => ({
				name: item.name,
				value: item.count || item.value
			}));
			updateDomainChart();
			domainChart.interpret({ type: "饼图", name: "制裁实体领域分布情况", data: data });
		}
	} catch (error) {
		console.error("获取实体清单-数据统计-制裁实体领域分布情况失败:", error);
	}
};

// 实体清单-数据统计-制裁实体地域分布情况
const rankData = ref([]);

const maxRankValue = computed(() => {
	if (!rankData.value || rankData.value.length === 0) return 50;
	return Math.max(...rankData.value.map(item => item.value)) || 50;
});

// 获取实体清单-数据统计-制裁实体地域分布情况
const getRegionCountData = async () => {
	// 参数
	const param = {};
	param.sanTypeId = sanTypeId.value;
	if (regionTime.value !== "all") {
		param.startDate = `${regionTime.value}-01-01`;
		param.endDate = `${regionTime.value}-12-31`;
	}

	try {
		const res = await getRegionCount(param);
		if (res && res.code === 200) {
			const data = res.data || [];
			rankData.value = data.map(item => ({
				name: item.name,
				value: item.count,
				lon: item.lon,
				lat: item.lat
			}));
			// Sort by value descending
			rankData.value.sort((a, b) => b.value - a.value);
			rankChart.interpret({ type: "柱状图", name: "制裁实体各省分布情况", data: data });
			updateMapChart();
		}
	} catch (error) {
		console.error("获取实体清单-数据统计-制裁实体地域分布情况失败:", error);
	}
};

// 实体清单-数据统计-制裁实体数量变化情况
const sanctionCountChange = ref([]);
// 获取实体清单-数据统计-制裁实体数量变化情况
const getSanctionCountChangeData = async () => {
	// 参数
	const param = {
		countType: activeTab.value === "year" ? "year" : "record",
		sanTypeId: sanTypeId.value
	};
	try {
		const res = await getSanctionCountChange(param);
		sanctionCountChange.value = res.data || [];
		updateSanctionCountChart();
		sanctionCountChart.interpret({ type: "饼图", name: "制裁实体数量变化情况", data: res.data });
	} catch (error) {
		console.error("获取实体清单-数据统计-制裁实体数量变化情况失败:", error);
	}
};

// 实体清单-数据统计-总量统计
const totalCount = ref(0);
// 获取实体清单-数据统计-总量统计
const getTotalCountData = async () => {
	try {
		const res = await getTotalCount(sanTypeId.value);
		totalCount.value = res.data || 0;
	} catch (error) {
		console.error("获取实体清单-数据统计-总量统计失败:", error);
	}
};

const activeTab = ref("year");
const handleTabChange = tab => {
	activeTab.value = tab;
	getSanctionCountChangeData();
};

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

const currentYear = new Date().getFullYear();

const timeOptions = [{ label: "全部时间", value: "all" }];

for (let i = 0; i <= 10; i++) {
	const year = currentYear - i;
	timeOptions.push({ label: `${year}年`, value: year.toString() });
}

const sanctionCountChartRef = ref(null);
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 sanctionCountChartOption = ref({
	grid: {
		top: "15%",
		left: "3%",
		right: "4%",
		bottom: "3%",
		containLabel: true
	},
	tooltip: {
		trigger: "axis",
		axisPointer: {
			type: "shadow"
		}
	},
	xAxis: {
		type: "category",
		data: [],
		axisTick: { show: false },
		axisLine: { show: false },
		axisLabel: {
			color: "#909399",
			fontFamily: "Microsoft YaHei",
			interval: 0,
			rotate: 0 // 如果数据较多，旋转标签
		}
	},
	yAxis: {
		type: "value",
		name: "数量",
		nameLocation: "end",
		nameGap: 5,
		nameTextStyle: {
			padding: [0, 40, 10, 0] // [上, 右, 下, 左] —— 减少右侧 padding 相当于左移
		},
		splitLine: {
			lineStyle: {
				type: "dashed",
				color: "#E6EBF5"
			}
		},
		axisLabel: {
			color: "#909399",
			fontFamily: "Microsoft YaHei"
		}
	},
	series: [
		{
			data: [],
			type: "bar",
			barWidth: 16,
			itemStyle: {
				borderRadius: [20, 20, 0, 0],
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{ offset: 0, color: "rgb(5, 95, 194)" },
					{ offset: 1, color: "rgba(5, 95, 194, 0)" }
				])
			}
		}
	]
});

const updateSanctionCountChart = () => {
	// if (!sanctionCountChartRef.value) return;
	// let chart = echarts.getInstanceByDom(sanctionCountChartRef.value);
	// if (!chart) {
	// 	chart = echarts.init(sanctionCountChartRef.value);
	// }
	const data = sanctionCountChange.value || [];

	// 按日期/年份排序 (从小到大)
	data.sort((a, b) => {
		const dateA = a.year || a.name || a.date || "";
		const dateB = b.year || b.name || b.date || "";
		// 简单的字符串或数字比较，如果需要复杂的日期解析可以使用 new Date()
		if (dateA < dateB) return -1;
		if (dateA > dateB) return 1;
		return 0;
	});

	const xData = data.map(item => item.year || item.name || item.date || "");
	const yData = data.map(item => item.count || item.value || item.num || 0);
	sanctionCountChartOption.value.xAxis.data = xData;
	sanctionCountChartOption.value.series[0].data = yData;
	sanctionCountChartOption.value.xAxis.axisLabel.rotate = xData.length > 10 ? 30 : 0; // 如果数据较多，旋转标签
	// const option = {
	// 	grid: {
	// 		top: "15%",
	// 		left: "3%",
	// 		right: "4%",
	// 		bottom: "3%",
	// 		containLabel: true
	// 	},
	// 	tooltip: {
	// 		trigger: "axis",
	// 		axisPointer: {
	// 			type: "shadow"
	// 		}
	// 	},
	// 	xAxis: {
	// 		type: "category",
	// 		data: xData.length ? xData : ["2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025"],
	// 		axisTick: { show: false },
	// 		axisLine: { show: false },
	// 		axisLabel: {
	// 			color: "#909399",
	// 			fontFamily: "Microsoft YaHei",
	// 			interval: 0,
	// 			rotate: xData.length > 10 ? 30 : 0 // 如果数据较多，旋转标签
	// 		}
	// 	},
	// 	yAxis: {
	// 		type: "value",
	// 		splitLine: {
	// 			lineStyle: {
	// 				type: "dashed",
	// 				color: "#E6EBF5"
	// 			}
	// 		},
	// 		axisLabel: {
	// 			color: "#909399",
	// 			fontFamily: "Microsoft YaHei"
	// 		}
	// 	},
	// 	series: [
	// 		{
	// 			data: yData.length ? yData : [200, 250, 300, 400, 500, 600, 610, 650, 750, 850],
	// 			type: "bar",
	// 			barWidth: 16,
	// 			itemStyle: {
	// 				borderRadius: [20, 20, 0, 0],
	// 				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
	// 					{ offset: 0, color: "rgb(5, 95, 194)" },
	// 					{ offset: 1, color: "rgba(5, 95, 194, 0)" }
	// 				])
	// 			}
	// 		}
	// 	]
	// };
	// chart.setOption(option);

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

const initSanctionCountChart = () => {
	updateSanctionCountChart();
};

let mapChartInstance = null;
const updateMapChart = () => {
	if (!mapChartRef.value) return;
	if (!mapChartInstance) {
		mapChartInstance = echarts.init(mapChartRef.value);
		echarts.registerMap("china", chinaJson);
		window.addEventListener("resize", () => {
			mapChartInstance && mapChartInstance.resize();
		});
	}

	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: rankData.value.map(item => ({
					name: item.name,
					value: [item.lon, item.lat, item.value]
				})),
				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]}家`;
					}
				}
			}
		]
	};

	mapChartInstance.setOption(option);
	mapChartInstance.on("click", function (params) {
		const param = {
			selectedProvince: params.name,
			selectedDate:
				regionTime.value === "all" ? null : JSON.stringify([regionTime.value + "-01-01", regionTime.value + "-12-31"])
		};
		const route = router.resolve({
			path: "/dataLibrary/dataEntityList",
			query: param
		});
		window.open(route.href, "_blank");
	});
};

const initMapChart = () => {
	updateMapChart();
};

const domainChartOption = ref({
	tooltip: {
		trigger: "item",
		formatter: params => {
			// 如果是“其他”项，展示详细列表
			if (params.name === "其他" && params.data.extra) {
				let listStr = params.data.extra
					.map(item => {
						const percent = totalValue ? ((item.value / totalValue) * 100).toFixed(2) : 0;
						return `<div style="display:flex;justify-content:space-between;gap:10px;"><span>${item.name}</span><span style="font-weight:bold">${item.value}家 (${percent}%)</span></div>`;
					})
					.join("");
				return `<div style="text-align:left;">
								<div style="font-weight:bold;margin-bottom:5px;">其他 (${params.value}家 ${params.percent}%)</div>
								${listStr}
							</div>`;
			}
			// 默认展示
			return `${params.name}: ${params.value} (${params.percent}%)`;
		}
	},
	color: [
		"#60acfc", // 集成电路 - 蓝色
		"#feb64d", // 人工智能 - 橙色
		"#5bc49f", // 通信网络 - 青色
		"#959cf3", // 量子科技 - 淡蓝紫
		"#ff7c7c", // 先进制造 - 红色
		"#b689ea", // 新材料 - 紫色
		"#32d3eb" // 航空航天 - 浅蓝
	],
	series: [
		{
			name: "制裁实体领域分布",
			type: "pie",
			radius: [73.5, 89.5],
			center: ["50%", "50%"],
			startAngle: 0,
			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: 16,
						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.1
				}
			},
			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 updateDomainChart = () => {
	// if (!domainChartRef.value) return;
	// let chart = echarts.getInstanceByDom(domainChartRef.value);
	// if (!chart) {
	// 	chart = echarts.init(domainChartRef.value);
	// }

	let data = domainData.value.length ? [...domainData.value] : [];

	// 方案一：合并“其他”项
	// 按数值大小降序排序
	data.sort((a, b) => b.value - a.value);

	const TOP_N = 6; // 保留前6项
	let totalValue = 0;
	if (data.length > 0) {
		totalValue = data.reduce((sum, item) => sum + (item.value || 0), 0);
	}

	if (data.length > TOP_N) {
		const topData = data.slice(0, TOP_N);
		const otherData = data.slice(TOP_N);
		const otherValue = otherData.reduce((sum, item) => sum + (item.value || 0), 0);

		if (otherValue > 0) {
			topData.push({
				name: "其他",
				value: otherValue,
				// 将详细数据存入 extra 字段，供 tooltip 使用
				extra: otherData
			});
		}
		data = topData;
	}
	domainChartOption.value.series[0].data = data;

	// const option = {
	// 	tooltip: {
	// 		trigger: "item",
	// 		formatter: params => {
	// 			// 如果是“其他”项，展示详细列表
	// 			if (params.name === "其他" && params.data.extra) {
	// 				let listStr = params.data.extra
	// 					.map(item => {
	// 						const percent = totalValue ? ((item.value / totalValue) * 100).toFixed(2) : 0;
	// 						return `<div style="display:flex;justify-content:space-between;gap:10px;"><span>${item.name}</span><span style="font-weight:bold">${item.value}家 (${percent}%)</span></div>`;
	// 					})
	// 					.join("");
	// 				return `<div style="text-align:left;">
	// 							<div style="font-weight:bold;margin-bottom:5px;">其他 (${params.value}家 ${params.percent}%)</div>
	// 							${listStr}
	// 						</div>`;
	// 			}
	// 			// 默认展示
	// 			return `${params.name}: ${params.value} (${params.percent}%)`;
	// 		}
	// 	},
	// 	color: [
	// 		"#60acfc", // 集成电路 - 蓝色
	// 		"#feb64d", // 人工智能 - 橙色
	// 		"#5bc49f", // 通信网络 - 青色
	// 		"#959cf3", // 量子科技 - 淡蓝紫
	// 		"#ff7c7c", // 先进制造 - 红色
	// 		"#b689ea", // 新材料 - 紫色
	// 		"#32d3eb" // 航空航天 - 浅蓝
	// 	],
	// 	series: [
	// 		{
	// 			name: "制裁实体领域分布",
	// 			type: "pie",
	// 			radius: [73.5, 89.5],
	// 			center: ["50%", "50%"],
	// 			startAngle: 0,
	// 			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.1
	// 				}
	// 			},
	// 			labelLayout: {
	// 				hideOverlap: true
	// 			},
	// 			itemStyle: {
	// 				borderWidth: 0
	// 			}
	// 		}
	// 	]
	// };

	// chart.setOption(option);

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

const initDomainChart = () => {
	updateDomainChart();
};

const typeChartOption = ref({
	tooltip: {
		trigger: "item",
		formatter: params => {
			if (params.name === "其他" && params.data.extra) {
				let listStr = params.data.extra
					.map(item => {
						const percent = totalValue ? ((item.value / totalValue) * 100).toFixed(2) : 0;
						return `<div style="display:flex;justify-content:space-between;gap:10px;"><span>${item.name}</span><span style="font-weight:bold">${item.value}家 (${percent}%)</span></div>`;
					})
					.join("");
				return `<div style="text-align:left;">
								<div style="font-weight:bold;margin-bottom:5px;">其他 (${params.value}家 ${params.percent}%)</div>
								${listStr}
							</div>`;
			}
			return `${params.name}: ${params.value} (${params.percent}%)`;
		}
	},
	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: 16,
						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;
				// points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
				// return {
				// 	labelLinePoints: points
				// };

				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 updateTypeChart = () => {
	// if (!typeChartRef.value) return;
	// let chart = echarts.getInstanceByDom(typeChartRef.value);
	// if (!chart) {
	// 	chart = echarts.init(typeChartRef.value);
	// }

	let data = typeData.value.length
		? [...typeData.value]
		: [
				{ value: 50, name: "企业" },
				{ value: 32, name: "高校" },
				{ value: 32, name: "科研院所" }
			];

	// 2. 聚合逻辑：保留前5项，其余合并为“其他”
	data.sort((a, b) => b.value - a.value);
	const TOP_N = 5;
	let totalValue = 0;
	if (data.length > 0) {
		totalValue = data.reduce((sum, item) => sum + (item.value || 0), 0);
	}

	if (data.length > TOP_N) {
		const topData = data.slice(0, TOP_N);
		const otherData = data.slice(TOP_N);
		const otherValue = otherData.reduce((sum, item) => sum + (item.value || 0), 0);

		// if (otherValue > 0) {
		// 	topData.push({
		// 		name: "其他",
		// 		value: otherValue,
		// 		extra: otherData
		// 	});
		// }
		typeChartOption.value.series[0].data = topData;
	}

	// const option = {
	// 	tooltip: {
	// 		trigger: "item",
	// 		formatter: params => {
	// 			if (params.name === "其他" && params.data.extra) {
	// 				let listStr = params.data.extra
	// 					.map(item => {
	// 						const percent = totalValue ? ((item.value / totalValue) * 100).toFixed(2) : 0;
	// 						return `<div style="display:flex;justify-content:space-between;gap:10px;"><span>${item.name}</span><span style="font-weight:bold">${item.value}家 (${percent}%)</span></div>`;
	// 					})
	// 					.join("");
	// 				return `<div style="text-align:left;">
	// 							<div style="font-weight:bold;margin-bottom:5px;">其他 (${params.value}家 ${params.percent}%)</div>
	// 							${listStr}
	// 						</div>`;
	// 			}
	// 			return `${params.name}: ${params.value} (${params.percent}%)`;
	// 		}
	// 	},
	// 	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 initTypeChart = () => {
	updateTypeChart();
};

const sanTypeId = ref("");

// 点击制裁实体数量变化情况
const handleBarChartClick = val => {
	console.log("value", val);
	const params = {
		selectedDate:
			activeTab.value === "year"
				? JSON.stringify([val.name + "-01-01", val.name + "-12-31"])
				: JSON.stringify([val.name, val.name])
	};
	const route = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: params
	});
	window.open(route.href, "_blank");
};

// 制裁实体各省分布情况
const handleClickRankChart = item => {
	// console.log('item', item);
	const params = {
		selectedProvince: item.name,
		selectedDate:
			regionTime.value === "all" ? null : JSON.stringify([regionTime.value + "-01-01", regionTime.value + "-12-31"])
	};
	const route = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: params
	});
	window.open(route.href, "_blank");
};

// 制裁实体领域分布情况
const handlePieChartClick = val => {
	console.log("val", val);
	const params = {
		domains: val.name,
		selectedDate:
			domainTime.value === "all" ? null : JSON.stringify([domainTime.value + "-01-01", domainTime.value + "-12-31"])
	};
	const route = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: params
	});
	window.open(route.href, "_blank");
};

// 制裁实体类型分布情况
const handlePieChartClick1 = val => {
	console.log("val", val);
	const params = {
		selectedEntityType: val.name,
		selectedDate: typeTime.value === "all" ? null : JSON.stringify([typeTime.value + "-01-01", typeTime.value + "-12-31"])
	};
	const route = router.resolve({
		path: "/dataLibrary/dataEntityList",
		query: params
	});
	window.open(route.href, "_blank");
};

onMounted(() => {
	sanTypeId.value = route.query.sanTypeId || "";
	console.log("数据统计页面接收到的 sanTypeId:", sanTypeId.value);
	// initSanctionCountChart();
	initMapChart();
	initDomainChart();
	initTypeChart();
	// 获取实体清单-数据统计-总量统计
	getTotalCountData();
	// 获取实体清单-数据统计-制裁实体数量变化情况
	getSanctionCountChangeData();
	// 获取实体清单-数据统计-制裁实体地域分布情况
	getRegionCountData();
	// 获取实体清单-数据统计-制裁实体领域分布情况
	getDomainCountData();
	// 获取实体清单-数据统计-制裁实体类型分布情况
	getTypeCountData();
});
</script>

<style scoped lang="scss">
.data-statistics {
	width: 1601px;
	margin: 0 auto;
	padding-top: 16px;
	padding-bottom: 50px;

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

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

			.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;

			.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 {
				padding: 2px 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;

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

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

		&::-webkit-scrollbar-track {
			background: transparent;
		}

		.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;
			}
		}
	}
}

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

	.t-btn {
		padding: 2px 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);
		}
	}
}

.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;
	}
}

.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>
