<template>
	<div class="wrap">
		<div class="main-header">
			<div class="search-box">

				<el-input placeholder="搜索智库动态" v-model="searchReport" style="width: 270px"
					@keyup.enter="handleGetThinkDynamicsReport()" />
				<div class="icon">
					<img src="./images/search-icon.png" alt="" @click="handleGetThinkDynamicsReport()" />
				</div>
			</div>
			<div class="report-btn-group">
				<div class="report-btn" v-for="type in choseTypeList" :key="type.id"
					:class="{ active: activeTypeId === type.id }" @click="handleChooseType(type)">
					<div class="text"> {{ type.name }}</div>
				</div>
			</div>
			<div>
				<div class="select-box">

					<div class="select-box-sort">
						<el-select v-model="sort" placeholder="发布时间" style="width: 120px" :teleported="true"
							:placement="'bottom-start'" :popper-options="{
								modifiers: [
									{
										name: 'preventOverflow', // 禁用自动翻转逻辑
										options: {
											mainAxis: false, // 禁用垂直方向的自动调整
											altAxis: false, // 禁用水平方向的自动调整
										}
									},
									{
										name: 'flip', // 完全禁用翻转功能
										enabled: false
									}
								]
							}">
							<template #prefix>
								<img v-if="sort !== true" src="./images/image down.png" class="select-prefix-img" alt=""
									@click.stop="toggleSortAndFetch()" />
								<img v-else src="./images/image up.png" class="select-prefix-img" alt=""
									@click.stop="toggleSortAndFetch()" />
							</template>
							<el-option :key="'think-dynamics-sort-asc'" label="正序" :value="true"
								@click="handleGetThinkDynamicsReport()" />
							<el-option :key="'think-dynamics-sort-desc'" label="倒序" :value="false"
								@click="handleGetThinkDynamicsReport()" />
						</el-select>
					</div>
				</div>
			</div>
		</div>
		<ThinkTankReport v-if="isThinkTankReport" :research-type-list="researchTypeList"
			:research-time-list="researchTimeList" :key="`智库报告-${tabResetKey}`" :selected-filters="selectedFilters"
			:cur-footer-list="curFooterList" :total="total" :current-page="currentPage" :search-keyword="searchReport"
			@update:selected-filters="handleSelectedFiltersUpdate"
			@filter-change="(payload) => handleGetThinkDynamicsReport(payload)" @page-change="handleCurrentChange"
			@report-click="handleToReportDetail" />
		<CongressHearing v-else-if="isCongressHearing" :research-type-list="researchTypeList"
			:research-time-list="researchTimeList" :key="`国会听证会-${tabResetKey}`" :research-hearing-list="researchHearingList"
			:selected-filters="selectedFilters" :selected-year="selectedYear" :total="total" :current-page="currentPage"
			:search-keyword="searchReport" :hearing-data="hearingData" @update:selected-filters="handleSelectedFiltersUpdate"
			@filter-change="(payload) => handleGetThinkDynamicsReport(payload)" @page-change="handleCurrentChange"
			@report-click="handleToHearingDetail" />
		<SurveyForm v-else-if="isSurveyForm" :research-type-list="researchTypeList" :research-time-list="researchTimeList"
			:key="`调查项目-${tabResetKey}`" :selected-filters="selectedFilters" :cur-footer-list="curFooterProjectList"
			:total="total" :current-page="currentPage" :search-keyword="searchReport"
			@update:selected-filters="handleSelectedFiltersUpdate"
			@filter-change="(payload) => handleGetThinkDynamicsReport(payload)" @page-change="handleCurrentChange"
			@report-click="handleToProjectDetail" />
	</div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import SurveyForm from "./SurveyForm/index.vue"
// import Img1 from "./images/img1.png";
// import Img2 from "./images/img2.png";
// import Img3 from "./images/img3.png";
// import Img4 from "./images/img4.png";
// import Img5 from "./images/img5.png";
// import Img6 from "./images/img6.png";
// import Img7 from "./images/img7.png";
// import Img8 from "./images/img8.png";
// import Img9 from "./images/img9.png";
// import Img10 from "./images/img10.png";
// import Img11 from "./images/img11.png";
// import Img12 from "./images/img12.png";
//getThinkDynamicsReport
import {
	getThinkDynamicsReportType,
	getHylyList,
	getThinkTankReport,
	getThinkTankProjectsByThinkTankId,
	getThinkTankTestimoniesByThinkTankId
} from "@/api/thinkTank/overview";
import {
	RESOURCE_FILTER_EARLIER,
	stripAllTimeForRequest,
	isSelectionCoveringAllOptions,
	getResourceLibraryReportDateRangeFromTimeSelection
} from "../../utils/resourceLibraryFilters";
import { useRouter } from "vue-router";
import ThinkTankReport from "./ThinkTankReport/index.vue";
import CongressHearing from "./CongressHearing/index.vue";
const router = useRouter();
const isThinkTankReport = ref(true);
const isSurveyForm = ref(false);
const isCongressHearing = ref(false);
const searchReport = ref('')

const handleToReportDetail = (item) => {
	window.sessionStorage.setItem('curTabName', item.name)
	const route = router.resolve({
		name: 'ReportDetail',
		params: {
			id: item.id
		}
	});
	window.open(route.href, "_blank");

}
const handleToHearingDetail = item => {
	const id = item?.id;
	if (!id) return;
	window.sessionStorage.setItem('curTabName', item?.title || item?.name || "");

	const route = router.resolve({
		name: "CongressHearingView",
		params: {
			id
		}
	});
	window.open(route.href, "_blank");
};
const handleToProjectDetail = (item) => {
	window.sessionStorage.setItem('curTabName', item.name)
	const route = router.resolve({
		name: 'SurveyProjectView',
		params: {
			id: item.id
		}
	});
	window.open(route.href, "_blank");

}
const hearingData = ref([


])
const reportTypeList = ref([
	{
		id: '研究报告',
		name: '研究报告',
	},
	{
		id: '简报',
		name: '简报',
	},
	{
		id: '会议记录',
		name: '会议记录',
	},
	{
		id: '期刊文章',
		name: '期刊文章',
	},
])
const selectedReportTypeList = ref([])

const researchTypeList = ref([
	{
		id: '研究报告',
		name: '研究报告',
	},
	{
		id: '简报',
		name: '简报',
	},
	{
		id: '会议记录',
		name: '会议记录',
	},
	{
		id: '期刊文章',
		name: '期刊文章',
	},
])
const choseTypeList = ref([
	{
		id: '智库报告',
		name: '智库报告',
	},
	{
		id: '调查项目',
		name: '调查项目',
	},
	{
		id: '国会听证会',
		name: '国会听证会',
	},

])
const activeTypeId = ref(choseTypeList.value[0]?.id || null)
const tabResetKey = ref(0)

const createDefaultSelectedFilters = () => ({
	researchTypeIds: [],
	researchTimeIds: [],
	researchHearingIds: []
})

const resetThinkDynamicsState = () => {
	searchReport.value = ''
	selectedYear.value = 1
	sort.value = null
	author.value = ''
	currentPage.value = 1
	selectedFilters.value = createDefaultSelectedFilters()
	curFooterList.value = []
	curFooterProjectList.value = []
	hearingData.value = []
	total.value = 0
	tabResetKey.value += 1
}

const handleChooseType = async (type) => {
	if (activeTypeId.value === type.id) {
		return
	}
	activeTypeId.value = type.id
	if (type.id === '国会听证会') {
		isThinkTankReport.value = false
		isCongressHearing.value = true
		isSurveyForm.value = false
	} else if (type.id === "智库报告") {
		isThinkTankReport.value = true
		isCongressHearing.value = false
		isSurveyForm.value = false
	} else {
		isThinkTankReport.value = false
		isCongressHearing.value = false
		isSurveyForm.value = true
	}
	// 等当前 tick 完成卸载/挂载后再重置 key 与拉数，避免 patch 阶段子组件 vnode 为 null（emitsOptions 报错）
	await nextTick()
	resetThinkDynamicsState()
	await handleGetThinkDynamicsReport()
}
const researchTimeList = ref([
	{
		id: '2025年',
		name: '2025年',
	},
	{
		id: '2024年',
		name: '2024年',
	},
	{
		id: '2023年',
		name: '2023年',
	},
	{
		id: '2022年',
		name: '2022年',
	},
	{
		id: '2021年',
		name: '2021年',
	},
	{
		id: RESOURCE_FILTER_EARLIER,
		name: RESOURCE_FILTER_EARLIER,
	}
])
const researchHearingList = ref([

])
const selectedFilters = ref(createDefaultSelectedFilters())

const handleSelectedFiltersUpdate = val => {
	selectedFilters.value = val
}

const author = ref('')  // 作者

/** 智库报告  */
const curFooterList = ref([]);
const curFooterProjectList = ref([]);


const selectedYear = ref(1);
/** null：界面显示「发布时间」占位且默认按发布时间倒序；true 正序；false 倒序（显式选中），与政策追踪一致 */
const sort = ref(null);
//获取智库研究类型
const handleGetThinkDynamicsReportType = async () => {
	try {
		const res = await getThinkDynamicsReportType();
		console.log("智库研究类型信息", res);
		if (res.code === 200 && res.data) {
			reportTypeList.value = res.data
		}
	} catch (error) {
		console.error("获取研究类型error", error);
	}
};


//获取行业领域字典
// getHylyList
const handleGetHylyList = async () => {
	try {
		const res = await getHylyList();
		console.log("行业领域字典", res);
		if (res.code === 200 && res.data) {
			researchTypeList.value = res.data;
		}
	} catch (error) {
		console.error("获取行业领域字典error", error);
	}
};

const toggleSortAndFetch = async () => {
	sort.value = sort.value === true ? false : true;
	await handleGetThinkDynamicsReport();
};
const currentPage = ref(1);
// 处理页码改变事件
const handleCurrentChange = page => {
	currentPage.value = page;
	handleGetThinkDynamicsReport()
};

function arrayToString(arr) {
	return arr.reduce((acc, item) => {
		if (item !== null && item !== undefined && item !== "") {
			return acc === "" ? item : acc + "," + item;
		}
		return acc;
	}, "");
}

/** 国会听证会列表筛选用「xxxx年x月x日」格式 */
const formatHearingTimeForFilter = (value) => {
	if (value === null || value === undefined || value === "") return "";
	const s = String(value).trim();
	if (/年/.test(s)) return s;
	const d = new Date(s);
	if (!Number.isNaN(d.getTime())) {
		return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
	}
	return s;
};

/** 后端证词/听证会条目 → CongressHearing 组件所需字段（与 /think-tank/{id}/testimonies 返回对齐） */
const mapTestimonyToHearingItem = (raw, index) => {
	const item = raw || {};
	const title = item.titleZh || item.title || item.hearingTitle || item.name || "";
	return {
		id: item.id ?? item.testimonyId ?? `hearing-${index}`,
		name: title,
		title,
		coverImgUrl: item.coverImgUrl || "",
		thinkTankLogoUrl: item.thinkTankLogoUrl || "",
		time: formatHearingTimeForFilter(
			item.testimonyDate || item.hearingDate || item.date || item.startDate || item.publishTime
		),
		content:
			item.committeeZh ||
			item.committee ||
			item.organization ||
			item.summaryZh ||
			item.summary ||
			item.subtitle ||
			"",
		category: item.category || item.domains || item.area || item.field || ""
	};
};

// 获取智库动态报告，payload 为子组件筛选变更时传入的当前选中值，避免时序导致拿到旧值
const handleGetThinkDynamicsReport = async (payload) => {
	const nextFilters = payload && typeof payload === "object"
		? {
			researchTypeIds: payload.researchTypeIds ? [...payload.researchTypeIds] : [],
			researchTimeIds: payload.researchTimeIds ? [...payload.researchTimeIds] : [],
			researchHearingIds: payload.researchHearingIds ? [...payload.researchHearingIds] : []
		}
		: selectedFilters.value;
	if (payload && typeof payload === "object") {
		selectedFilters.value = nextFilters;
		currentPage.value = 1;
	}

	if (!isThinkTankReport.value && !isSurveyForm.value && !isCongressHearing.value) {
		return;
	}
	try {
		const strippedTime = stripAllTimeForRequest(nextFilters.researchTimeIds || []);
		const allTimeIds = (researchTimeList.value || []).map((x) => x.id);
		const { startDate, endDate } = getResourceLibraryReportDateRangeFromTimeSelection(
			strippedTime,
			allTimeIds
		);
		const areas = nextFilters.researchTypeIds || [];
		const allAreaIds = (researchTypeList.value || []).map((a) => a.id);
		const domainIds = isSelectionCoveringAllOptions(areas, allAreaIds)
			? ""
			: arrayToString(areas);
		const keyword = (searchReport.value || "").trim();
		const thinkTankId = router.currentRoute._value.params?.id;
		if (isCongressHearing.value) {
			curFooterList.value = [];
			curFooterProjectList.value = [];
			const res = await getThinkTankTestimoniesByThinkTankId({
				thinkTankId,
				pageNum: Math.max(0, (currentPage.value || 1)),
				pageSize: 10,

				domainIds,
				startDate,
				endDate,
				title: keyword || undefined
			});
			if (res.code === 200 && res.data) {
				const list = Array.isArray(res.data.content) ? res.data.content : Array.isArray(res.data) ? res.data : [];
				hearingData.value = list.map((row, idx) => mapTestimonyToHearingItem(row, idx));
				total.value = res.data.totalElements ?? hearingData.value.length;
			} else {
				hearingData.value = [];
				total.value = 0;
			}
			return;
		}
		if (isSurveyForm.value) {
			// 调查项目：用新接口 /think-tank/{thinkTankId}/projects
			curFooterList.value = [];
			const res = await getThinkTankProjectsByThinkTankId({
				thinkTankId,
				pageNum: currentPage.value,
				pageSize: 12,
				sortFun: sort.value === true,
				sortField: "startDate",
				sortOrder: sort.value === true ? "asc" : "desc",
				domainIds,
				startDate,
				endDate,
				projectName: keyword || undefined
			});
			if (res.code === 200 && res.data) {
				curFooterProjectList.value = res.data.content || [];
				total.value = res.data.totalElements || 0;
			} else {
				curFooterProjectList.value = [];
				total.value = 0;
			}
			return;
		}

		// 智库报告：保持原逻辑
		const params = {
			pageNum: currentPage.value,
			pageSize: 12,
			sortFun: sort.value === true,
			domainIds,
			startDate,
			endDate
		};
		if (thinkTankId) {
			params.thinkTankId = thinkTankId;
		}
		if (keyword) {
			params.keyword = keyword;
		}
		const res = await getThinkTankReport(params);
		if (res.code === 200 && res.data) {
			curFooterList.value = res.data.content;
			total.value = res.data.totalElements;
		} else {
			curFooterList.value = [];
			total.value = 0;
		}
	} catch (error) {
		console.error("获取智库动态报告error", error);
	}
};

const total = ref(0)
onMounted(async () => {
	handleGetThinkDynamicsReportType()
	handleGetHylyList()
	handleGetThinkDynamicsReport()
});

</script>

<style lang="scss" scoped>
.main-header {

	width: 1600px;
	margin-bottom: 16px;
	display: flex;
	align-items: center;
	background: rgb(255, 255, 255);

	// 让右侧下拉框整体靠右
	>div:last-child {
		margin-left: auto;
		display: flex;
		align-items: center;
	}

	.report-btn-group {
		width: 384px;
		height: 32px;

		/* 定位参数：top:268px、left:536px（需基于定位父容器） */


		/* 布局分布：集中分布（水平+垂直居中） */
		display: flex;
		margin-top: 16px;
		margin-left: 16px;

		/* 图层模式：穿透（事件+视觉穿透） */

		background: rgb(255, 255, 255); // 与整体背景一致的纯白色

		/* 基础兼容：避免尺寸偏移 */
		box-sizing: border-box;
		gap: 12px;


		.report-btn {
			width: 120px; // 宽度：120px
			height: 32px; // 高度：32px

			border-radius: 21px; // 圆角半径：21px
			border: 1px solid rgb(230, 231, 232); // 描边：1px实线，颜色为rgb(230, 231, 232)
			background: rgb(255, 255, 255); // 背景色：白色

			box-shadow: 0px 0px 20px 0px rgba(94, 95, 95, 0.1);
			// 布局分布：集中分布（水平+垂直居中）
			display: flex;
			align-items: center;
			justify-content: center;
			// 文字样式（匹配你项目的字体风格）
			color: rgba(59, 65, 75, 1); // 适配你项目的文字主色
			font-family: 'Source Han Sans CN';
			font-size: 16px;
			font-weight: 400;
			line-height: 1; // 消除行高对垂直居中的影响
			// 图层模式：穿透（即允许点击事件穿透，如需的话）

			box-sizing: border-box; // 确保描边/内边距不影响尺寸
			cursor: pointer; // 鼠标悬停时显示为可点击

			&.active {
				background: rgb(5, 95, 194); // 蓝色背景
				color: #fff; // 文字变白
				box-shadow: none; // 需要的话可以关掉灰描边
			}
		}
	}

	.search-box {
		margin-top: 16px;
		display: flex;
		width: 360px;
		height: 32px;
		box-sizing: border-box;
		border: 1px solid rgb(230, 231, 232);
		border-radius: 4px;
		background: rgb(255, 255, 255);
		box-shadow: 0px 0px 20px 0px rgba(94, 95, 95, 0.1);


		.icon {
			width: 16px;
			height: 16px;
			margin-top: 8px;
			margin-bottom: 8px;
			margin-left: 50px;
			cursor: pointer;

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

	.select-box {
		margin-top: 16px;
		display: flex;

		.select-box-time,
		.select-box-sort {
			background: rgb(255, 255, 255);
			box-shadow: 0px 0px 20px 0px rgba(94, 95, 95, 0.1);
			border: 1px solid rgb(230, 231, 232);
			border-radius: 4px;
			height: 32px;
		}

		.select-prefix-img {
			width: 8px;
			height: 8px;
			margin-right: 4px;
		}

		:deep(.el-select-dropdown) {
			left: 0 !important;
			/* 强制下拉框左对齐选择框 */
			top: 100% !important;
			/* 强制下拉框在选择框正下方 */
			transform: none !important;
			/* 禁用默认的位移变换 */
		}
	}
}

.main-content {
	width: 1600px;
	display: flex;
	gap: 16px;

	.left {
		width: 360px;
		height: 541px;
		padding-bottom: 36px;
		box-sizing: border-box;
		border: 1px solid rgba(234, 236, 238, 1);
		border-radius: 10px;
		box-shadow: 0px 0px 20px 0px rgba(94, 95, 95, 0.1);
		background: rgba(255, 255, 255, 1);
		position: relative;


	}

	.right {
		width: 1284px;
		height: 1377px;

		.card-box {
			width: 1226px;
			height: 1248px;
			display: flex;
			justify-content: space-around;
			flex-wrap: wrap;

			.footer-card {
				width: 398px;
				height: 300px;
				border-radius: 10px;
				box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
				background: rgba(255, 255, 255, 1);
				transition: transform 0.3s ease, box-shadow 0.3s ease;

				&:hover {
					transform: translateY(-3px);
					box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
				}

				cursor: pointer;

				.footer-card-top {
					width: 364px;
					height: 206px;
					margin: 0 auto;
					margin-top: 15px;

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

				.footer-card-title {
					margin: 0 auto;
					margin-top: 13px;
					width: 376px;
					height: 24px;
					color: rgba(59, 65, 75, 1);
					font-family: Microsoft YaHei;
					font-size: 18px;
					font-weight: 700;
					line-height: 24px;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.footer-card-footer {
					margin: 0 auto;
					margin-top: 5px;
					width: 376px;
					height: 22px;
					display: flex;
					justify-content: space-between;
					color: rgba(95, 101, 108, 1);
					font-family: Microsoft YaHei;
					font-size: 14px;
					font-weight: 400;
					line-height: 22px;
				}
			}
		}

		.right-footer {
			margin-top: 43px;
			display: flex;
			justify-content: space-between;

			.info {
				height: 19px;
				color: rgba(132, 136, 142, 1);
				font-family: Microsoft YaHei;
				font-size: 14px;
				font-weight: 400;
				line-height: 18px;
				letter-spacing: 0px;
				text-align: left;
			}
		}
	}
}

.filter-checkbox {
	width: 180px;

}


.page {
	width: 1600px;
	height: 40px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin: 36px 0 0 0;
	padding-left: 11px;

	.count {
		color: rgba(59, 65, 75, 1);

		font-family: Microsoft YaHei;
		font-size: 16px;
		font-weight: 400;
		line-height: 24px;
		letter-spacing: 0px;
		text-align: left;
	}

}
</style>