<template>
	<div class="relevant-situation">
		<div class="left">
			<div class="title">
				<div class="box"></div>
				<div class="text">相关实体</div>
				<div class="btn">
					<img src="./assets/下载按钮.png" alt="" />
					<img src="./assets/收藏按钮.png" alt="" />
				</div>
				<div class="search">
					<el-input v-model="searchText" placeholder="搜索内容" :suffix-icon="Search" class="search-input"></el-input>
					<el-select
						v-model="selectedOption"
						placeholder="请选择"
						class="search-select"
						popper-class="rs-select-popper"
						:teleported="false"
						size="small"
					>
					<el-option @click="" v-for="item in yearList" :key="item.value"
							:label="item.label" :value="item.value" />
					</el-select>
				</div>
			</div>
			<!-- 主要内容-echarts图表 -->
			<div class="chart">
				<div class="iconBox">
					<img src="./assets/icon01.png" alt="" @click="setLayout('circle')" />
					<img src="./assets/icon02.png" alt="" @click="setLayout('tree')" />
					<img src="./assets/icon03.png" alt="" @click="setLayout('force')" />
				</div>
				<div class="echarts"></div>
			</div>
			<div class="bottom">
				<img class="img01" src="./assets/AI.png" alt="" />
				<span class="text01"
					>美国《大而美法案》（OBBBA）通过系统性政策调整，对中国新能源产业链形成多维度冲击，同时倒逼产业链加速重构与技术创新。</span
				>
				<img class="img02" src="./assets/right.png" alt="" />
			</div>
		</div>
		<div class="right">
			<div class="title">
				<div class="box"></div>
				<div class="text">数据详情</div>
				<div class="btn">
					<img src="./assets/查看按钮.png" alt="" />
					<img src="./assets/下载按钮.png" alt="" />
					<img src="./assets/收藏按钮.png" alt="" />
				</div>
			</div>
			<!-- 主要内容 -->
			<div class="right-main">
				<div class="main-box">
					<div class="main-box-title">
						<img src="./assets/titleIcon01.png" alt="" class="title-icon" />
						<span class="title-text">科技法案</span>
						<img src="./assets/bottom.png" alt="" class="title-bottom" />
					</div>
					<div class="main-box-content" style="height: 300px;">
						<div v-for="item in relationBillsList" :key="item.id" class="item">
							<img :src="item.img" alt="" class="item-img" />
							<div>
								<div class="item-name">{{ item.name }}</div>
								<div class="item-date">{{ item.date }}</div>
							</div>
							<div class="item-type" :class="{'type-ai': item.type === '人工智能', 'type-energy': item.type === '能源'}">{{ item.type }}</div>
						</div>
					</div>
				</div>
				<div class="main-box">
					<div class="main-box-title">
						<img src="./assets/titleIcon02.png" alt="" class="title-icon" />
						<span class="title-text">科技政令</span>
						<img src="./assets/bottom.png" alt="" class="title-bottom" />
					</div>
					<div class="main-box-content" style="height: 142px;">
						<div v-for="item in relationAdList" :key="item.id" class="item">
							<div>
								<div class="item-name">{{ item.name }}</div>
								<div class="item-date">{{ item.date }}</div>
							</div>
							<div class="item-type-order">{{ item.type }}</div>
						</div>
					</div>
				</div>
				<div class="main-box">
					<div class="main-box-title">
						<img src="./assets/titleIcon03.png" alt="" class="title-icon" />
						<span class="title-text">科技智库</span>
						<img src="./assets/bottom.png" alt="" class="title-bottom" />
					</div>
                    <div class="main-box-content" style="height: 142px;">
						<div v-for="item in relationThinkTankList" :key="item.id" class="item">
							<img :src="item.img" alt="" class="item-img" />
							<div>
								<div class="item-name">{{ item.name }}</div>
								<div class="item-date">{{ item.date }}</div>
							</div>
							<img :src="item.type" alt="" class="item-type-img" />
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { Search } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import companyIcon from "./assets/company.png";
import companyRedIcon from "./assets/companyred.png";

import book1 from "./assets/book1.png";
import book2 from "./assets/book2.png";
import book3 from "./assets/book3.png";
import book4 from "./assets/book4.png";
import book5 from "./assets/book5.png";
import book6 from "./assets/book6.png";
import type1 from "./assets/type1.png";
import type2 from "./assets/type2.png";

import { getCharacterRelatedEntity } from "@/api/characterPage/characterPage.js";

import { useRoute } from 'vue-router';
const route = useRoute();
const personId = ref(route.query.personId || "Y000064");

const selectedOption = ref(1);
const yearList = ref([
	{
		label: "近一年",
		value: 1
	},
	{
		label: "近两年",
		value: 2
	},
	{
		label: "近五年",
		value: 5
	}
]);

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 relationBillsList = ref({});
const relationAdList = ref({});
const relationThinkTankList = ref({});

const getCharacterRelatedEntityFn = async () => {
	const params = {
		personId: personId.value,
		startTime: getDateYearsAgo(selectedOption.value) || "2025-01-01"
	};
	
	try{
		const res = await getCharacterRelatedEntity(params);
		if (res.code === 200) {
			console.log("人物相关实体", res);
			if (res.data) {
				relationBillsList.value = res.data.relationBillsList.map(item=>{
					return{
						id: item.billId,
						name: item.billName,
						type: item.industryList,
						date: item.billTime,
						img: book1 //待加
					}
				});
				relationAdList.value = res.data.relationAdList.map(item=>{
					return{
						id: item.id,
						name: item.adName,
						type: item.adType,
						date: item.adTime
					}
				});
				relationThinkTankList.value = res.data.relationThinkTankList.map(item=>{
					return{
						id: item.reportId,
						name: item.reportName,
						type: type1, //缺属性
						date: item.reportTime,
						img: item.thinkTankUrl
					}
				});
			}
		}
	}catch(error){

	}
	
};



const searchText = ref("");


const billList = ref([
	{
		id: 1,
		name: "大而美法案",
		type: "人工智能",
		date: "2025年7月4日",
		img: book1
	},
	{
		id: 2,
		name: "汽车零部件25%关税实施规则",
		type: "能源",
		date: "2025年7月4日",
		img: book2
	},
	{
		id: 3,
		name: "小额豁免包裹政策调整",
		type: "能源",
		date: "2025年7月4日",
		img: book3
	},
	{
		id: 4,
		name: "NIH预算否决案",
		type: "能源",
		date: "2025年7月4日",
		img: book4
	}
]);
const twoList = ref([
	{
		id: 1,
		name: "关于进一步延长TikTok执法宽限期的...",
		type: "总统政令",
		date: "2025年7月4日"
	},
	{
		id: 2,
		name: "修改对等关税税率以反映与中华人民...",
		type: "总统政令",
		date: "2025年7月4日"
	}
]); 
const billList2 = ref([
	{
		id: 1,
		name: "中国对AI的转型产业政策",
		type: type1,
		date: "2025年7月4日",
        img: book5
	},
	{
		id: 2,
		name: "中美对抗、竞争和合作跨越人工智能...",
		type: type2,
		date: "2025年7月4日",
        img: book6
	}
]);

let chart;
let resizeHandler;
const activeLayout = ref("circle");

const labels = [
	"大而美法案",
	"泰丰先行",
	"国轩高科",
	"晶科能源",
	"容百科技",
	"江西紫宸",
	"比亚迪",
	"长盈精密",
	"昆仑化学",
	"海辰储能",
	"华阳集团",
	"嘉源科技",
	"天合光能",
	"铜陵有色",
	"紫江企业",
	"格林美",
	"德方纳米"
];

const baseNodes = labels.map((name, i) => ({
	id: i.toString(),
	name
}));

// 构建从外圈指向中心的连线
const baseLinks = baseNodes
	.map((n, i) => {
		if (i === 0) return null;
		// 特殊节点：红色虚线
		const isSpecial = ["容百科技", "海辰储能", "华阳集团"].includes(n.name);
		if (isSpecial) {
			return {
				source: i.toString(),
				target: "0",
				lineStyle: {
					color: "rgb(206, 79, 81)",
					type: "dashed"
				}
			};
		}
		return { source: i.toString(), target: "0" };
	})
	.filter(Boolean);

const makeOption = el => {
	const rect = el.getBoundingClientRect();
	const cx = rect.width / 2;
	const cy = rect.height / 2;
	const radius = Math.min(cx, cy) - 150;

	const positioned = baseNodes.map((n, i) => {
		if (activeLayout.value === "circle") {
			if (i === 0) return { ...n, x: cx, y: cy, fixed: true };
			const angle = ((i - 1) / (baseNodes.length - 1)) * Math.PI * 2;
			const x = cx + radius * Math.cos(angle);
			const y = cy + radius * Math.sin(angle);
			return { ...n, x, y };
		}
		if (activeLayout.value === "tree") {
			if (i === 0) return { ...n, x: cx, y: cy - 200, fixed: true };
			const totalWidth = Math.min(rect.width, 1000) - 100;
			const gap = totalWidth / (baseNodes.length - 2); // 除去根节点后的间隔数
			const startX = cx - totalWidth / 2;

			// (i-1) 是因为 i 从 1 开始遍历子节点
			const x = startX + (i - 1) * gap;
			const y = cy + 100;
			return { ...n, x, y };
		}
		return { ...n };
	});

	const ringSeries = {
		type: "graph",
		layout: activeLayout.value === "force" ? "force" : "none",
		roam: true,
		data: positioned.map((n, i) => {
			const isForce = activeLayout.value === "force";
			const isSpecial = ["容百科技", "海辰储能", "华阳集团"].includes(n.name);
			const icon = isSpecial ? companyRedIcon : companyIcon;
			const textColor = isSpecial ? "rgb(206, 79, 81)" : "rgb(59, 65, 75)";

			// force 布局保持原样（直接显示图标）；其他布局使用圆圈+RichText Label显示图标和文字
			if (isForce) {
				return {
					...n,
					symbol: "image://" + icon,
					symbolSize: 18,
					draggable: true,
					label: {
						show: true,
						position: "bottom",
						color: textColor,
						fontSize: i === 0 ? 20 : 16,
						fontWeight: i === 0 ? 700 : 400
					}
				};
			}

			// Circle/Tree 布局：单层实现（圆圈 + Rich Text Icon + Text）
			return {
				...n,
				symbol: "circle",
				symbolSize: 36,
				draggable: true,
				label: {
					show: true,
					position: "inside",
					formatter:
						i === 0
							? "{icon|}\n{nameCenter|{b}}"
							: isSpecial
							? "{icon|}\n{nameRed|{b}}"
							: "{icon|}\n{nameNormal|{b}}",
					// 微调 offset：[x, y]。y 越大，整体越向下偏移。
					offset: i === 0 ? [0, 10] : [0, 10],
					rich: {
						icon: {
							width: 18,
							height: 18,
							backgroundColor: { image: icon },
							align: "center"
						},
						nameCenter: {
							padding: [16, 0, 0, 0],
							color: "rgb(59,65,75)",
							fontSize: 18,
							fontWeight: 700,
							fontFamily: "Microsoft YaHei",
							align: "center",
							lineHeight: 24
						},
						nameNormal: {
							padding: [16, 0, 0, 0],
							color: "rgb(59,65,75)",
							fontSize: 14,
							fontWeight: 400,
							fontFamily: "Microsoft YaHei",
							align: "center",
							lineHeight: 14
						},
						nameRed: {
							padding: [16, 0, 0, 0],
							color: "rgb(206, 79, 81)",
							fontSize: 14,
							fontWeight: 400,
							fontFamily: "Microsoft YaHei",
							align: "center",
							lineHeight: 14
						}
					}
				},
				itemStyle: {
					color: "#fff",
					borderColor: "rgb(230, 231, 232)",
					borderWidth: 1,
					shadowBlur: 8,
					shadowColor: "rgba(0, 0, 0, 0.1)"
				}
			};
		}),
		links: baseLinks,
		edgeSymbol: ["none", "arrow"],
		edgeSymbolSize: [4, 6],
		lineStyle: {
			color: "rgba(174, 214, 255, 1)",
			width: 2,
			opacity: 1
		},
		emphasis: { focus: "adjacency" },
		force: activeLayout.value === "force" ? { repulsion: 800, edgeLength: [80, 160] } : undefined
	};

	return {
		tooltip: {},
		series: [ringSeries]
	};
};

onMounted(() => {
	getCharacterRelatedEntityFn();
	const el = document.querySelector(".echarts");
	if (!el) return;
	chart = echarts.init(el);

	const option = makeOption(el);
	chart.setOption(option);

	resizeHandler = () => {
		if (!chart) return;
		chart.resize();
		chart.setOption(makeOption(el));
	};
	window.addEventListener("resize", resizeHandler);
});

onBeforeUnmount(() => {
	if (resizeHandler) window.removeEventListener("resize", resizeHandler);
	if (chart) chart.dispose();
});

// 切换布局
const setLayout = type => {
	activeLayout.value = type;
	const el = document.querySelector(".echarts");
	if (!el) return;
	const opt = makeOption(el);
	chart && chart.setOption(opt, true);
};
</script>

<style scoped lang="scss">
* {
	padding: 0;
	margin: 0;
}
.relevant-situation {
	width: 1600px;
	height: 848px;
	margin: 0 auto;
	display: flex;
	justify-content: space-between;
	align-items: center;
	.left {
		width: 1068px;
		height: 848px;
		margin-right: 12px;
		background-color: #fff;
		border-radius: 10px;
		box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
		.title {
			width: 100%;
			height: 56px;
			display: flex;
			align-items: center;
			padding: 14px 12px 16px 0;
			position: relative;
			.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);
			}
			.btn {
				width: 60px;
				height: 28px;
				margin-left: auto;
				img {
					width: 28px;
					height: 28px;
					cursor: pointer;
				}
				img:first-child {
					margin-right: 4px;
				}
			}
			.search {
				width: 312px;
				position: absolute;
				right: 83px;
				top: 14px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				.search-input {
					width: 150px;
					height: 24px;
					color: rgb(95, 101, 108);
					font-size: 12px;
					font-weight: 400;
					font-family: "Microsoft YaHei";
					line-height: 20px;
				}
				.search-select {
					width: 150px;
					height: 24px;
				}
			}
		}
		.chart {
			width: 1068px;
			height: 739px;
			padding: 14px 11px;
			background-image: url("./assets/background.png");
			background-size: cover;
			.iconBox {
				width: 96px;
				height: 28px;
				background-color: #fff;
				border-radius: 4px;
				border: 1px solid rgb(234, 236, 238);
				box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
				padding: 0px 7px 0px 14px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				img {
					width: 14px;
					height: 14px;
					cursor: pointer;
				}
				img:nth-child(2) {
					width: 16px;
					height: 16px;
				}
			}
			.echarts {
				width: 1046px;
				height: 683px;
			}
		}
		.bottom {
			width: 1036px;
			height: 40px;
			margin: 0 auto;
			background-color: rgba(246, 250, 255, 1);
			border: 1px solid rgba(231, 243, 255, 1);
			border-radius: 4px;
			padding: 6px 12px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.img01 {
				width: 19px;
				height: 20px;
			}
			.text01 {
				font-size: 16px;
				font-weight: 400;
				font-family: "Microsoft YaHei";
				line-height: 24px;
				color: rgb(5, 95, 194);
			}
			.img02 {
				width: 24px;
				height: 24px;
			}
		}
	}
	.right {
		width: 520px;
		height: 848px;
		background-color: #fff;
		border-radius: 10px;
		box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
		.title {
			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);
			}
			.btn {
				width: 92px;
				height: 28px;
				margin-left: auto;
				img {
					width: 28px;
					height: 28px;
					cursor: pointer;
				}
				img:first-child {
					margin-right: 4px;
				}
				img:nth-child(2) {
					margin-right: 4px;
				}
			}
		}
		.right-main {
			width: 100%;
			height: 732px;
			padding: 15px 19px 0 17px;
			.main-box {
				width: 484px;
				min-height: 190px;
				border-radius: 4px;
				border: 1px solid rgb(234, 236, 238);
				margin-bottom: 16px;
				.main-box-title {
					width: 100%;
					height: 48px;
					background-color: rgb(247, 248, 249);
					border-bottom: 1px solid rgb(234, 236, 238);
					display: flex;
					align-items: center;
					justify-content: space-between;
					position: relative;
					.title-icon {
						width: 23px;
						height: 21px;
						margin-left: 20px;
					}
					.title-bottom {
						width: 12px;
						height: 8px;
						margin-right: 20px;
					}
					.title-text {
						position: absolute;
						top: 12px;
						left: 58px;
						font-size: 16px;
						font-weight: 700;
						font-family: "Microsoft YaHei";
						line-height: 24px;
						color: rgb(5, 95, 194);
					}
				}
				.main-box-content {
					width: 100%;
					padding: 12px 0;
					overflow-y: scroll;
					.item {
						width: 100%;
						height: 53px;
						padding: 0 18px 0 19px;
						display: flex;
						align-items: center;
                        margin-bottom: 12px;
                        position: relative;
                        .item-img {
                            width: 36px;
                            height: 48px;
                            margin-right: 10px;
                        }
                        .item-name {
                            font-size: 16px;
                            font-weight: 700;
                            font-family: "Microsoft YaHei";
                            line-height: 30px;
                            color: rgb(59, 65, 75);
                        }
                        .item-date {
                            font-size: 16px;
                            font-weight: 400;
                            font-family: "Microsoft YaHei";
                            line-height: 24px;
                            color: rgb(132, 136, 142);
                        }
                        .item-type {
                            position: absolute;
                            top: 2px;
                            right: 18px;
                            font-size: 14px;
                            font-weight: 400;
                            font-family: "Microsoft YaHei";
                            line-height: 20px;
                            padding: 1px 8px;
                            
                        }
                        .type-ai {
							border-radius: 4px;
                            border: 1px solid;
                            color: rgba(19, 168, 168, 1);
                            border-color: rgba(135, 232, 222, 1);
                            background-color: rgba(230, 255, 251, 1);
                        }
                        .type-energy {
							border-radius: 4px;
                            border: 1px solid;
                            color: rgba(245, 34, 45, 1);
                            border-color: rgba(255, 163, 158, 1);
                            background-color: rgba(255, 241, 240, 1);
                        }
                        .item-type-order {
                            position: absolute;
                            top: 1px;
                            right: 17.58px;
                            font-size: 14px;
                            font-weight: 400;
                            font-family: "Microsoft YaHei";
                            line-height: 20px;
                            padding: 2px 18.21px;
                            border-radius: 4px;
                            border: 1px solid rgba(186, 224, 255, 1);
                            background-color: rgba(230, 244, 255, 1);
                            color: rgba(22, 119, 255, 1);
                        }
                        .item-type-img {
                            width: 16px;
                            height: 16px;
                            position: absolute;
                            top: 5px;
                            right: 14px;
                        }
					}
                    .item:last-child {
                        margin-bottom: 0;
                    }
				}
			}
		}
	}
}
</style>
