<template>
	<div class="wrap">
		<div class="content-list">
			<div class="content-item" v-loading="box1Loading">
				<AnalysisBox title="数量变化趋势">
					<template #header-btn>
						<div class="warning-text">{{ `${inProgressCount}项调查仍在进行中` }}</div>
					</template>
					<div class="box-main">
						<div class="box-head" ref="box1Chart"></div>
						<TipTab text="美对华301调查案件的数量变化趋势，数据来源：美国贸易代表办公室官网" style="margin-top: 16px" />
						<div class="ai-pane">
							<AiButton />
							<AiPane :aiContent="aiContent.content1" />
						</div>
					</div>
				</AnalysisBox>
			</div>
			<div class="content-item" v-loading="box2Loading">
				<AnalysisBox title="国家分布情况">
					<template #header-btn>
						<el-select v-model="box2Paarams.years" @change="handleGetSearchCountry()" 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" id="box2Chart"></div>
						<TipTab text="美301调查所涉及的国家分布情况，数据来源：美国贸易代表办公室官网" style="margin-top: 16px" />
						<div class="ai-pane">
							<AiButton />
							<AiPane :aiContent="aiContent.content2" />
						</div>
					</div>
				</AnalysisBox>
			</div>
		</div>
		<div class="content-list">
			<div class="content-item" v-loading="box3Loading">
				<AnalysisBox title="调查方向及结果分布">
					<div class="box-main">
						<div class="box-head" id="box3Chart"></div>
						<TipTab text="美301调查方向及结果分布情况，数据来源：美国贸易代表办公室官网" style="margin-top: 16px;" />
						<div class="ai-pane">
							<AiButton />
							<AiPane :aiContent="aiContent.content3" />
						</div>
					</div>
				</AnalysisBox>
			</div>
			<div class="content-item" v-loading="box4Loading">
				<AnalysisBox title="领域分布情况">
					<template #header-btn>
						<el-select v-model="box4Paarams.years" @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 text="美对华301调查案件的领域分布情况，数据来源：美国贸易代表办公室官网" style="margin-top: -16px;" />
						<div class="ai-pane">
							<AiButton />
							<AiPane :aiContent="aiContent.content4" />
						</div>
					</div>
				</AnalysisBox>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, nextTick, reactive } 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/utils/baseLineChart";
import createPieChart from "@/views/marketAccessRestrictions/utils/basePiechart.js";
import AiButton from '@/components/base/Ai/AiButton/index.vue';
import AiPane from '@/components/base/Ai/AiPane/index.vue';
import { getNearYearList, getAIReport } from "@/views/marketAccessRestrictions/utils/index.ts";

const yearList = getNearYearList();
// 获取AI智能报告
const aiContent = reactive({
	content1: "正在生成...",
	content2: "正在生成...",
	content3: "正在生成...",
	content4: "正在生成...",
})
const onAIReport = (data, key) => {
	getAIReport(data).then(res => { aiContent[key] = res })
}

const inProgressCount = ref(0);

const box1Chart = ref(null);
const box1Loading = ref(false);
const handleGetStatNum = async () => {
	box1Loading.value = true;
	let chartData = { title: [], list: [] }
	try {
		const res = await getStatNum({ byYorM: "12", sortCode: "301" });
		console.log('数量变化趋势', res)
		if (res.code === 200 && res.data) {
			const sortedData = res.data.sort((a, b) => parseInt(a.searchYorM) - parseInt(b.searchYorM));
			chartData.title = sortedData.map(item => item.searchYorM);
			chartData.list = [{ name: "301调查", value: sortedData.map(item => item.searchCount) }]
			inProgressCount.value = res.data.reduce((acc, cur) => acc + (cur.inSearchCount || 0), 0);
		} else {
			chartData.title = []
			chartData.list = []
			inProgressCount.value = 0
		}
	} catch (error) {
		chartData.title = []
		chartData.list = []
		inProgressCount.value = 0
	}
	onAIReport({ type: "折线图", name: "数量变化趋势", data: chartData }, "content1")
	nextTick(() => { createLineChart(box1Chart, chartData) })
	box1Loading.value = false;
};

const box2Paarams = reactive({
	sortCode: 301,
	years: '2025'
})
const box2Loading = ref(false);
const handleGetSearchCountry = async () => {
	box2Loading.value = true;
	let chartData = { title: [], data: [] }
	try {
		const res = await getSearchCountry(box2Paarams);
		console.log('国家分布情况', res)
		if (res.code === 200 && res.data) {
			chartData.title = res.data.map(item => ({
				img: item.COUNTRYIMAGE ? (item.COUNTRYIMAGE.startsWith("http") ? item.COUNTRYIMAGE : `http://${item.COUNTRYIMAGE}`) : "",
				name: item.COUNTRY
			}));
			chartData.data = res.data.map(item => item.NUM)
			
		} else {
			chartData.title = []
			chartData.data = []
		}
	} catch (error) {
		chartData.title = []
		chartData.data = []
	}
	onAIReport({ type: "柱状图", name: "国家分布情况", data: chartData }, "content2")
	nextTick(() => {
		const box2Chart = getBarChart(chartData.title, chartData.data);
		setChart(box2Chart, "box2Chart");
	})
	box2Loading.value = false;
};

const box3Loading = ref(false);
const handleGetSearchDirection = async () => {
	box3Loading.value = true;
	let chartData = { nodes: [], links: [] }
	try {
		const res = await getSearchDirection({ sortCode: "301" });
		console.log('调查方向及结果分布', res)
		chartData.nodes = [];
		chartData.links = [];
		if (res.code === 200 && res.data) {
			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) {
					chartData.links.push({
						source: item.SEARCHDIRECTION,
						target: item.SEARCHRESULT,
						value: item.SEARCHCOUNT || 0
					});
				}
			});
			nodeNames.forEach(name => { chartData.nodes.push({ name }) });
		}
	} catch (error) {
		chartData.nodes = [];
		chartData.links = [];
	}
	onAIReport({ type: "桑基图", name: "调查方向及结果分布", data: chartData }, "content3")
	nextTick(() => {
		const box3Chart = getSankeyChart(chartData.nodes, chartData.links);
		setChart(box3Chart, "box3Chart");
	})
	box3Loading.value = false;
};

const box4Chart = ref(null)
const box4Paarams = reactive({
	sortCode: 301,
	years: '2025'
})
const box4Loading = ref(false);
const handleGetStatArea = async () => {
	box4Loading.value = true;
	let chartData = []
	try {
		const res = await getStatArea(box4Paarams);
		console.log('领域分布情况', res)
		if (res.code === 200 && res.data) {
			chartData = res.data.map(item => ({name: item.areaname, value: item.areacount}));
		} else {
			chartData = []
		}
	} catch (error) {
		chartData = []
	}
	onAIReport({ type: "环形图", name: "领域分布情况", data: chartData }, "content4")
	nextTick(() => { createPieChart(box4Chart, chartData) })
	box4Loading.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;
				position: relative;
				.box-head {
					height: 20px;
					flex: auto;
				}
				.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;
						}
					}
				}
			}
		}
	}

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