<template>
	<div class="datasub">
		<div class="datasub-left">
			<div class="left">
				<div class="left-title">
					<img src="./assets/icon01.png" alt="" />
					<div class="tit">资助领域分布情况</div>
					<div :class="radio1 === true ? 'btn-select' : 'btn'" style="		right:250px;" @click="changeradio1()">
						资助经费
					</div>
					<div :class="radio1 === false ? 'btn-select' : 'btn'" style="		right: 150px;" @click="changeradio1()">
						资助项目
					</div>

					<el-select v-model="value1" placeholder="Select" class="select" style="		right: 31px;">
						<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</div>
				<div class="left-main">

					<div class="left-main-echarts" ref="leftChartRef" v-show="radio1 === true">资助经费</div>
					<div class="left-main-echarts" ref="leftChartRef1" v-show="radio1 === false">资助项目</div>

				</div>
			</div>
			<div class="left">
				<div class="left-title">
					<img src="./assets/icon03.png" alt="" />
					<div class="tit">机构资助领域情况</div>
					<el-select v-model="value2" placeholder="Select" class="select" @change="handleGetOrgFundsArea">
						<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</div>
				<div class="left-main1">
					<div class="left-sankey-echarts" ref="leftSankeyRef"></div>
				</div>
			</div>
		</div>
		<div class="datasub-right">
			<div class="right">
				<div class="right-title">
					<img src="./assets/icon02.png" alt="" />
					<div class="tit">资助经费变化情况</div>
					<el-select v-model="value" placeholder="Select" class="select">
						<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</div>
				<div class="right-main">
					<div class="right-main-echarts" ref="rightChartRef"></div>
					<div class="right-main-tit">亿美元</div>
				</div>
			</div>
			<div class="right">
				<div class="right-title">
					<img src="./assets/icon03.png" alt="" />
					<div class="tit">项目资助强度分布</div>
					<el-select v-model="value3" placeholder="Select" class="select">
						<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</div>
				<div class="right-main1">
					<div class="right-boxplot-echarts" ref="boxplotChartRef"></div>
					<div class="right-main1-tit">单位：亿美元</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import {
	findFundField, findCountryProjectAreaList, getCountryFundingChange, getCountryFundProjectChange, getOrgFundsArea, getOrgFundStrength
} from "@/api/scientificFunding/overview";

import * as echarts from "echarts";



const value = ref(10);




const options = [
	{
		value: 10,
		label: "近十年"
	},
	{
		value: 5,
		label: "近五年"
	}
];
const options1 = [
	{
		value: "2025",
		label: "2025年"
	},
	{
		value: "2024",
		label: "2024年"
	}
];
//获取当前时间x年前的日期
function getDateYearsAgo(years) {
	// 获取当前日期
	const currentDate = new Date();
	// 计算指定年数之前的日期
	const pastDate = new Date(currentDate.getFullYear() - years, currentDate.getMonth(), currentDate.getDate());
	// 格式化日期为 "YYYY-MM-DD" 的形式
	const year = pastDate.getFullYear();
	const month = String(pastDate.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
	const day = String(pastDate.getDate()).padStart(2, "0");
	return `${year}-${month}-${day}`;
}
const radio1 = ref(true)
const changeradio1 = () => {
	radio1.value = !radio1.value
}
const value1 = ref(2025);
const leftChartRef = ref(null);
const leftChartRef1 = ref(null);
// 资助体系v2.0:资助领域分布情况:资助经费
const handleGetFundField = async () => {
	try {
		let params = {
			year: value1.value
		}
		const res = await findFundField(params);
		console.log("资助领域分布情况", res);
		if (res.code === 200 && res.data) {
			initLeftDonut(res.data, true)
		}
	} catch (error) {
		console.error("获取资助领域分布情况error", error);
	}
};

//资助体系v2.0:资助领域分布情况:资助项目
const handleFindCountryProjectAreaList = async () => {
	try {
		let params = {
			year: value1.value
		}
		const res = await findCountryProjectAreaList(params);
		console.log("资助领域分布情况", res);
		if (res.code === 200 && res.data) {
			initLeftDonut(res.data, false)
		}
	} catch (error) {
		console.error("获取资助领域分布情况error", error);
	}
};
// 资助领域分布情况
const initLeftDonut = (rawData, show) => {

	const color = [
		'rgba(206, 79, 81, 1)',
		'rgba(145, 202, 255, 1)',
		'rgba(255, 169, 64, 1)',
		'rgba(146, 84, 222, 1)',
		'rgba(92, 219, 211, 1)',
		'rgba(5, 95, 194, 1)'
	];

	const option = {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			}
		},

		xAxis: {
			type: 'value',
			boundaryGap: [0, 0.01],
			axisLabel: {
				show: false // 不展示X轴文字
			}
		},
		yAxis: {
			type: 'category',
			data: rawData.map(item => item.countryName)
		},
		series: rawData.flatMap(country => {
			return country.fundAreaList.map((area, index) => ({
				name: area.areaName,
				type: 'bar',
				stack: country.countryName,
				itemStyle: {
					color: color[index % color.length]
				},
				data: country.fundAreaList.map(a => a.amount)
			}));
		}).map((seriesItem, index) => ({
			...seriesItem,
			data: seriesItem.data.map((amount, i) => ({
				value: amount,
				name: rawData[i].countryName
			}))
		}))
	};
	if (show == true) {

		leftChart = echarts.init(leftChartRef.value);
		leftChart.setOption(option);
	} else {

		leftChart1 = echarts.init(leftChartRef1.value);
		leftChart1.setOption(option);
	}

};
const rightChartRef = ref(null);
// 资助体系v2.0:资助经费变化情况:资助经费 
const handlegetCountryFundingChange = async () => {
	try {
		let params = {
			startDate: getDateYearsAgo(value.value)
		}
		const res = await getCountryFundingChange(params);
		console.log("资助经费变化情况", res);
		if (res.code === 200 && res.data) {
			initRightLine(res.data, true)
		}
	} catch (error) {
		console.error("获取资助经费变化情况error", error);
	}
};
//资助体系v2.0:资助经费变化情况:资助项目
// getCountryFundProjectChange
const fundProjectChange = ref([])
const handlegetCountryFundProjectChange = async () => {
	try {
		let params = {
			startDate: getDateYearsAgo(value.value)
		}
		const res = await getCountryFundProjectChange(params);
		console.log("资助项目变化情况", res);
		if (res.code === 200 && res.data) {
			initRightLine(res.data)
		}
	} catch (error) {
		console.error("获取资助项目变化情况error", error);
	}
};

//项目资助强度分布
const value3 = ref(2025);
const boxplotChartRef = ref(null);
const handlegetOrgFundStrength = async () => {
	try {
		let params = {
			year: value3.value
		}
		const res = await getOrgFundStrength(params);
		console.log("项目资助强度分布", res);
		if (res.code === 200 && res.data) {
			initBoxPlot(res.data)
		}
	} catch (error) {
		console.error("获取项目资助强度分布error", error);
	}
};
//项目资助强度分布
const initBoxPlot = (data) => {
	if (!boxplotChartRef.value) {
		console.warn("boxplotChartRef is null");
		return;
	}
	if (boxplotChart) boxplotChart.dispose();
	boxplotChart = echarts.init(boxplotChartRef.value);

	// 提取所有行业名称
	const categories = data.map(item => item.industryName);

	// 初始化数据数组
	const dataUS = [];
	const dataCN = [];

	// 遍历数据，填充每个行业的数据
	data.forEach(item => {
		const { industryName, orgDonationSourceVOList } = item;
		const usData = orgDonationSourceVOList.find(org => org.orgName === "美国")?.amount || 0;
		const cnData = orgDonationSourceVOList.find(org => org.orgName === "中国")?.amount || 0;

		// 生成箱线图所需的五数概括（最小值、Q1、中位数、Q3、最大值）
		dataUS.push([usData, usData, usData, usData, usData]); // 示例数据，实际应根据数据计算
		dataCN.push([cnData, cnData, cnData, cnData, cnData]); // 示例数据，实际应根据数据计算
	});

	// 构建 ECharts 配置
	const option = {
		legend: {
			data: ["美国", "中国"],
			left: 20,
			top: 0,
			itemWidth: 12,
			itemHeight: 12,
			icon: 'circle',
			textStyle: {
				color: "#5F656C",
				fontSize: 14
			}
		},
		tooltip: {
			trigger: "item",
			axisPointer: {
				type: "shadow"
			}
		},
		grid: {
			left: 50,
			right: 20,
			top: 60,
			bottom: 40
		},
		xAxis: {
			type: "category",
			data: categories,
			boundaryGap: true,
			nameGap: 30,
			splitArea: {
				show: false
			},
			axisLine: {
				show: true,
				lineStyle: {
					color: "#E6E6E6"
				}
			},
			axisTick: {
				show: false
			},
			axisLabel: {
				color: "#5F656C",
				fontSize: 14,
				margin: 15
			},
			splitLine: {
				show: false
			}
		},
		yAxis: {
			type: "value",
			splitLine: {
				show: true,
				lineStyle: {
					color: "#F0F2F5",
					type: "solid"
				}
			},
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			},
			axisLabel: {
				color: "#5F656C",
				fontSize: 14
			}
		},
		series: [
			{
				name: "美国",
				type: "boxplot",
				data: dataUS,
				boxWidth: 30,
				itemStyle: {
					color: "#fff",
					borderColor: "#1890FF",
					borderWidth: 1
				},
				emphasis: {
					itemStyle: {
						borderWidth: 2,
						shadowBlur: 5,
						shadowOffsetX: 1,
						shadowColor: "rgba(0,0,0,0.2)"
					}
				}
			},
			{
				name: "中国",
				type: "boxplot",
				data: dataCN,
				boxWidth: 30,
				itemStyle: {
					color: "#fff",
					borderColor: "#D15054",
					borderWidth: 1
				},
				emphasis: {
					itemStyle: {
						borderWidth: 2,
						shadowBlur: 5,
						shadowOffsetX: 1,
						shadowColor: "rgba(0,0,0,0.2)"
					}
				}
			}
		]
	};

	boxplotChart.setOption(option);
};



let leftChart;
let leftChart1;
let rightChart;
let leftSankey;
let boxplotChart;



//资助经费变化情况
const initRightLine = (data) => {
	if (!rightChartRef.value) return;
	if (rightChart) rightChart.dispose();
	rightChart = echarts.init(rightChartRef.value);
	const colorMap = [
		"rgba(20, 89, 187, 1)",
		"rgba(206, 79, 81, 1)",
		"rgba(255, 172, 77, 1)",
		"rgba(19, 168, 168, 1)",
		"rgba(114, 46, 209, 1)"
	];
	// 提取所有年份
	const years = data.map(item => item.year);

	// 提取所有组织名称
	const orgNames = data.flatMap(item => item.fundsOrgList.map(org => org.orgName));
	const uniqueOrgNames = [...new Set(orgNames)];

	// 构建 series 数据
	const series = uniqueOrgNames.map((orgName, index) => {
		const values = years.map(year => {
			const yearData = data.find(d => d.year === year);
			if (yearData) {
				const orgData = yearData.fundsOrgList.find(o => o.orgName === orgName);
				return orgData ? orgData.amount : 0;
			}
			return 0;
		});

		// 提取颜色并设置透明度为 0.2
		const color = colorMap[index % colorMap.length];
		const areaColor = color.replace("1)", "0.2)");

		return {
			name: orgName,
			type: "line",
			data: values,
			symbol: "none",
			showSymbol: false,
			endLabel: {
				show: true,
				formatter: orgName, // 只显示 orgName
				rich: {
					[orgName]: {
						fontSize: 14,
						fontFamily: "Microsoft YaHei",
						fontWeight: 400,
						lineHeight: 22,
						color: color
					}
				}
			},
			areaStyle: { color: areaColor }
		};

	});

	// 构建 ECharts 配置
	const option = {
		color: colorMap,
		grid: { left: 40, right: 80, top: 20, bottom: 40 },
		tooltip: { trigger: "axis" },
		legend: { show: false },
		xAxis: {
			type: "category",
			data: years,
			boundaryGap: false,
			axisLine: { show: false },
			axisTick: { show: false },
			axisLabel: {
				color: "rgba(132, 136, 142, 1)",
				fontSize: 14,
				fontFamily: "Microsoft YaHei",
				fontWeight: 400,
				lineHeight: 22
			}
		},
		yAxis: {
			type: "value",
			min: 0,
			max: 100,
			splitLine: { show: true, lineStyle: { color: "#e6e6e6", type: "dashed" } },
			axisLine: { show: false },
			axisTick: { show: false },
			axisLabel: {
				color: "rgba(132, 136, 142, 1)",
				fontSize: 14,
				fontFamily: "Microsoft YaHei",
				fontWeight: 400,
				lineHeight: 22
			}
		},
		series: series
	};
	rightChart.setOption(option);
};

const leftSankeyRef = ref(null);
const value2 = ref(2025);
// 机构资助领域情况
const handleGetOrgFundsArea = async () => {
	try {
		let params = {
			year: value2.value
		}
		const res = await getOrgFundsArea(params);
		console.log("机构资助领域情况", res);
		if (res.code === 200 && res.data) {
			initLeftSankey(res.data)
		}
	} catch (error) {
		console.error("获取机构资助领域情况error", error);
	}
};
//机构资助领域情况
const initLeftSankey = (data) => {
	if (!leftSankeyRef.value) return;
	if (leftSankey) leftSankey.dispose();
	leftSankey = echarts.init(leftSankeyRef.value);

	// 提取所有组织名称和行业名称
	const orgNames = new Set();
	const industryNames = new Set();
	const links = [];

	data.forEach(item => {
		const { industryName, usadonationSourceVOList, chinaDonationSourceVOList } = item;
		industryNames.add(industryName);

		// 处理美国捐赠数据
		usadonationSourceVOList.forEach(org => {
			orgNames.add(org.orgName);
			links.push({
				source: org.orgName,
				target: industryName,
				value: org.amount
			});
		});

		// 处理中国捐赠数据
		chinaDonationSourceVOList.forEach(org => {
			orgNames.add(org.orgName);
			links.push({
				source: org.orgName,
				target: industryName,
				value: org.amount
			});
		});
	});

	// 构建节点数组
	const nodes = [
		...Array.from(orgNames).map(name => ({ name })),
		...Array.from(industryNames).map(name => ({ name }))
	];

	// 定义颜色映射
	const colorMap = {
		"国家地理空间情报局": "#722ED1",
		"国际商业机器公司": "#0A57A6",
		"成都海威华芯科技有限公司": "#2266FF",
		"新一代通信技术": "#B05FA0",
		"人工智能": "#5070DD"
	};

	// 构建 ECharts 配置
	const option = {
		tooltip: { trigger: "item" },
		series: [{
			type: "sankey",
			data: nodes.map(node => ({
				name: node.name,
				itemStyle: { color: colorMap[node.name] || "#bbb" }
			})),
			links: links,
			sort: 'none',
			layoutIterations: 0,
			draggable: false,
			nodeAlign: "justify",
			orient: "horizontal",
			left: 10,
			right: 70,
			top: 0,
			bottom: 0,
			nodeWidth: 40,
			nodeGap: 10,
			lineStyle: { color: "#E7E7E8", opacity: 0.8, curveness: 0.5 },
			emphasis: { focus: "adjacency" },
			label: {
				show: true,
				color: "rgb(59, 65, 75)",
				fontSize: 14,
				fontFamily: "Microsoft YaHei",
				fontWeight: 400,
				lineHeight: 16,
				formatter: (params) => {
					return params.name;
				},
				position: 'right'
			}
		}]
	};

	leftSankey.setOption(option);
};


// const handleResize = () => {
// 	if (leftChart) leftChart.resize();
// 	if (leftChart1) leftChart1.resize();
// 	if (rightChart) rightChart.resize();
// 	if (leftSankey) leftSankey.resize();
// 	if (boxplotChart) boxplotChart.resize();
// };

onMounted(() => {
	handleGetFundField()
	handleFindCountryProjectAreaList()
	handlegetCountryFundingChange()
	handlegetCountryFundProjectChange()
	handleGetOrgFundsArea()
	handlegetOrgFundStrength()

});
// onBeforeUnmount(() => {
// 	window.removeEventListener("resize", handleResize);
// 	if (leftChart) {
// 		leftChart.dispose();
// 		leftChart = null;
// 	}
// 	if (leftChart1) {
// 		leftChart1.dispose();
// 		leftChart1 = null;
// 	}
// 	if (rightChart) {
// 		rightChart.dispose();
// 		rightChart = null;
// 	}
// 	if (leftSankey) {
// 		leftSankey.dispose();
// 		leftSankey = null;
// 	}
// 	if (boxplotChart) {
// 		boxplotChart.dispose();
// 		boxplotChart = null;
// 	}
// });
</script>

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

.datasub {
	width: 1600px;
	height: 936px;
	display: flex;
	justify-content: space-between;

	.datasub-left {
		width: 792px;
		height: 936px;

		.left {
			width: 792px;
			height: 460px;
			margin-right: 16px;
			margin-bottom: 16px;
			border-radius: 10px;
			box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
			background-color: #fff;

			.left-title {
				width: 792px;
				height: 48px;
				border-bottom: 1px solid rgb(234, 236, 238);
				position: relative;

				img {
					width: 19px;
					height: 19px;
					position: absolute;
					top: 16px;
					left: 21px;
				}

				.tit {
					margin-left: 60px;
					height: 48px;
					padding: 11px 0;
					font-size: 20px;
					font-weight: 700;
					font-family: "Microsoft YaHei";
					line-height: 26px;
					color: rgb(5, 95, 194);
				}

				.select {
					width: 120px;
					height: 28px;
					padding: 0px 12px;
					position: absolute;
					top: 11px;
					right: 31px;
				}
			}

			.left-main {
				width: 792px;
				height: 412px;
				padding: 52px 60px 78px 61px;

				.left-main-echarts {
					width: 100%;
					/* 确保宽度占满容器 */
					height: 400px;
					/* 设置一个合适的高度 */
				}
			}

			.left-main1 {
				width: 792px;
				height: 412px;
				padding: 30px 30px 30px 30px;

				.left-sankey-echarts {
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	.datasub-right {
		width: 792px;
		height: 936px;

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

			.right-title {
				width: 792px;
				height: 48px;
				border-bottom: 1px solid rgb(234, 236, 238);
				position: relative;

				img {
					width: 19px;
					height: 19px;
					position: absolute;
					top: 16px;
					left: 21px;
				}

				.tit {
					margin-left: 60px;
					height: 48px;
					padding: 11px 0;
					font-size: 20px;
					font-weight: 700;
					font-family: "Microsoft YaHei";
					line-height: 26px;
					color: rgb(5, 95, 194);
				}

				.select1 {
					width: 155px;
					height: 28px;
					padding: 0px 12px;
					position: absolute;
					top: 11px;
					right: 163px;
				}

				.select {
					width: 120px;
					height: 28px;
					padding: 0px 12px;
					position: absolute;
					top: 11px;
					right: 31px;
				}
			}

			.right-main {
				width: 792px;
				height: 421px;
				padding: 40px 5px 30px 22px;
				position: relative;

				.right-main-echarts {
					width: 100%;
					height: 100%;
				}

				.right-main-tit {
					position: absolute;
					top: 18px;
					right: 83px;
					font-size: 14px;
					font-weight: 400;
					font-family: "Microsoft YaHei";
					line-height: 22px;
					color: rgb(132, 136, 142);
				}
			}

			.right-main1 {
				width: 792px;
				height: 421px;
				padding: 20px 20px;
				position: relative;
				box-sizing: border-box;

				.right-boxplot-echarts {
					width: 100%;
					height: 100%;
					min-height: 300px;
				}

				.right-main1-tit {
					position: absolute;
					top: 18px;
					right: 31px;
					font-size: 14px;
					font-weight: 400;
					font-family: "Microsoft YaHei";
					line-height: 22px;
					color: rgb(132, 136, 142);
					z-index: 10;
				}
			}
		}
	}
}

.btn {
	position: absolute;
	top: 11px;

	/* 切换按钮 */
	width: 85px;
	height: 28px;
	/* 自动布局 */
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	gap: 8;
	padding: 1px 8px 1px 8px;

	color: rgba(59, 65, 75, 1);
	box-sizing: border-box;
	border: 1px solid rgba(230, 231, 232, 1);
	border-radius: 4px;
	background: rgba(255, 255, 255, 1);
	font-family: Microsoft YaHei;
	font-style: Regular;
	font-size: 16px;
	font-weight: 400;
	line-height: 24px;
	letter-spacing: 0px;
	text-align: left;
}

.btn-select {
	position: absolute;
	top: 11px;
	/* 切换按钮 */
	width: 85px;
	height: 28px;
	/* 自动布局 */
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	gap: 8;
	padding: 1px 8px 1px 8px;
	color: rgba(5, 95, 194, 1);
	box-sizing: border-box;
	border: 1px solid rgba(5, 95, 194, 1);
	border-radius: 4px;
	background: rgba(231, 243, 255, 1);
	font-family: Microsoft YaHei;
	font-style: Regular;
	font-size: 16px;
	font-weight: 400;
	line-height: 24px;
	letter-spacing: 0px;
	text-align: left;
}
</style>
