<template>
	<div class="wrap" ref="wrapRef">

		<div class="box1">
			<AnalysisBox title="政策建议相关情况" :showAllBtn="true">
				<div class="box1-main">
					<div class="left">
						<div class="search-box">
							<el-input placeholder="搜索政策建议" v-model="searchOpinions" @keyup.enter="handleSearchOpinions" />
							<div class="icon">
								<img src="../images/Line_Search.png" alt="" @click="handleSearchOpinions" />
							</div>

						</div>
						<div class="tag-box">
							<span class="tag" :class="{ 'tag-active': !activeTag }" @click="handleTagClick('')">
								<div class="tag-text">{{ "全部" }}</div>
							</span>
							<span class="tag" v-for="(tag, index) in allTags" :key="tag + index"
								:class="{ 'tag-active': activeTag === tag }" @click="handleTagClick(tag)">
								<span class="tag-text"> {{ tag }} ({{ tagCountMap[tag] || 0 }} 项)</span>
							</span>
						</div>
						<div class="item-box">
							<div class="item" v-for="(item, index) in filteredOpinions" :key="item.id || index"
								:class="{ 'item-active': index === activeItemIndex }" @click="
									() => {
										activeItemIndex = index;
										box1DataItem = item;
										console.log('当前选中政策建议：', item);
									}
								">
								<!-- 序号 -->
								<div class="item-left">{{ index + 1 }}</div>
								<!-- 标题中与搜索关键词相同的文字高亮显示 -->
								<div class="item-right" v-html="highlightKeyword(item.titleZh)"></div>
								<!-- 仅在选中项时显示右侧竖线 -->
								<div class="item-right-solid" v-if="index === activeItemIndex"></div>
							</div>
						</div>
						<div class="box4-main-footer">
							<div class="info">共{{ opinionsTotal }}条核心论点</div>
							<div class="page-box">
								<el-pagination :page-size="pageSize" background layout="prev, pager, next" :total="opinionsTotal"
									@current-change="handleCurrentChange" :current-page="currentPage" />
							</div>
						</div>
					</div>
					<div class="right" v-if="box1DataItem">
						<div class="right-header">
							<div class="header-text">
								<div class="left-text">
									{{ "政策建议详情" }}
								</div>
								<div class="right-text">
									<div class="text">
										{{ "跳转原文" }}
									</div>
									<div class="right-header-image">
										<img src="../images/image-open2.png" alt="" @click="toReport()" />
									</div>
								</div>
							</div>
						</div>
						<div class="right-content" v-html="box1DataItem ? highlightKeyword(box1DataItem.contentZh || '') : ''">
						</div>
						<div class="info-group">
							<div class="info-content">
								<div class="info-item">
									<div class="info-text">{{ "相关领域：" }}</div>
									<div class="info-right" v-if="box1DataItem && box1DataItem.domains">
										<div class="tag-box">
											<div class="tag" v-for="(item, index) in box1DataItem.domains" :key="index" v-show="item">{{
												item.industryName
											}}</div>
										</div>
									</div>
								</div>
								<div class="info-item" v-if="box1DataItem">
									<div class="info-text">{{ "遏制手段：" }}</div>
									<div class="info-right">
										<div class="tag-box">
											<div class="tag">{{ "移民政策" }}</div>
										</div>
									</div>
								</div>
								<div class="info-item">
									<div class="info-text">{{ "涉及部门：" }}</div>
									<div class="info-right" v-for="(item, index) in box1DataItem.organizations" :key="index"
										v-show="item">
										<div class="info-right-image">
											<img :src="item.logoUrl" />
										</div>
										<div class="info-right-text">
											{{ item.orgName }}
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="right-footer-title">
							<div class="footer-title-text">{{ "相关政策" }}</div>
						</div>
						<div class="right-footer-box">
							<div class="relatedBills" v-for="(item, index) in box1DataItem.relatedBills" :key="index" v-show="item">
								<div class="tag">{{ "法案" }}</div>
								<div class="tag">{{ "科技领域相似" }}</div>
								<div class="relatedBills-content">{{ item.name }}</div>
								<div class="footer-image" @click.stop="handleBillMoreClick(item)"> <img src="../images/image-right.png"
										alt="" /></div>
							</div>
							<div class="relatedAdministrativeOrders" v-for="(item, index) in box1DataItem.relatedAdministrativeOrders"
								v-show="item" :key="index">
								<div class="tag">{{ "政令" }}</div>
								<div class="tag">{{ "科技领域相似" }}</div>
								<div class="relatedAdministrativeOrders-content">{{ item.content }}</div>
								<div class="footer-image" @click.stop="handleAdministrativeMoreClick(item)"> <img
										src="../images/image-right.png" alt="" /></div>
							</div>
						</div>
					</div>
				</div>
			</AnalysisBox>

		</div>
	</div>



</template>

<script setup>
import { ref, onMounted, computed, nextTick } from "vue";
import {
	getThinkTankReportPolicy,
	getThinkTankReportPolicyAction
} from "@/api/thinkTank/overview";
import { useRouter } from "vue-router";
import DefaultNewsImg from '@/assets/images/default-icon-news.png'
const router = useRouter();
const searchOpinions = ref("");
// 政策建议相关情况（当前页/当前筛选展示的数据）
const box1Data = ref([]);
// 全量数据（用于标签统计与前端筛选分页）
const allBox1Data = ref([]);
// 每个标签在全部数据中的出现次数（基于全部数据，非当前页）
const tagCountMap = ref({});
// 标签列表（基于当前全量数据 + 搜索条件）
const allTags = ref([]);
// 当前选中的标签（空字符串表示“全部”）
const activeTag = ref("");
// 当前选中的条目索引（相对于当前页，默认选中第一个）
const activeItemIndex = ref(0);
const pageSize = ref(10);
// 当前选中 item 的数据
const box1DataItem = ref(null);
// 整个页面容器，用于分页后滚回 wrap 顶部
const wrapRef = ref(null);
const reportUrl = ref("");

// 总条数基于当前筛选条件（activeTag）
const opinionsTotal = computed(() => {
	if (!activeTag.value) {
		return allBox1Data.value.length;
	}
	return allBox1Data.value.filter(item =>
		(item.domains || []).some(d => d?.industryName === activeTag.value)
	).length;
});
const currentPage = ref(1);
const handleCurrentChange = page => {
	currentPage.value = page;
	activeItemIndex.value = 0;
	updatePageData();
	// 使用页面滚动轴滚动到最顶部
	nextTick(() => {
		scrollToWrapTop()
	});
};
const scrollToWrapTop = () => {
	const el = wrapRef.value;
	if (!el) return;

	// 向上查找最近的可滚动父元素
	let node = el.parentElement;
	while (node && node !== document.body && node !== document.documentElement) {
		if (node.scrollHeight > node.clientHeight + 1) {
			const top = node.scrollTop + el.getBoundingClientRect().top - node.getBoundingClientRect().top - 400;
			node.scrollTo({ top, behavior: "smooth" });
			return;
		}
		node = node.parentElement;
	}

	// 兜底：全局滚动
	window.scrollTo({
		top: el.getBoundingClientRect().top + window.scrollY - 40,
		behavior: "smooth"
	});
};

const toReport = () => {

	const route = router.resolve({
		name: "ReportOriginal",
		params: {
			id: router.currentRoute._value.params.id
		}
	});
	window.open(route.href, "_blank");
};
// 当前页展示的数据
const filteredOpinions = computed(() => box1Data.value);
// 处理标签点击（通过接口按标签过滤）
const handleTagClick = tag => {
	activeTag.value = tag;
	currentPage.value = 1;
	// 切换标签只在前端重算分页，并重置选中行
	activeItemIndex.value = 0;
	updatePageData();
};
const handleBillMoreClick = (bill) => {
	const billId = bill?.id;
	if (!billId) {
		return;
	}
	const route = router.resolve({
		path: "/billLayout/bill/introduction",
		query: { billId: String(billId) }
	});
	window.open(route.href, "_blank");
};
/** 政策建议关联法案：新标签页打开政令介绍页*/
const handleAdministrativeMoreClick = (ad) => {
	const id = ad?.bcId;
	if (!id) {
		return;
	}
	const route = router.resolve({
		path: "/decreeLayout/overview/introduction",
		query: { id: String(id) }
	});
	window.open(route.href, "_blank");
};
const handleSearchOpinions = () => {
	// 搜索时默认切回“全部”标签
	activeTag.value = "";
	currentPage.value = 1;
	activeItemIndex.value = 0;
	handleGetThinkTankReportPolicyAction();
};
// 高亮标题中与搜索关键词相同的文字
const highlightKeyword = text => {
	if (!text) return "";
	const keyword = (searchOpinions.value || "").trim();
	if (!keyword) return text;
	// 转义正则特殊字符
	const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
	const reg = new RegExp(escaped, "gi");
	return text.replace(reg, match => `<span class="highlight-keyword">${match}</span>`);
};
// 根据当前全量数据更新 tag 及数量
const updateTagsFromAllData = () => {
	const set = new Set();
	const map = {};
	allBox1Data.value.forEach(item => {
		(item.domains || []).forEach(d => {
			if (!d?.industryName) return;
			const name = d.industryName;
			set.add(name);
			map[name] = (map[name] || 0) + 1;
		});
	});
	allTags.value = Array.from(set);
	tagCountMap.value = map;
};

const handleGetThinkTankReportPolicyAction = async () => {
	try {
		const params = {
			reportId: router.currentRoute._value.params.id,
			// 这里请求全量数据，前端自行分页
			currentPage: 0,
			pageSize: 1000,
			keyword: (searchOpinions.value || "").trim(),
			// 仍将标签传给后端，若后端支持则为额外兜底过滤
			industryName: activeTag.value || undefined
		};
		const res = await getThinkTankReportPolicyAction(params);
		console.log("相关政策动态", res);
		// 每次请求先清空全量与当前页数据
		allBox1Data.value = [];
		box1Data.value = [];
		if (res && res.code === 200 && res.data && Array.isArray(res.data.content)) {
			const content = res.data.content;
			allBox1Data.value = content;
			console.log(allBox1Data.value, "allBox1Data");
			// 基于当前搜索结果更新 tag 和数量
			updateTagsFromAllData();
			// 拉取到全量后，根据当前筛选与页码更新本页数据，默认选中第一页第一条
			activeItemIndex.value = 0;
			updatePageData();
		} else {
			// 非 200 / 数据结构异常时，清空标签和数量
			allTags.value = [];
			tagCountMap.value = {};
			console.warn("相关政策动态接口返回非 200：", res && res.code);
		}
	} catch (error) {
		console.error("获取相关政策动态 error", error);
		allBox1Data.value = [];
		box1Data.value = [];
		allTags.value = [];
		tagCountMap.value = {};
	}
};
// 按当前标签与页码从全量数据中截取一页
const updatePageData = () => {
	const start = (currentPage.value - 1) * pageSize.value;
	const end = start + pageSize.value;
	let list = allBox1Data.value;
	if (activeTag.value) {
		list = list.filter(item =>
			(item.domains || []).some(d => d?.industryName === activeTag.value)
		);
	}
	const pageList = list.slice(start, end);
	box1Data.value = pageList;
	// 如当前页有数据且当前选中索引超出范围，则默认选中当前页第一条
	if (pageList.length > 0) {
		if (activeItemIndex.value < 0 || activeItemIndex.value >= pageList.length) {
			activeItemIndex.value = 0;
		}
		// 同步当前选中 item 数据
		box1DataItem.value = pageList[activeItemIndex.value];
		console.log("当前选中政策建议：", box1DataItem.value);
	} else {
		activeItemIndex.value = -1;
		box1DataItem.value = null;
	}
};
onMounted(async () => {
	handleGetThinkTankReportPolicyAction()
});
</script>

<style lang="scss" scoped>
.wrap {
	display: flex;
	justify-content: center;
	gap: 16px;
	height: 1573px;
	padding-bottom: 16px;

	.box1 {
		margin-top: 19px;
		width: 1600px;


		.box1-main {
			margin-top: 8px;
			min-height: 778px;
			padding-left: 21px;
			padding-right: 50px;
			padding-bottom: 21px;
			gap: 55px;
			display: flex;

			.left {
				width: 506px;
				gap: 12px;
				display: flex;
				flex-direction: column;

				.search-box {
					display: flex;
					width: 100%;
					height: 32px;
					box-sizing: border-box;
					border: 1px solid rgba(230, 231, 232, 1);
					border-radius: 4px;
					background: rgba(255, 255, 255, 1);
					position: relative;


					.icon {
						width: 16px;
						height: 16px;

						cursor: pointer;
						position: absolute;
						right: 8px;
						top: 8px;

						display: flex;
						justify-content: flex-end;

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

				.tag-box {
					width: 506px;
					gap: 8px;
					display: flex;
					height: 28px;



					.tag {
						height: 28px;

						border: 1px solid rgb(230, 231, 232);
						border-radius: 4px;

						padding: 0px 8px;
						display: flex;
						cursor: pointer;

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

							.tag-text {
								color: rgb(5, 95, 194);
							}
						}


						.tag-text {
							font-size: 16px;
							line-height: 28px;
							letter-spacing: 0px;
							text-align: left;
							font-family: "Source Han Sans CN";
							color: rgb(59, 65, 75);
							font-weight: 400;
							align-items: center;
							display: flex;
						}
					}
				}

				.item-box {
					width: 506px;
					min-height: 639.2px;
					border-top: 1px solid rgb(234, 236, 238);

					.item {
						width: 506px;
						display: flex;
						gap: 18px;
						padding-top: 16px;
						padding-left: 15px;
						padding-right: 22px;
						padding-bottom: 16px;
						border-bottom: 1px solid rgb(234, 236, 238);
						cursor: pointer;
						position: relative;

						&.item-active {
							background-color: rgb(246, 250, 255);
							border: 1px solid rgb(185, 220, 255);

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

						.item-left {
							margin-top: 3px;
							width: 24px;
							height: 27px;
							display: inline-flex;
							align-items: center;
							justify-content: center;
							border-radius: 50%;
							background: rgba(231, 243, 255, 1);
							color: var(--color-main-active);
							font-family: "Source Han Sans CN";
							font-size: 14px;
							font-weight: 400;
							letter-spacing: 0px;
							/* 关键：不要被 flex 压缩 */
							flex: 0 0 27px;
						}

						.item-right {
							flex: 1;
							width: auto;
							color: rgba(59, 65, 75, 1);
							font-family: "Source Han Sans CN";
							font-size: 16px;
							font-weight: 400;
							line-height: 30px;
							letter-spacing: 0px;
							text-align: left;
						}

						.item-right-solid {
							position: absolute;
							right: 0;
							top: 16px;
							bottom: 16px;
							width: 4px;
							background-color: rgb(5, 95, 194);
						}
					}
				}

				.box4-main-footer {
					display: flex;
					justify-content: space-between;
				}
			}

			.right {
				width: 968px;

				.right-header {
					height: 54px;
					width: 968px;
					display: flex;
					border-top: 1px solid rgb(234, 236, 238);
					border-bottom: 1px solid rgb(234, 236, 238);
					margin-bottom: 16px;

					.header-text {
						width: 968px;
						height: 24px;
						margin-top: 16px;
						justify-content: space-between;
						display: flex;

						.right-text {
							height: 24px;
							display: flex;

							.text {
								color: rgb(5, 95, 194);
								font-family: "Source Han Sans CN";
								font-weight: 400;
								/* Regular */
								font-size: 16px;
								line-height: 24px;
								letter-spacing: 0;
								text-align: justify;
								/* 两端对齐 */
							}

							.right-header-image {
								width: 12px;
								height: 12px;
								display: inline-block;

								margin-left: 6px;
								margin-top: 4.5px;

								img {
									width: 100%;
									height: 100%;
									object-fit: contain;
									/* 保证图片不变形 */


								}
							}
						}

						.left-text {
							height: 24px;
							color: rgb(59, 65, 75);
							font-family: "Source Han Sans CN";
							font-weight: 700;
							/* Bold 粗体 */
							font-size: 18px;
							line-height: 24px;
							letter-spacing: 0;
							text-align: left;
						}
					}
				}

				.right-content {
					font-family: "Source Han Sans CN";
					font-weight: 400;
					/* Regular */
					font-size: 16px;
					line-height: 30px;
					letter-spacing: 0;
					text-align: left;
					color: rgb(59, 65, 75);
					margin-bottom: 16px;
				}

				.info-group {
					width: 968px;
					height: 160px;
					border-top: 1px solid rgb(234, 236, 238);
					border-bottom: 1px solid rgb(234, 236, 238);


					.info-content {
						width: 968px;
						height: 128px;
						margin-top: 16px;
						display: flex;
						flex-direction: column;
						gap: 16px;

						.info-item {
							height: 32px;
							display: flex;
							align-items: center;
							justify-content: flex-start;

							.info-text {
								font-family: "Source Han Sans CN";
								font-weight: 400;
								font-size: 16px;
								line-height: 24px;
								letter-spacing: 0;
								text-align: justify;
							}

							.info-right {
								height: 24px;
								margin-left: 8px;
								display: flex;

								.tag-box {
									height: 24px;
									display: flex;
									flex-direction: row;
									flex-wrap: nowrap;
									gap: 8px;

									.tag {
										border-radius: 4px;
										height: 24px;
										background-color: rgb(231, 243, 255);
										padding: 1px 8px;
										font-family: "Source Han Sans CN", sans-serif;
										font-weight: 400;
										font-size: 14px;
										line-height: 22px;
										letter-spacing: 0;
										text-align: left;
										color: rgb(5, 95, 194);
									}
								}

								.info-right-image {
									height: 20px;
									width: 20px;
									margin-right: 4px;
									margin-top: 2px;

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

								.info-right-text {
									color: rgb(95, 101, 108);
									font-family: "Source Han Sans CN";
									font-weight: 400;
									font-size: 16px;
									line-height: 24px;
									letter-spacing: 0px;
									text-align: left;
								}
							}
						}
					}

				}

				.right-footer-title {
					width: 968px;
					height: 56px;
					border-bottom: 1px solid rgb(234, 236, 238);
					display: flex;

					.footer-title-text {
						height: 24px;
						margin-top: 16px;
						color: rgb(59, 65, 75);
						font-family: "Source Han Sans CN";
						font-weight: 700;
						font-size: 18px;
						line-height: 24px;
						letter-spacing: 0px;
						text-align: justify;
					}
				}

				.right-footer-box {
					width: 968px;
					gap: 13px;
					display: flex;
					flex-direction: column;

					.relatedBills {
						width: 968px;
						height: 48px;
						border: 1px solid rgb(231, 243, 255);
						background-color: rgb(246, 250, 255);
						padding: 11px 16px;
						display: flex;

						.tag {
							border-radius: 4px;
							height: 24px;
							background-color: rgb(231, 243, 255);
							padding: 1px 8px;
							font-family: "Source Han Sans CN", sans-serif;
							font-weight: 400;
							font-size: 14px;
							line-height: 22px;
							letter-spacing: 0;
							text-align: left;
							color: rgb(5, 95, 194);
							margin-right: 4px;
						}

						.relatedBills-content {
							height: 24px;
							margin-left: 8px;

							margin-left: 8px;
							font-family: "Source Han Sans CN", sans-serif;
							font-weight: 400;
							/* Regular 对应字重 */
							font-size: 16px;
							line-height: 24px;
							letter-spacing: 0;
							text-align: left;
							color: rgb(5, 95, 194);
						}

						.footer-image {
							margin-top: 2px;
							width: 20px;
							height: 20px;
							margin-left: auto;

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

					.relatedAdministrativeOrders {
						width: 968px;
						height: 48px;
						border: 1px solid rgb(231, 243, 255);
						background-color: rgb(246, 250, 255);
						padding: 11px 16px;
						display: flex;


						.relatedAdministrativeOrders-content {
							height: 24px;
							margin-left: 8px;
							font-family: "Source Han Sans CN", sans-serif;
							font-weight: 400;
							/* Regular 对应字重 */
							font-size: 16px;
							line-height: 24px;
							letter-spacing: 0;
							text-align: left;
							color: rgb(5, 95, 194);
						}

						.tag {
							border-radius: 4px;
							height: 24px;
							background-color: rgb(231, 243, 255);
							padding: 1px 8px;
							font-family: "Source Han Sans CN", sans-serif;
							font-weight: 400;
							font-size: 14px;
							line-height: 22px;
							letter-spacing: 0;
							text-align: left;
							color: rgb(5, 95, 194);
							margin-right: 4px;
						}

						.footer-image {
							margin-top: 2px;
							width: 20px;
							height: 20px;
							margin-left: auto;

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


	}


}

/* 搜索关键词高亮（v-html 渲染，需要 :deep 才能作用到插入的 DOM） */
:deep(.highlight-keyword) {
	background-color: #fff3b0;
}

:deep(.analysis-box-wrapper .wrapper-header) {
	height: 54px !important;
	display: flex;
	align-items: center;

	.header-title>div {
		line-height: 54px;
	}
}
</style>