<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>
					<EChart :option="sanctionCountChartOption" autoresize :style="{ height: '300px', padding: '0 20px' }" />

					<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">
								<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="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>
					<EChart :option="domainChartOption" autoresize :style="{ height: '300px', padding: '0 20px' }" />

					<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="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> -->
					<template #header-btn>
						<div class="toggle-btns">
							<div
								class="t-btn"
								:class="{ active: activeDomainTab === 'year' }"
								@click="handleDomainTabChange('year')"
							>
								按年度
							</div>
							<div
								class="t-btn"
								:class="{ active: activeDomainTab === 'sanction' }"
								@click="handleDomainTabChange('sanction')"
							>
								按制裁
							</div>
						</div>
					</template>
					<EChart :option="domainNumChartOption" autoresize :style="{ height: '300px', padding: '0 20px' }" />

					<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="domainNumChart.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' }" />
					<!-- <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 { getDomainNum } from "@/api/finance";
import getMultiLineChart from "@/views/ZMOverView/components/fourSuppress/components/addDomain/multiLineChart";
import EChart from "@/components/Chart/index.vue";
import { useRoute } 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 domainNumChart = useChartInterpretation();
const typeChart = useChartInterpretation();
const rankChart = useChartInterpretation();

const route = useRoute();
// 实体清单-数据统计-制裁实体类型分布情况
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);
		console.log("制裁实体类型分布情况", res.data);
		if (res && res.code === 200) {
			const data = res.data || [];
			typeData.value = data.map(item => ({
				name: item.name,
				value: item.count || item.value
			}));
			updateTypeChart();
			typeChart.interpret({ type: "饼图", name: "制裁实体类型分布情况", data: data });
		}
	} 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 domainNumChartOption = ref({
	color: [],
	tooltip: {
		trigger: "axis",
		backgroundColor: "rgba(255, 255, 255, 0.9)",
		textStyle: {
			color: "#666"
		},
		extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); border-radius: 4px;"
	},
	grid: {
		top: "15%",
		right: "2%",
		bottom: "5%",
		left: "2%",
		containLabel: true
	},
	legend: {
		type: "scroll",
		show: true,
		top: 0,
		left: "center",
		icon: "circle",
		itemWidth: 12,
		itemHeight: 12,
		data: [],
		textStyle: {
			fontFamily: "Microsoft YaHei",
			fontSize: 16,
			fontWeight: 400,
			lineHeight: 24,
			color: "rgb(95, 101, 108)"
		}
	},
	xAxis: [
		{
			type: "category",
			boundaryGap: false,
			data: [],
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			},
			axisLabel: {
				color: "#999",
				fontSize: 12,
				margin: 15
			}
		}
	],
	yAxis: [
		{
			type: "value",
			min: 0,
			// max: 100,
			// interval: 20,
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			},
			axisLabel: {
				color: "#999",
				fontSize: 12
			},
			splitLine: {
				lineStyle: {
					type: "dashed",
					color: "#E0E6F1"
				}
			}
		}
	],
	series: []
});
const activeDomainTab = ref("year");
const handleDomainTabChange = tab => {
	activeDomainTab.value = tab;
	getDomainNumData();
};

// 处理领域趋势数据的方法
const processDomainTrendData = rawData => {
	// 提取所有的月份作为标题
	const titles = rawData.map(item => item.year).reverse();

	// 收集所有不重复的领域名称
	const domainNamesSet = new Set();
	rawData.forEach(item => {
		item.domainCountInfo.forEach(domain => {
			domainNamesSet.add(domain.name);
		});
	});
	const domainNames = Array.from(domainNamesSet);

	// 定义颜色映射
	const colorMap = {
		人工智能: "#E34D59",
		新一代通信网络: "#FF9F1C",
		核: "#FFB3B3",
		生物科技: "#00A79D",
		量子科技: "#7B61FF",
		先进制造: "#363B42",
		新能源: "#2BA471",
		太空: "#3762F0",
		集成电路: "#0052D9",
		新材料: "#FFD900",
		航空航天: "#3762F0",
		海洋: "#76D1FF",
		深海: "#002060",
		其他: "#A6A6A6"
	};

	// 生成数据系列
	const dataSeries = domainNames.map(domainName => {
		const values = rawData
			.map(yearData => {
				const domainItem = yearData.domainCountInfo.find(d => d.name === domainName);
				return domainItem ? domainItem.count : 0;
			})
			.reverse(); // 数据值也需要跟随标题反转顺序

		return {
			name: domainName,
			color: colorMap[domainName] || `#${Math.floor(Math.random() * 16777215).toString(16)}`, // 如果没有预定义颜色，则随机生成
			value: values
		};
	});

	return {
		title: titles,
		data: dataSeries
	};
};
const getDomainNumData = async () => {
	// 参数
	const param = {
		countType: activeDomainTab.value === "year" ? "year" : "record",
		sanTypeId: sanTypeId.value
	};
	try {
		const res = await getDomainNum(param);
		if (res && res.length > 0) {
			const processedData = processDomainTrendData(res);
			domainNumChartOption.value = getMultiLineChart(processedData);
			console.log("获取实体清单-数据统计-processedData:", processedData);
			console.log("获取实体清单-数据统计-domainNumChartOption:", domainNumChartOption.value);
		}
	} 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);
};

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