<template>
	<div class="industrial-impact">
		<div class="main">
			<div class="left">
				<!-- <div class="title-com">
					<div class="box"></div>
					<div class="text">制裁企业列表</div>
					<div class="right-group">
						<div class="btn">
							<img src="../../../../assets/数据库按钮.png" alt="" />
							<img src="../../../../assets/下载按钮.png" alt="" />
							<img src="../../../../assets/收藏按钮.png" alt="" />
						</div>
					</div>
				</div>
				<div class="left-main">
					<div class="top-bar">
						<el-select v-model="searchDomain" placeholder="全部领域" class="domain-select">
							<el-option label="全部领域" value="" />
							<el-option label="人工智能" value="1" />
							<el-option label="生物科技" value="2" />
							<el-option label="新一代信息技术" value="3" />
							<el-option label="量子科技" value="4" />
							<el-option label="新能源" value="5" />
							<el-option label="集成电路" value="6" />
							<el-option label="海洋" value="7" />
							<el-option label="先进制造" value="8" />
							<el-option label="新材料" value="9" />
							<el-option label="航空航天" value="10" />
							<el-option label="深海" value="11" />
							<el-option label="极地" value="12" />
							<el-option label="太空" value="13" />
							<el-option label="核" value="14" />
						</el-select>
						<el-input v-model="searchKeyword" class="search-input" placeholder="搜索实体" :suffix-icon="Search" />
					</div>
					<div class="company-list-container">
						<div class="list-header">企业名称</div>
						<div class="company-list">
							<div class="company-item" :class="{ active: selectedCompanyId === item.id }" v-for="item in entityList"
								:key="item.id" @click="selectedCompanyId = item.id">
								<div class="icon-wrapper">
									<img :src="defaultTitle" alt="" />
								</div>
								<div class="company-name">{{ item.name }}</div>
							</div>
						</div>
					</div>
				</div> -->
				<AnalysisBox title="制裁企业列表">
					<div class="left-main">
						<div class="top-bar">
							<el-select v-model="searchDomain" placeholder="全部领域" class="domain-select">
								<el-option label="全部领域" value="" />
								<el-option label="人工智能" value="1" />
								<el-option label="生物科技" value="2" />
								<el-option label="新一代信息技术" value="3" />
								<el-option label="量子科技" value="4" />
								<el-option label="新能源" value="5" />
								<el-option label="集成电路" value="6" />
								<el-option label="海洋" value="7" />
								<el-option label="先进制造" value="8" />
								<el-option label="新材料" value="9" />
								<el-option label="航空航天" value="10" />
								<el-option label="深海" value="11" />
								<el-option label="极地" value="12" />
								<el-option label="太空" value="13" />
								<el-option label="核" value="14" />
							</el-select>
							<el-input v-model="searchKeyword" class="search-input" placeholder="搜索实体" :suffix-icon="Search" />
						</div>
						<div class="company-list-container">
							<div class="list-header">企业名称</div>
							<div class="company-list">
								<div
									class="company-item"
									:class="{ active: selectedCompanyId === item.id }"
									v-for="item in entityList"
									:key="item.id"
									@click="selectedCompanyId = item.id"
								>
									<div class="icon-wrapper">
										<img :src="defaultTitle" alt="" />
									</div>
									<div class="company-name">{{ item.name }}</div>
								</div>
							</div>
						</div>
					</div>
				</AnalysisBox>
			</div>
			<div class="right">
				<div class="right-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: activeScale === item }" v-for="item in scaleOptions" :key="item"
									@click="handleScaleClick(item)">
									{{ item }}
								</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="right-main">
						<div class="echarts" ref="chartRef"></div>
						<div class="bottom">
							<img :src="ai" class="ai-icon" alt="" />
							<span class="text">列入实体清单后企业营收初期下降，后基本趋于稳定。</span>
							<img :src="right" class="right-icon" alt="" />
						</div>
					</div> -->
					<AnalysisBox title="企业规模">
						<template #header-btn>
							<div class="toggle-btns">
								<div
									class="t-btn"
									:class="{ active: activeScale === item }"
									v-for="item in scaleOptions"
									:key="item"
									@click="handleScaleClick(item)"
								>
									{{ item }}
								</div>
							</div>
						</template>
						<div class="right-main">
							<!-- <div class="echarts" ref="chartRef"></div> -->
							<!-- <div class="bottom">
								<img :src="ai" class="ai-icon" alt="" />
								<span class="text">列入实体清单后企业营收初期下降，后基本趋于稳定。</span>
								<img :src="right" class="right-icon" alt="" />
							</div> -->
							<EChart :option="revenueChartOption" autoresize :style="{ height: '300px' }" />
							<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="revenueChart.interpretation" />
							</div>
						</div>
					</AnalysisBox>
				</div>
				<div class="right-item">
					<!-- <div class="title-com">
						<div class="box"></div>
						<div class="text">企业市值变化</div>
						<div class="right-group">
							<div class="btn">
								<img src="../../../../assets/数据库按钮.png" alt="" />
								<img src="../../../../assets/下载按钮.png" alt="" />
								<img src="../../../../assets/收藏按钮.png" alt="" />
							</div>
						</div>
					</div>
					<div class="right-main">
						<div class="echarts" ref="marketChartRef"></div>
						<div class="bottom">
							<img :src="ai" class="ai-icon" alt="" />
							<span class="text">列入实体清单后企业营收初期下降，后基本趋于稳定。</span>
							<img :src="right" class="right-icon" alt="" />
						</div>
					</div> -->
					<AnalysisBox title="企业市值变化">
						<div class="right-main">
							<!-- <div class="echarts" ref="marketChartRef"></div>
							<div class="bottom">
								<img :src="ai" class="ai-icon" alt="" />
								<span class="text">列入实体清单后企业营收初期下降，后基本趋于稳定。</span>
								<img :src="right" class="right-icon" alt="" />
							</div> -->
							<EChart :option="marketChartOption" autoresize :style="{ height: '300px' }" />
							<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="marketChart.interpretation" />
							</div>
						</div>
					</AnalysisBox>
				</div>
				<div class="right-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: activeRD === item }" v-for="item in rdOptions" :key="item"
									@click="activeRD = item">
									{{ item }}
								</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="right-main">
						<div class="echarts" ref="rdChartRef"></div>
						<div class="bottom">
							<img :src="ai" class="ai-icon" alt="" />
							<span class="text">列入实体清单后企业研发资金投入逐渐提高。</span>
							<img :src="right" class="right-icon" alt="" />
						</div>
					</div> -->
					<AnalysisBox title="企业研发投入">
						<template #header-btn>
							<div class="toggle-btns">
								<div
									class="t-btn"
									:class="{ active: activeRD === item }"
									v-for="item in rdOptions"
									:key="item"
									@click="activeRD = item"
								>
									{{ item }}
								</div>
							</div>
						</template>
						<div class="right-main">
							<!-- <div class="echarts" ref="rdChartRef"></div>
							<div class="bottom">
								<img :src="ai" class="ai-icon" alt="" />
								<span class="text">列入实体清单后企业研发资金投入逐渐提高。</span>
								<img :src="right" class="right-icon" alt="" />
							</div> -->
							<EChart :option="rdChartOption" autoresize :style="{ height: '300px' }" />
							<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="rdChart.interpretation" />
							</div>
						</div>
					</AnalysisBox>
				</div>
				<div class="right-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: activeMarketShare === item }" v-for="item in marketShareOptions"
									:key="item" @click="activeMarketShare = item">
									{{ item }}
								</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="right-main">
						<div class="echarts" ref="shareChartRef"></div>
						<div class="bottom">
							<img :src="ai" class="ai-icon" alt="" />
							<span class="text">列入实体清单后企业营收初期下降，后基本趋于稳定。</span>
							<img :src="right" class="right-icon" alt="" />
						</div>
					</div> -->
					<AnalysisBox title="企业市场占比">
						<template #header-btn>
							<div class="toggle-btns">
								<div
									class="t-btn"
									:class="{ active: activeMarketShare === item }"
									v-for="item in marketShareOptions"
									:key="item"
									@click="activeMarketShare = item"
								>
									{{ item }}
								</div>
							</div>
						</template>
						<div class="right-main">
							<!-- <div class="echarts" ref="shareChartRef"></div>
							<div class="bottom">
								<img :src="ai" class="ai-icon" alt="" />
								<span class="text">列入实体清单后企业营收初期下降，后基本趋于稳定。</span>
								<img :src="right" class="right-icon" alt="" />
							</div> -->
							<EChart :option="shareChartOption" autoresize :style="{ height: '300px' }" />
							<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="shareChart.interpretation" />
							</div>
						</div>
					</AnalysisBox>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from "vue";
import { debounce } from "lodash";
import * as echarts from "echarts";
import { Search } from "@element-plus/icons-vue";
import defaultTitle from "../../../../assets/default-icon2.png";
import ai from "../../assets/ai.png";
import right from "../../assets/right.png";
import tipsIcon from "../../../../../assets/icons/info-icon.png";

import {
	getSingleSanctionEntityList,
	getSingleSanctionEntityRevenue,
	getSingleSanctionEntityNetProfit,
	getSingleSanctionEntityPersonnel,
	getSingleSanctionEntityMarketValue,
	getSingleSanctionEntityRDInvestment,
	getSingleSanctionEntityMarketShare
} from "@/api/exportControlV2.0";
import AiButton from "@/components/base/Ai/AiButton/index.vue";
import AiPane from "@/components/base/Ai/AiPane/index.vue";
import EChart from "@/components/Chart/index.vue";

import { useChartInterpretation } from "@/views/exportControl/utils/common";
const revenueChart = useChartInterpretation();
const marketChart = useChartInterpretation();
const rdChart = useChartInterpretation();
const shareChart = useChartInterpretation();

// 单次制裁-影响分析-企业市场占比
const marketShareData = ref([]);
const getMarketShare = async () => {
	if (!selectedCompanyId.value) return;
	try {
		const res = await getSingleSanctionEntityMarketShare({
			id: selectedCompanyId.value
		});
		if (res.code === 200) {
			marketShareData.value = res.data || [];

			// 格式化市场占比数据
			const sortedData = [...marketShareData.value].sort((a, b) => a.year - b.year);
			if (sortedData.length > 0) {
				shareChartData.value = {
					dates: sortedData.map(item => item.year.toString()),
					values: sortedData.map(item => Number(item.count?.toFixed(2) || 0)),
					unit: "%",
					sanctionDate: "2024\nQ1" // 默认制裁日期
				};

				nextTick(() => {
					initShareChart();
				});
				shareChart.interpret({ type: "柱状图", name: "企业市场占比", data: sortedData });
			}
		}
	} catch (error) {
		console.log(error);
	}
};

// 单次制裁-影响分析-企业研发投入
const rdInvestmentData = ref([]);
const getRDInvestment = async () => {
	if (!selectedCompanyId.value) return;
	try {
		const res = await getSingleSanctionEntityRDInvestment({
			id: selectedCompanyId.value
		});
		if (res.code === 200) {
			rdInvestmentData.value = res.data || [];

			// 格式化研发投入数据
			const sortedData = [...rdInvestmentData.value].sort((a, b) => a.year - b.year);
			if (sortedData.length > 0) {
				const lastItem = sortedData[sortedData.length - 1];
				rdChartData.value = {
					dates: sortedData.map(item => item.year.toString()),
					values: sortedData.map(item => Number(item.count?.toFixed(2) || 0)),
					unit: " 万",
					endValue: Number(lastItem.count?.toFixed(2) || 0),
					sanctionDate: "2024\nQ1" // 默认制裁日期
				};

				nextTick(() => {
					initRDChart();
				});
				rdChart.interpret({ type: "折线图", name: "企业研发投入", data: sortedData });
			}
		}
	} catch (error) {
		console.log(error);
	}
};

// 单次制裁-影响分析-企业市值变化
const marketValueData = ref([]);
const getMarketValue = async () => {
	if (!selectedCompanyId.value) return;
	try {
		const res = await getSingleSanctionEntityMarketValue({
			id: selectedCompanyId.value
		});
		if (res.code === 200) {
			marketValueData.value = res.data || [];

			// 格式化市值数据
			const sortedData = [...marketValueData.value].sort((a, b) => a.year - b.year);
			if (sortedData.length > 0) {
				const lastItem = sortedData[sortedData.length - 1];
				marketChartData.value = {
					dates: sortedData.map(item => item.year.toString()),
					values: sortedData.map(item => Number(item.count?.toFixed(2) || 0)),
					unit: " 万",
					endValue: Number(lastItem.count?.toFixed(2) || 0),
					sanctionDate: "2024\nQ1" // 默认制裁日期
				};

				nextTick(() => {
					initMarketChart();
				});
				marketChart.interpret({ type: "折线图", name: "企业市值变化", data: sortedData });
			}
		}
	} catch (error) {
		console.log(error);
	}
};

// 单次制裁-影响分析-企业规模-人员
const personnelData = ref([]);
// 单次制裁-影响分析-企业规模-人员-调查
const getPersonnel = async () => {
	if (!selectedCompanyId.value) return;
	try {
		const res = await getSingleSanctionEntityPersonnel({
			id: selectedCompanyId.value
		});
		if (res.code === 200) {
			personnelData.value = res.data || [];

			// 将数据格式化为图表所需格式
			const sortedData = [...personnelData.value].sort((a, b) => a.year - b.year);
			chartData.value = {
				dates: sortedData.map(item => item.year.toString()),
				values: sortedData.map(item => Number(item.count?.toFixed(0) || 0)), // 人员通常是整数
				unit: " 人",
				endValue: Number(sortedData[sortedData.length - 1]?.count || 0)
			};

			// 重新初始化图表
			nextTick(() => {
				initRevenueChart();
			});
			revenueChart.interpret({ type: "折线图", name: "企业规模", data: sortedData });
		}
	} catch (error) {
		console.log(error);
	}
};

// 单次制裁-影响分析-企业规模-净利润
const netProfitData = ref([]);
// 单次制裁-影响分析-企业规模-净利润-调查
const getNetProfitData = async () => {
	if (!selectedCompanyId.value) return;
	try {
		const res = await getSingleSanctionEntityNetProfit({
			id: selectedCompanyId.value
		});
		if (res.code === 200) {
			netProfitData.value = res.data || [];

			// 将数据格式化为图表所需格式
			const sortedData = [...netProfitData.value].sort((a, b) => a.year - b.year);
			chartData.value = {
				dates: sortedData.map(item => item.year.toString()),
				values: sortedData.map(item => Number(item.count?.toFixed(2) || 0)),
				unit: " 万",
				endValue: Number(sortedData[sortedData.length - 1]?.count.toFixed(2) || 0)
			};

			// 重新初始化图表
			nextTick(() => {
				initRevenueChart();
			});
			revenueChart.interpret({ type: "折线图", name: "企业规模", data: sortedData });
		}
	} catch (error) {
		console.log(error);
	}
};

// 单次制裁-影响分析-制裁企业列表
const entityList = ref([]);
const searchDomain = ref("");
const searchKeyword = ref("");
const selectedCompanyId = ref(null);
const sanRecordId = ref("");

// 单次制裁-影响分析-企业规模-营收
const revenueData = ref([]);
// 单次制裁-影响分析-企业规模-营收-查询
const getRevenueData = async () => {
	if (!selectedCompanyId.value) return;
	try {
		const res = await getSingleSanctionEntityRevenue({
			id: selectedCompanyId.value
		});
		if (res.code === 200) {
			revenueData.value = res.data || [];
			// 将数据格式化为图表所需格式
			const sortedData = [...revenueData.value].sort((a, b) => a.year - b.year);
			chartData.value = {
				dates: sortedData.map(item => item.year.toString()),
				values: sortedData.map(item => Number(item.count?.toFixed(2) || 0)), // 防御空值
				unit: " 万",
				endValue: Number(sortedData[sortedData.length - 1]?.count.toFixed(2) || 0)
			};
			// 重新初始化图表
			nextTick(() => {
				initRevenueChart();
			});
			revenueChart.interpret({ type: "折线图", name: "企业规模", data: sortedData });
		}
	} catch (error) {
		console.log(error);
	}
};

const handleScaleClick = item => {
	activeScale.value = item;
	if (item === "营收") {
		getRevenueData();
	} else if (item === "净利润") {
		getNetProfitData();
	} else if (item === "人员") {
		getPersonnel();
	}
};

watch(selectedCompanyId, val => {
	if (val) {
		// 切换企业时，根据当前激活的按钮更新企业规模数据
		if (activeScale.value === "营收") {
			getRevenueData();
		} else if (activeScale.value === "净利润") {
			getNetProfitData();
		} else if (activeScale.value === "人员") {
			getPersonnel();
		}
		// 更新其他图表数据
		getMarketValue();
		getRDInvestment();
		getMarketShare();
	}
});

// 单次制裁-影响分析-制裁企业列表-查询
const getEntityList = async () => {
	try {
		const res = await getSingleSanctionEntityList({
			sanRecordId: sanRecordId.value,
			isOnlyCn: false,
			domainId: searchDomain.value || undefined,
			searchText: searchKeyword.value || undefined
		});
		if (res.code === 200) {
			entityList.value = (res.data || []).reduce((acc, group) => {
				if (group.orgType === "企业" && group.orgInfoList) {
					acc.push(
						...group.orgInfoList.map(org => ({
							id: org.id,
							name: org.orgNameZh
						}))
					);
				}
				return acc;
			}, []);

			// 默认选中第一个
			if (entityList.value.length > 0 && !selectedCompanyId.value) {
				selectedCompanyId.value = entityList.value[0].id;
			}
		}
	} catch (error) {
		console.log(error);
	}
};

const debouncedGetEntityList = debounce(() => {
	getEntityList();
}, 500);

watch(searchDomain, () => {
	getEntityList();
});

watch(searchKeyword, () => {
	debouncedGetEntityList();
});

const getUrlParams = () => {
	const urlParams = new URLSearchParams(window.location.search);
	sanRecordId.value = urlParams.get("id") || "";
};

const activeScale = ref("营收");
const scaleOptions = ["营收", "净利润", "人员"];

const activeRD = ref("研发经费");
const rdOptions = ["研发经费"];

const activeMarketShare = ref("总体市场份额");
const marketShareOptions = ["总体市场份额"];

const chartData = ref({
	dates: [],
	values: [],
	sanctionDate: "",
	endValue: 0
});

const marketChartData = ref({
	dates: [],
	values: [],
	sanctionDate: "",
	endValue: 0
});

const rdChartData = ref({
	dates: [],
	values: [],
	sanctionDate: "",
	endValue: 0
});

const shareChartData = ref({
	dates: [],
	values: [],
	sanctionDate: "",
	unit: "%"
});

const chartRef = ref(null);
const marketChartRef = ref(null);
const rdChartRef = ref(null);
const shareChartRef = ref(null);

// 提取通用配置生成器
const getBaseOption = data => {
	return {
		tooltip: {
			trigger: "axis",
			valueFormatter: value => value + (data.unit || " 亿元")
		},
		grid: {
			top: "15%", // 默认顶部留白
			left: "2%",
			right: "4%",
			bottom: "5%",
			containLabel: true
		},
		xAxis: {
			type: "category",
			boundaryGap: true,
			data: data.dates || [],
			axisLine: { lineStyle: { color: "#E6EBF5" } },
			axisLabel: {
				color: "#606266",
				fontSize: 10,
				interval: 0,
				rotate: 45,
				hideOverlap: false
			},
			axisTick: { show: false }
		},
		yAxis: {
			type: "value",
			min: 0,
			splitNumber: 5,
			axisLabel: {
				color: "#606266",
				fontSize: 12,
				formatter: value => value.toLocaleString()
			},
			splitLine: { lineStyle: { type: "dashed", color: "rgba(231, 243, 255, 1)" } }
		}
	};
};
const revenueChartOption = ref(getBaseOption({}));
// 1. 初始化企业营收图表 (应用原型图置顶样式)
const initRevenueChart = () => {
	// const dom = chartRef.value;
	const data = chartData.value;
	// if (!dom || !data.values || data.values.length === 0) return;

	// let myChart = echarts.getInstanceByDom(dom) || echarts.init(dom);
	const lastDate = data.dates[data.dates.length - 1];
	const lastValue = data.values[data.values.length - 1];
	const unit = data.unit || " 亿元";

	const maxVal = Math.max(...data.values.map(v => Number(v) || 0));
	const maxY = Math.ceil((maxVal * 1.5) / 100) * 100 || 100;

	const option = getBaseOption(data);
	option.grid.top = "20%"; // 增加顶部空间
	option.yAxis.max = maxY;
	option.series = [
		{
			data: data.values,
			type: "line",
			symbol: "none",
			lineStyle: { color: "#055FC2", width: 2 },
			areaStyle: {
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{ offset: 0, color: "rgba(5, 95, 194, 0.2)" },
					{ offset: 1, color: "rgba(5, 95, 194, 0)" }
				])
			},
			markLine: {
				symbol: "none",
				data: [
					data.sanctionDate
						? {
								xAxis: data.sanctionDate,
								label: {
									formatter: "列入实体清单",
									position: "end",
									color: "#F56C6C",
									backgroundColor: "rgba(255, 238, 238, 1)",
									borderRadius: 4,
									padding: [4, 8]
								},
								lineStyle: { color: "#F56C6C", type: "dotted", width: 1 }
							}
						: null,
					[
						{ coord: [lastDate, lastValue], symbol: "none" },
						{ coord: [lastDate, maxY], symbol: "none", lineStyle: { color: "#055FC2", type: "dotted" } }
					]
				].filter(Boolean)
			},
			markPoint: {
				symbol: "circle",
				symbolSize: 6,
				itemStyle: { color: "#055FC2" },
				label: {
					show: true,
					position: "left",
					formatter: "{c}" + unit.trim(),
					color: "#055FC2",
					fontSize: 16,
					fontWeight: "bold",
					offset: [-10, 0]
				},
				data: [{ coord: [lastDate, maxY], value: data.endValue || lastValue }]
			}
		}
	];
	// myChart.setOption(option, true);
	revenueChartOption.value = option;
};

const marketChartOption = ref(getBaseOption({}));
// 2. 初始化企业市值图表
const initMarketChart = () => {
	// const dom = marketChartRef.value;
	const data = marketChartData.value;
	// if (!dom || !data.values || data.values.length === 0) return;

	// let myChart = echarts.getInstanceByDom(dom) || echarts.init(dom);
	const lastDate = data.dates[data.dates.length - 1];
	const lastValue = data.values[data.values.length - 1];
	const unit = data.unit || " 万";

	const maxVal = Math.max(...data.values.map(v => Number(v) || 0));
	const maxY = Math.ceil((maxVal * 1.5) / 100) * 100 || 100;

	const option = getBaseOption(data);
	option.grid.top = "20%"; // 增加顶部空间
	option.yAxis.max = maxY;
	option.series = [
		{
			data: data.values,
			type: "line",
			symbol: "none",
			lineStyle: { color: "#055FC2", width: 2 },
			areaStyle: {
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{ offset: 0, color: "rgba(5, 95, 194, 0.2)" },
					{ offset: 1, color: "rgba(5, 95, 194, 0)" }
				])
			},
			markLine: {
				symbol: "none",
				data: [
					data.sanctionDate
						? {
								xAxis: data.sanctionDate,
								label: { formatter: "列入实体清单", position: "end", color: "#F56C6C" },
								lineStyle: { color: "#F56C6C", type: "dotted" }
							}
						: null,
					[
						{ coord: [lastDate, lastValue], symbol: "none" },
						{ coord: [lastDate, maxY], symbol: "none", lineStyle: { color: "#055FC2", type: "dotted" } }
					]
				].filter(Boolean)
			},
			markPoint: {
				symbol: "circle",
				symbolSize: 6,
				itemStyle: { color: "#055FC2" },
				label: {
					show: true,
					position: "left",
					formatter: "{c}" + unit.trim(),
					color: "#055FC2",
					fontSize: 16,
					fontWeight: "bold",
					offset: [-10, 0]
				},
				data: [{ coord: [lastDate, maxY], value: data.endValue || lastValue }]
			}
		}
	];
	// myChart.setOption(option, true);
	marketChartOption.value = option;
};

const rdChartOption = ref(getBaseOption({}));
// 3. 初始化研发投入图表
const initRDChart = () => {
	// const dom = rdChartRef.value;
	const data = rdChartData.value;
	// if (!dom || !data.values || data.values.length === 0) return;

	// let myChart = echarts.getInstanceByDom(dom) || echarts.init(dom);
	const lastDate = data.dates[data.dates.length - 1];
	const lastValue = data.values[data.values.length - 1];
	const unit = data.unit || " 万";

	// 计算 Y 轴最大值，留出顶部空间给数值标签
	const maxVal = Math.max(...data.values.map(v => Number(v) || 0));
	const maxY = Math.ceil((maxVal * 1.5) / 100) * 100 || 100;

	const option = getBaseOption(data);
	option.grid.top = "20%"; // 增加顶部空间
	option.yAxis.max = maxY;
	option.series = [
		{
			data: data.values,
			type: "line",
			symbol: "none",
			lineStyle: { color: "#055FC2", width: 2 },
			areaStyle: {
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{ offset: 0, color: "rgba(5, 95, 194, 0.2)" },
					{ offset: 1, color: "rgba(5, 95, 194, 0)" }
				])
			},
			markLine: {
				symbol: "none",
				data: [
					data.sanctionDate
						? {
								xAxis: data.sanctionDate,
								label: { formatter: "列入实体清单", position: "end", color: "#F56C6C" },
								lineStyle: { color: "#F56C6C", type: "dotted" }
							}
						: null,
					[
						{ coord: [lastDate, lastValue], symbol: "none" },
						{ coord: [lastDate, maxY], symbol: "none", lineStyle: { color: "#055FC2", type: "dotted" } }
					]
				].filter(Boolean)
			},
			markPoint: {
				symbol: "circle",
				symbolSize: 6,
				itemStyle: { color: "#055FC2" },
				label: {
					show: true,
					position: "left",
					formatter: "{c}" + unit.trim(),
					color: "#055FC2",
					fontSize: 16,
					fontWeight: "bold",
					offset: [-10, 0]
				},
				data: [{ coord: [lastDate, maxY], value: data.endValue || lastValue }]
			}
		}
	];
	// myChart.setOption(option, true);
	rdChartOption.value = option;
};
const shareChartOption = ref(getBaseOption({}));
// 4. 初始化市场占比图表 (柱状图)
const initShareChart = () => {
	// const dom = shareChartRef.value;
	const data = shareChartData.value;
	// if (!dom || !data.values || data.values.length === 0) return;

	// let myChart = echarts.getInstanceByDom(dom) || echarts.init(dom);
	const option = getBaseOption(data);

	// 针对柱状图优化 X 轴
	option.xAxis.boundaryGap = true;
	option.xAxis.axisLabel.interval = "auto"; // 自动计算间隔，避免标签重叠导致柱子变细

	option.yAxis.name = "百分比";
	// 动态计算 Y 轴最大值，避免数据太小时展示不明显
	const maxVal = Math.max(...data.values);
	const maxY = maxVal === 0 ? 100 : maxVal * 1.5;
	option.yAxis.max = maxY;

	option.series = [
		{
			data: data.values,
			type: "bar",
			// 移除固定 barWidth，让其根据数据量自适应，或设置一个合理的最小值
			barMaxWidth: 20,
			barMinHeight: 2, // 确保即使数值极小也能看到一点
			itemStyle: {
				color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
					{ offset: 0, color: "#055FC2" },
					{ offset: 1, color: "rgba(5, 95, 194, 0.1)" }
				]),
				borderRadius: [8, 8, 0, 0]
			},
			markLine: {
				symbol: "none",
				data: [
					data.sanctionDate
						? {
								xAxis: data.sanctionDate,
								label: {
									formatter: "列入实体清单",
									position: "end",
									color: "#F56C6C",
									backgroundColor: "rgba(245, 108, 108, 0.1)",
									padding: [2, 4],
									borderRadius: 10
								},
								lineStyle: { color: "#F56C6C", type: "dotted" }
							}
						: null
				].filter(Boolean)
			}
		}
	];
	// myChart.setOption(option, true);
	shareChartOption.value = option;
};

onMounted(async () => {
	getUrlParams();
	// 单次制裁-影响分析-制裁企业列表-查询 (获取到默认的 selectedCompanyId 后会触发 watch 加载其他数据)
	await getEntityList();

	// 初始化阶段默认调用营收数据
	if (selectedCompanyId.value) {
		getRevenueData();
	}
});
</script>

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

.industrial-impact {
	width: 100%;
	padding-top: 16px;
	padding-bottom: 50px;

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

		.t-btn {
			padding: 2px 8px;
			border: 1px solid rgb(230, 231, 232);
			border-radius: 4px;
			font-size: 16px;
			font-weight: 400;
			font-family: "Microsoft YaHei";
			color: rgb(59, 65, 75);
			cursor: pointer;
			box-sizing: border-box;

			&.active {
				color: rgb(5, 95, 194);
				background-color: rgba(231, 243, 255, 1);
				border-color: rgb(5, 95, 194);
			}
		}
	}

	.main {
		width: 100%;
		display: flex;
		justify-content: space-between;

		.left {
			width: 480px;
			height: 848px;

			.left-main {
				margin-top: 12px;
				padding: 0 16px;

				.top-bar {
					display: flex;
					gap: 12px;
					margin-bottom: 8px;

					.domain-select {
						width: 150px;

						:deep(.el-input__wrapper) {
							height: 32px;
							border-radius: 4px;
						}
					}

					.search-input {
						width: 288px;

						:deep(.el-input__wrapper) {
							height: 32px;
							border-radius: 4px;
						}
					}
				}

				.company-list-container {
					.list-header {
						width: 446px;
						height: 48px;
						padding: 12px 16px;
						font-size: 16px;
						font-weight: 700;
						color: rgb(59, 65, 75);
						border-top: 1px solid rgb(234, 236, 238);
						border-bottom: 1px solid rgb(234, 236, 238);
					}

					.company-list {
						height: 700px;
						overflow-y: auto;

						.company-item {
							display: flex;
							align-items: center;
							height: 48px;
							padding: 0 16px;
							cursor: pointer;
							border-bottom: 1px solid #f0f2f5;
							box-sizing: border-box;

							&:hover {
								background-color: #f5f7fa;
							}

							&.active {
								background-color: rgba(246, 250, 255, 1);
								border: 1px solid rgba(174, 214, 255, 1);

								.company-name {
									color: rgb(5, 95, 194);
									font-weight: 700;
								}

								.icon-wrapper {
									background-color: transparent;
								}
							}

							.icon-wrapper {
								width: 24px;
								height: 24px;
								display: flex;
								align-items: center;
								justify-content: center;
								margin-right: 12px;
								border-radius: 50%;

								img {
									width: 100%;
									height: 100%;
								}
							}

							.company-name {
								font-size: 16px;
								color: rgb(59, 65, 75);
								font-weight: 400;
								line-height: 24px;
								font-family: "Microsoft YaHei";
							}
						}
					}
				}
			}
		}

		.right {
			width: 1104px;
			height: 848px;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			align-content: space-between;

			.right-item {
				width: 544px;
				height: 416px;
				background-color: #fff;
				box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
				border-radius: 10px;
			}

			.right-main {
				width: 100%;
				height: calc(100% - 56px);
				padding: 0px 14px 15px 14px;

				.echarts {
					width: 516px;
					height: 300px;
					margin-bottom: 5px;
				}

				.bottom {
					width: 516px;
					// height: 40px;
					border-radius: 4px;
					background-color: rgba(246, 250, 255, 1);
					border: 1px solid rgba(231, 243, 255, 1);
					display: flex;
					align-items: center;
					padding: 6px 12px;
					box-sizing: border-box;

					.ai-icon {
						width: 20px;
						height: 20px;
						margin-right: 12px;
					}

					.text {
						flex: 1;
						font-size: 16px;
						font-family: "Microsoft YaHei";
						font-weight: 400;
						color: rgb(5, 95, 194);
						line-height: 24px;
					}

					.right-icon {
						width: 24px;
						height: 24px;
						cursor: pointer;
					}
				}
			}
		}
	}
}

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

		.rule-checkbox {
			margin-right: 20px;

			:deep(.el-checkbox__label) {
				font-size: 16px;
				color: #5f656c;
				font-family: "Microsoft YaHei";
			}

			:deep(.el-checkbox__inner) {
				border-color: #c9cdd4;
			}

			:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
				background-color: #055fc2;
				border-color: #055fc2;
			}

			:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
				color: #5f656c;
			}
		}

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

			.t-btn {
				padding: 2px 8px;
				border: 1px solid rgb(230, 231, 232);
				border-radius: 4px;
				font-size: 16px;
				font-weight: 400;
				font-family: "Microsoft YaHei";
				color: rgb(59, 65, 75);
				cursor: pointer;
				box-sizing: border-box;

				&.active {
					color: rgb(5, 95, 194);
					background-color: rgba(231, 243, 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;
		}
	}
}

.data-origin-box {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: flex-start;
	padding: 30px 0;
	.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>
