<template>
	<div class="overviewContainer">
		<div class="row">
			<CardCustom title="实体清单发布机构" :style="{ width: '984px', height: '284px' }">
				<div class="panel1">
					<img :src="organizationInfo.img" alt="" class="img" />
					<div class="infoWrap">
						<div class="item">
							<div class="name">机构名称：</div>
							<div class="doc">{{ organizationInfo.mingcheng }}</div>
						</div>
						<div class="item">
							<div class="name">相关措施：</div>
							<div class="doc">{{ organizationInfo.cuoshi }}</div>
						</div>
						<div class="item">
							<div class="name">机构职责：</div>
							<div class="doc zhize">{{ organizationInfo.zhize }}</div>
						</div>
					</div>
				</div>
			</CardCustom>
			<CardCustom title="重点人物" :style="{ width: '600px', height: '284px' }">
				<div class="panel2">
					<div class="item" v-for="(item, index) in personLis" :key="index" @click="handlePerClick(item)">
						<img :src="item.img" alt="" class="img" />
						<div class="infoWrap">
							<div class="name">{{ item.name }}</div>
							<div class="enName">{{ item.enName }}</div>
							<div class="party">{{ item.position }}</div>
						</div>
					</div>
				</div>
			</CardCustom>
		</div>
		<div class="row">
			<CardCustom title="实体清单分布" :style="{ width: '984px', height: '520px' }">
				<template #right>
					<div class="panel3ButtonWrap">
						<div
							class="leftButton"
							:class="{ activeButton: panel3ActiveIndex === 1 }"
							@click="setPanel3ActiveIndex(1)"
						>
							领域类别分布
						</div>
						<div
							class="rightButton"
							:class="{ activeButton: panel3ActiveIndex === 2 }"
							@click="setPanel3ActiveIndex(2)"
						>
							区域分布
						</div>
					</div>
					<div class="panel3Jinbi"></div>
				</template>
				<div class="panel3">
					<div class="chartWrap">
						<PieCharts v-if="panel3ActiveIndex === 1"></PieCharts>
						<MapCharts v-if="panel3ActiveIndex === 2" :date="route.query.startTime"></MapCharts>
					</div>
					<Hint text="本次制裁共新增83个实体，其中53个中国大陆实体、1个中国台湾实体。"></Hint>
				</div>
			</CardCustom>
			<CardCustom title="制裁原因" :style="{ width: '600px', height: '520px' }">
				<div class="panel4">
					<div class="item" v-for="(item, index) in sanReasonSelect" :key="index">
						<div class="icon1">{{ index + 1 }}</div>
						<div class="text">{{ item.text }}</div>
						<div class="icon2"></div>
					</div>
				</div>
			</CardCustom>
		</div>
		<div class="row">
			<CardCustom title="实体清单列表" :style="{ width: '984px', height: '678px' }">
				<template #right>
					<el-checkbox v-model="panel5IsChecked" label="只看中国实体" size="large" :style="{ marginRight: '15px' }" />
					<!-- <ButtonList
						:list="panel5ButtonList"
						:gap="8"
						:active-id="panel5ButtonAcitveID"
						@click="panel5SetButtonAcitveID"
						:style="{ marginRight: '15px' }"
					></ButtonList> -->
				</template>
				<div class="panel5">
					<div class="hintWrap">
						<div class="title">
							共计
							<span class="text1">{{ entityTotal }}</span>
							家，其中50%规则涉及
							<span class="text2">{{
								panel5IsChecked
									? entitiesCountBy50PercentRules?.ruleCount
									: entitiesCountBy50PercentRules?.totalCount
							}}</span>
							家
						</div>
					</div>
					<div class="tableWrap" ref="tableWrapRef" @scroll="handleScroll">
						<el-table
							:data="selectEntitiesList"
							class="sanction-table"
							stripe
							empty-text="暂无数据"
							header-row-class-name="table-header"
							row-class-name="table-row"
						>
							<el-table-column prop="name" label="实体清单" min-width="180">
								<template #default="{ row }">
									<div style="font-weight: 500" class="name" @click="handleOrgClick(row)">
										<img v-if="row.img" :src="row.img" alt="" class="img" />
										<div v-else class="imgUndefined">
											{{ row.name?.match(/[\u4e00-\u9fa5a-zA-Z0-9]/)?.[0] }}
										</div>
										{{ row.name }}
									</div>
								</template>
							</el-table-column>

							<el-table-column prop="domains" label="涉及领域" width="180">
								<template #default="{ row }">
									<div class="domain-tags">
										<el-tag v-for="tag in row.domains" :key="tag" :type="panel5TypeMap[tag]">{{
											tag
										}}</el-tag>
									</div>
								</template>
							</el-table-column>

							<!-- <el-table-column prop="address" label="上市地点" width="90" align="center">
								<template #default="{ row }">
									{{ row.address }}
								</template>
							</el-table-column> -->

							<el-table-column prop="time" label="制裁时间" width="150" align="center">
								<template #default="{ row }">
									{{ row.time }}
								</template>
							</el-table-column>

							<!-- <el-table-column prop="revenue" label="营收(亿元)" width="100" align="center">
								<template #default="{ row }">
									{{ row.revenue }}
								</template>
							</el-table-column> -->

							<el-table-column prop="subCompany" label="50%规则子企业" min-width="140" align="center">
								<template #default="{ row }">
									<span class="subCompany">
										{{ row.subCompany }}
									</span>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</div>
			</CardCustom>
			<CardCustom title="美国前序相关制裁、前序相关事件列表" :style="{ width: '600px', height: '678px' }">
				<div class="panel6">
					<div class="panel6-list">
						<div class="item" v-for="(item, idx) in panel6" :key="item.title">
							<div class="left">
								<div class="icon"></div>
								<div class="line"></div>
							</div>
							<div class="right">
								<div class="date">{{ item.time }}</div>
								<div class="title">{{ item.title }}</div>
								<div class="desc">{{ item.desc }}</div>
							</div>
						</div>
					</div>
					<div class="more" @click="handleMoreClick">
						查看更多
						<span class="moreIcon"></span>
					</div>
				</div>
			</CardCustom>
		</div>
	</div>
</template>

<script setup>
import CardCustom from "../../components/CardCustom.vue";
import PieCharts from "../components/pieCharts.vue";
import MapCharts from "../components/mapCharts.vue";
import ButtonList from "@/components/buttonList/buttonList.vue";
import Hint from "../components/hint.vue";
import { onMounted, reactive, ref, shallowRef, watch } from "vue";
import panel1_1 from "../../assets/images/panel1_1.png";
import {
	getOrganizationInfo,
	getPersonList,
	getSanReasonSelect,
	getSelectEntitiesList,
	getEntitiesList,
	getEntitiesCountBy50PercentRules,
	getPrecedingEvents
} from "@/api/exportControl";

import _ from "lodash";
import { useRoute, useRouter } from "vue-router";
import { formatAnyDateToChinese } from "../../utils";
const route = useRoute();
const router = useRouter();
const organizationInfo = shallowRef({});
const personLis = shallowRef([]);
const sanReasonSelect = shallowRef([
	{
		text: "获取美国产物项，以支持中国量子技术；"
	},
	{
		text: "支持2023年2月飞越美国上空的高空气球；"
	},
	{
		text: "获取获取美国原产的无人机物项供中国军方使用。"
	},
	{
		text: "法案序言称“中国光伏、风电企业通过政府补贴倾销产品”"
	},
	{
		text: "将中国定位为“通过强制技术转让获取先进制程的威胁”"
	}
]);

const handlePerClick = item => {
	console.log(item);
	const route = router.resolve({
		path: "/characterPage",
		query: {
			type: item.type || [1, 2, 3][Math.floor(Math.random() * 3)]
		}
	});
	window.open(route.href, "_blank");
};

const panel5IsChecked = ref(true);

const selectEntitiesList = shallowRef([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const tableWrapRef = ref(null);
const noMoreData = ref(false);
const entitiesCountBy50PercentRules = ref({
	ruleCount: 0,
	totalCount: 0
});
const precedingEvents = shallowRef([]);
const panel6 = ref([]);
const panel6CurrentPage = ref(1);
const panel6PageSize = ref(10);
const panel6Loading = ref(false);
const panel6NoMoreData = ref(false);

onMounted(async () => {
	try {
		const [organizationInfoData, sanReasonSelectData, entitiesCountBy50PercentRulesData, precedingEventsData] =
			await Promise.all([
				getOrganizationInfo(),
				// getPersonList(),
				getSanReasonSelect(route.query.startTime),
				getEntitiesCountBy50PercentRules("实体清单", currentPage.value, pageSize.value),
				// getSelectEntitiesList(route.query.startTime),
				getPrecedingEvents(route.query.startTime)
			]);
		console.log("entitiesCountBy50PercentRulesData", entitiesCountBy50PercentRulesData);
		entitiesCountBy50PercentRules.value = {
			ruleCount: entitiesCountBy50PercentRulesData?.ruleCount || 0,
			totalCount: entitiesCountBy50PercentRulesData?.totalCount || 0
		};
		organizationInfo.value = {
			img: panel1_1,
			mingcheng: organizationInfoData?.orgNameZh,
			cuoshi: organizationInfoData?.cuoshi || "出口管制条例（EAR）、实体清单、商业管制清单（CCL）、232调查等",
			zhize: organizationInfoData?.orgDuty || "--"
		};
		personLis.value = _.map(organizationInfoData?.personList, item => {
			return {
				name: item.name,
				enName: item.enName,
				position: item.position,
				party: item.party,
				img: item.imageUrl
			};
		});
		sanReasonSelect.value = _.map(sanReasonSelectData, item => {
			return { text: item };
		});

		precedingEvents.value = precedingEventsData.content || [];
		panel6.value = precedingEventsData.content.map(item => ({
			...item,
			time: formatAnyDateToChinese(item.eventTime),
			desc: item.summary || "--"
		}));

		// 初始化加载第一页数据
		await fetchEntitiesList(currentPage.value, pageSize.value);
	} catch (err) {
		console.log(err);
	}
});

// 获取实体清单数据
const entityTotal = ref(0);
const fetchEntitiesList = async (page = 1, size = 10) => {
	if (loading.value || noMoreData.value) return;

	loading.value = true;
	try {
		const res = await getEntitiesList("实体清单", page, size, route.query.startTime, panel5IsChecked.value);
		if (res) {
			entityTotal.value = res.totalElements;
			const newData = res.content.map(item => ({
				...item,
				name: item.entityNameZh,
				enName: item.entityName,
				domains: item.techDomains,
				time: formatAnyDateToChinese(item.startTime),
				address: "--",
				subCompany: "--",
				img: ""
			}));

			// 如果是第一页，替换数据；否则追加数据
			if (page === 1) {
				selectEntitiesList.value = newData;
			} else {
				selectEntitiesList.value = [...selectEntitiesList.value, ...newData];
			}

			total.value = res.totalElements;
			currentPage.value = res.number + 1;

			// 检查是否还有更多数据
			if (selectEntitiesList.value.length >= total.value) {
				noMoreData.value = true;
			}
		}
	} catch (err) {
		console.error(err);
		if (currentPage.value > 1) {
			currentPage.value--;
		}
	} finally {
		loading.value = false;
	}
};

watch(
	() => panel5IsChecked.value,
	newVal => {
		fetchEntitiesList(1, 10);
		// getEntitiesCountBy50PercentRules("实体清单", 1, pageSize.value)
	}
);

// 处理滚动事件
const debounceFlag = ref(false);
const handleScroll = () => {
	if (!tableWrapRef.value || debounceFlag.value) return;

	const { scrollTop, scrollHeight, clientHeight } = tableWrapRef.value;
	// 当距离底部小于50px时加载更多
	if (scrollHeight - scrollTop - clientHeight < 50) {
		// 设置防抖标志
		debounceFlag.value = true;
		loadMore();

		// 延迟重置防抖标志，防止连续触发
		setTimeout(() => {
			debounceFlag.value = false;
		}, 300);
	}
};

// 加载更多数据
const loadMore = () => {
	if (!loading.value && !noMoreData.value) {
		currentPage.value++;
		fetchEntitiesList(currentPage.value, pageSize.value);
	}
};

const panel3ActiveIndex = ref(1);
const setPanel3ActiveIndex = index => {
	panel3ActiveIndex.value = index;
};

const panel5ButtonList = [
	{ id: 1, text: "新增实体" },
	{ id: 2, text: "移除实体" }
];
const panel5ButtonAcitveID = ref(panel5ButtonList[0].id);
const panel5SetButtonAcitveID = id => {
	panel5ButtonAcitveID.value = id;
};

const panel5TypeMap = {
	人工智能: "danger",
	通信网络: "warning",
	航空航天: "success"
};

const handleOrgClick = item => {
	console.log(item);
	if (item.entityType != 2) return;
	const route = router.resolve({
		name: "companyPages",
		params: {
			id: item.id
		}
	});
	window.open(route.href, "_blank");
};

// 处理"查看更多"点击事件
const handleMoreClick = async () => {
	if (panel6Loading.value || panel6NoMoreData.value) return;

	panel6Loading.value = true;
	try {
		// 增加页码
		panel6CurrentPage.value++;

		// 获取更多数据
		const moreEvents = await getPrecedingEvents(route.query.startTime, panel6CurrentPage.value, panel6PageSize.value);

		if (moreEvents && Array.isArray(moreEvents.content) && moreEvents.content.length > 0) {
			// 处理新数据
			const newEvents = moreEvents.content.map(item => ({
				...item,
				time: formatAnyDateToChinese(item.eventTime),
				desc: item.summary || "--"
			}));

			// 追加到现有数据
			panel6.value = [...panel6.value, ...newEvents];

			// 检查是否还有更多数据（简单的检查方式）
			// 如果返回的数据少于请求的数量，则认为没有更多数据
			if (newEvents.length < panel6PageSize.value) {
				panel6NoMoreData.value = true;
			}
		} else {
			// 没有更多数据
			panel6NoMoreData.value = true;
		}
	} catch (error) {
		console.error("获取更多前序事件失败:", error);
		// 出错时回退页码
		panel6CurrentPage.value--;
	} finally {
		panel6Loading.value = false;
	}
};
</script>

<style lang="scss" scoped>
.overviewContainer {
	width: 1600px;
	margin: 0px auto 0 auto;
	padding-bottom: 20px;
}
.row {
	display: flex;
	flex-direction: row;
	gap: 16px;
	margin-top: 15px;
}
.panel1 {
	height: 100%;
	padding: 2px 35px 0 24px;
	display: flex;
	.img {
		width: 90px;
		height: 90px;
		margin-right: 16px;
	}
	.infoWrap {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 19px;
		.item {
			display: flex;

			.name {
				flex-shrink: 0;
				width: 100px;
				color: rgba(59, 65, 75, 1);
				font-size: 16px;
				font-weight: 700;
				line-height: 24px;
			}
			.doc {
				flex: 1;
				color: rgba(5, 95, 194, 1);
				font-size: 16px;
				font-weight: 700;
				line-height: 24px;
			}
			.zhize {
				color: rgba(95, 101, 108, 1);
				font-size: 16px;
				font-weight: 400;
				line-height: 24px;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 5; /* 控制行数 */
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}
	}
}
.panel2 {
	display: flex;
	flex-wrap: wrap;
	justify-content: flex-start;
	height: 100%;
	overflow: auto;
	align-content: flex-start;
	gap: 16px;
	padding: 0 23px 20px;
	.item {
		width: 268px;
		height: 94px;
		padding: 10px 16px;
		background: rgba(231, 243, 255, 0.5);
		display: flex;
		align-items: center;
		cursor: pointer;
		.img {
			width: 70px;
			height: 70px;
			margin-right: 16px;
		}
		.infoWrap {
			display: flex;
			flex-direction: column;
			flex: 1;
			max-height: 100%;
			gap: 3px;
			color: rgba(95, 101, 108, 1);
			font-size: 16px;
			font-weight: 400;
			line-height: 24px;
			.name {
				color: rgba(5, 95, 194, 1);
				font-size: 16px;
				font-weight: 700;
				line-height: 22px;
			}
		}
	}
}
.panel3 {
	height: 100%;
	display: flex;
	flex-direction: column;
	padding: 3px 24px 10px;
	.chartWrap {
		flex: 1;
	}
}
.panel3ButtonWrap {
	flex: 1;
	display: flex;
	justify-content: center;
	margin-right: 18px;
	.leftButton {
		width: 140px;
		height: 34px;
		/* 自动布局 */
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		color: rgba(5, 95, 194, 1);
		font-size: 16px;
		font-weight: 400;
		line-height: 24px;
		border-radius: 40px 0 0 40px;
		border: 2px solid rgba(5, 95, 194, 1);
		border-right: none;
		cursor: pointer;
	}
	.rightButton {
		width: 140px;
		height: 34px;
		/* 自动布局 */
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		color: rgba(5, 95, 194, 1);
		font-size: 16px;
		font-weight: 400;
		line-height: 24px;
		border-radius: 0px 40px 40px 0px;
		border: 2px solid rgba(5, 95, 194, 1);
		border-left: none;
		cursor: pointer;
	}
	.activeButton {
		background-color: rgba(5, 95, 194, 1);
		color: #ffffff;
	}
}
.panel3Jinbi {
	width: 28px;
	height: 28px;
	background-image: url("../../assets/images/panel3_1.png");
	background-size: 100% 100%;
	margin-right: 4px;
	cursor: pointer;
}
.panel4 {
	display: flex;
	flex-direction: column;
	gap: 8px;
	align-items: center;
	.item {
		width: 552px;
		height: 48px;
		display: flex;
		align-items: center;
		border: 1px solid rgba(234, 236, 238, 1);
		border-radius: 2px;
		.icon1 {
			width: 24px;
			height: 24px;
			border-radius: 12px;
			background-color: rgba(231, 243, 255, 1);
			display: flex;
			justify-content: center;
			align-items: center;
			margin-left: 15px;
			margin-right: 15px;
			font-size: 12px;
			color: rgb(5, 95, 194);
			font-weight: 500;
		}
		.text {
			color: rgba(59, 65, 75, 1);
			font-size: 16px;
			font-weight: 400;
			line-height: 30px;
			flex: 1;
			overflow: hidden;
			white-space: noWrap;
			text-overflow: ellipsis;
			min-width: 0;
		}
		.icon2 {
			width: 16px;
			height: 16px;
			background-image: url("../../assets/images/panel4_1.png");
			background-size: 100% 100%;
			margin-left: 15px;
			margin-right: 15px;
		}
	}
}
.panel5 {
	height: 100%;
	display: flex;
	flex-direction: column;
	padding: 3px 24px 10px;
	:deep(.table-header) {
		color: rgba(59, 65, 75, 1);
		font-size: 16px;
		font-weight: 700;
		height: 64px;
	}
	:deep(.table-row) {
		height: 60px;
		font-size: 16px;
		font-weight: 400;
	}
	.hintWrap {
		height: 40px;
		display: flex;
		align-items: center;
		padding: 0 12px;
		border: 1px solid rgb(231, 241, 255);
		border-radius: 4px;
		background: rgb(246, 251, 255);
		.title {
			color: var(--color-main-active);
			font-size: 14px;
			font-weight: 400;
			line-height: 24px;
			.text1 {
				color: rgb(206, 79, 81);
				font-weight: 900;
			}
			.text2 {
				color: rgb(255, 149, 77);
				font-weight: 900;
			}
		}
	}
	.tableWrap {
		flex: 1;
		margin-top: 14px;
		min-height: 0;
		overflow: auto;
		.domain-tags {
			display: flex;
			gap: 4px;
		}
	}
	.name {
		display: flex;
		align-items: center;
		cursor: pointer;
		.img {
			width: 40px;
			height: 40px;
			margin-right: 6px;
			margin-left: 6px;
			flex-shrink: 0;
		}
		.imgUndefined {
			width: 40px;
			height: 40px;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-shrink: 0;
			color: rgba(5, 95, 194, 1);
			background-color: rgb(236, 245, 255);
			border-radius: 20px;
			margin-right: 6px;
			margin-left: 6px;
		}
	}
	.subCompany {
		color: rgba(5, 95, 194, 1);
	}
}
.panel6 {
	height: 100%;
	padding: 6px 45px 20px 28px;
	display: flex;
	flex-direction: column;
	align-items: center;
	.panel6-list {
		height: 90%;
		overflow-y: auto;
		margin-bottom: auto;
		padding-left: 5px;
	}
	.item {
		display: flex;
		.left {
			position: relative;
			margin-right: 20px;
			.icon {
				position: absolute;
				left: -5px;
				top: 7px;
				width: 10px;
				height: 10px;
				background-image: url("../../assets/images/panel6_1.png");
				background-size: 100% 100%;
			}
			.line {
				width: 1px;
				background-color: rgba(174, 214, 255, 1);
				height: 100%;
			}
		}
		.right {
			flex: 1;
			display: flex;
			flex-direction: column;
			padding-bottom: 40px;
			.date {
				font-size: 16px;
				font-weight: 700;
				line-height: 24px;
				color: rgba(5, 95, 194, 1);
			}
			.title {
				color: rgba(5, 95, 194, 1);
				font-size: 16px;
				font-weight: 400;
				line-height: 24px;
				margin-top: 12px;
			}
			.desc {
				color: rgba(95, 101, 108, 1);
				font-size: 16px;
				font-weight: 400;
				line-height: 24px;
				margin-top: 8px;
			}
		}
	}
	.more {
		display: flex;
		color: rgba(5, 95, 194, 1);
		font-size: 14px;
		font-weight: 400;
		line-height: 22px;
		align-items: center;
		cursor: pointer;
		.moreIcon {
			width: 16px;
			height: 16px;
			background-image: url("../../assets/images/panel6_more.png");
			margin-left: 3px;
			background-size: 100% 100%;
			margin-bottom: 2px;
		}
	}
}
</style>
