<template>
	<div class="wrap">
		<div class="content-list">
			<div class="content-item" v-loading="box1Loading">
				<AnalysisBox title="对华301调查年度数量趋势">
					<template #header-btn>
						<div class="warning-text">{{ `${inProgressCount}项调查仍在进行中` }}</div>
					</template>
					<div class="box-main">
						<div class="box-head" ref="box1Chart"></div>
						<TipTab style="margin-top: 16px" />
					</div>
				</AnalysisBox>
			</div>
			<div class="content-item" v-loading="box2Loading">
				<AnalysisBox title="301调查国家分布">
					<div class="box-main">
						<div class="box-head" id="box2Chart"></div>
						<TipTab style="margin-top: 16px" />
					</div>
				</AnalysisBox>
			</div>
		</div>
		<div class="content-list">
			<div class="content-item" v-loading="box3Loading">
				<AnalysisBox title="301调查方向及结果分布">
					<div class="box-main">
						<div class="box-head" id="box3Chart"></div>
						<TipTab style="margin-top: 16px;" />
					</div>
				</AnalysisBox>
			</div>
			<div class="content-item" v-loading="box4Loading">
				<AnalysisBox title="301调查领域分布">
					<template #header-btn>
						<el-select v-model="selectYear" @change="handleGetStatArea()" placeholder="选择时间" style="width:120px; margin-right:12px;">
							<el-option v-for="item in yearList" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
					<div class="box-main">
						<div class="box-head" ref="box4Chart"></div>
						<TipTab style="margin-top: -16px;" />
					</div>
				</AnalysisBox>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import setChart from "@/utils/setChart";
import getBarChart from "./utils/barChart";
import getSankeyChart from "./utils/sankey";
import {
	getSearchCountry,
	getStatArea,
	getStatNum,
	getSearchDirection
} from "@/api/marketAccessRestrictions";
import createLineChart from "@/views/marketAccessRestrictions/marketAccessHome/utils/baseLineChart";
import createPieChart from "@/views/marketAccessRestrictions/marketAccessHome/utils/basePiechart.js";

const inProgressCount = ref(0);
const box1Loading = ref(false);
const box2Loading = ref(false);
const box3Loading = ref(false);
const box4Loading = ref(false);

const box1ChartData = ref({
	title: [],
	list: []
});
const box1Chart = ref(null);
const handleGetStatNum = async () => {
	box1Loading.value = true;
	try {
		const res = await getStatNum({
			byYorM: "12",
			sortCode: "301"
		});
		if (res.code === 200 && res.data) {
			const sortedData = res.data.sort((a, b) => parseInt(a.searchYorM) - parseInt(b.searchYorM));
			box1ChartData.value.title = sortedData.map(item => item.searchYorM);
			box1ChartData.value.list = [{ name: "301调查", value: sortedData.map(item => item.searchCount) }]
			console.log(box1ChartData.value);
			inProgressCount.value = res.data.reduce((acc, cur) => acc + (cur.inSearchCount || 0), 0);
			nextTick(() => { createLineChart(box1Chart, box1ChartData.value) })
		}
	} catch (error) {
		console.error("获取调查年度数量趋势失败", error);
	} finally {
		box1Loading.value = false;
	}
};

const box3ChartData = ref({
	nodes: [],
	links: []
});
const handleGetSearchDirection = async () => {
	box3Loading.value = true;
	try {
		const res = await getSearchDirection({ sortCode: "301" });
		if (res.code === 200 && res.data) {
			const nodes = [];
			const links = [];
			const nodeNames = new Set();

			res.data.forEach(item => {
				if (item.SEARCHDIRECTION) nodeNames.add(item.SEARCHDIRECTION);
				if (item.SEARCHRESULT) nodeNames.add(item.SEARCHRESULT);

				if (item.SEARCHDIRECTION && item.SEARCHRESULT) {
					links.push({
						source: item.SEARCHDIRECTION,
						target: item.SEARCHRESULT,
						value: item.SEARCHCOUNT || 0
					});
				}
			});

			nodeNames.forEach(name => {
				nodes.push({ name });
			});

			box3ChartData.value = { nodes, links };
			const box3Chart = getSankeyChart(box3ChartData.value.nodes, box3ChartData.value.links);
			setChart(box3Chart, "box3Chart");
		}
	} catch (error) {
		console.error("获取调查方向及结果分布失败", error);
	} finally {
		box3Loading.value = false;
	}
};

// 获取最近年份列表
const currentYear = new Date().getFullYear();
const getYearList = (count = 6) => {
	const yearOptions = [];
	for (let i = 0; i < count; i++) {
		const year = currentYear - i;
		yearOptions.push({ label: `${year.toString()}年`, value: year.toString() });
	}
	return yearOptions;
};
const yearList = getYearList();
const selectYear = ref('2025');
const box4ChartData = ref([]);
const box4Chart = ref(null)
const handleGetStatArea = async () => {
	box4Loading.value = true;
	try {
		const res = await getStatArea({years: selectYear.value, sortCode: 301});
		if (res.code === 200 && res.data) {
			box4ChartData.value = res.data.map(item => ({name: item.areaname, value: item.areacount}));
		} else {
			box4ChartData.value = []
		}
	} catch (error) {
		box4ChartData.value = []
	}
	nextTick(() => { createPieChart(box4Chart, box4ChartData.value) })
	box4Loading.value = false;
};

const box2ChartData = ref({
	title: [],
	data: []
});
const handleGetSearchCountry = async () => {
	box2Loading.value = true;
	try {
		const res = await getSearchCountry({ sortCode: 301 });
		if (res.code === 200 && res.data) {
			box2ChartData.value = {
				title: res.data.map(item => ({
					img: item.COUNTRYIMAGE ? (item.COUNTRYIMAGE.startsWith("http") ? item.COUNTRYIMAGE : `http://${item.COUNTRYIMAGE}`) : "",
					name: item.COUNTRY
				})),
				data: res.data.map(item => item.NUM)
			};
			const box2Chart = getBarChart(box2ChartData.value.title, box2ChartData.value.data);
			setChart(box2Chart, "box2Chart");
		}
	} catch (error) {
		console.error("获取受调查国家分布失败", error);
	} finally {
		box2Loading.value = false;
	}
};

onMounted(() => {
	handleGetStatNum();
	handleGetSearchCountry();
	handleGetStatArea();
	handleGetSearchDirection();
});
</script>

<style lang="scss" scoped>
.wrap {
	width: 1600px;
	margin: 0 auto;
	padding: 20px 0;
	display: flex;
	flex-direction: column;
	gap: 16px;

	.content-list {
		height: 410px;
		display: flex;
		gap: 16px;

		.content-item {
			width: 20px;
			flex: auto;
			height: 100%;
			.box-main {
				width: 100%;
				height: 100%;
				padding: 12px 30px 20px;
				display: flex;
				flex-direction: column;
				.box-head {
					height: 20px;
					flex: auto;
				}
			}
		}
	}

	.warning-text {
		margin-right: 12px;
		height: 24px;
		color: rgba(206, 79, 81, 1);
		font-family: Microsoft YaHei;
		font-size: 18px;
		font-weight: 700;
		line-height: 24px;
		letter-spacing: 0px;
		text-align: center;
	}
}
</style>
