<template>
	<div class="reslib-page">
		<div class="nav">
			<div class="nav-item" :class="{ active: isAllProjectsActive }" @click="handleNavSelect(null)">
				{{ "全部资助项目" }}
			</div>
			<div v-for="item in navList" :key="item.orgId" class="nav-item" :class="{ active: item.orgId === activeItem }"
				@click="handleNavSelect(item.orgId)">
				{{ item.orgName }}
			</div>

		</div>
		<div class="reslib-sort-box">
			<div class="select-box">
				<el-select v-model="sortModel" class="resource-library-sort-select" placeholder="发布时间" style="width: 120px"
					:teleported="true" placement="bottom-start" :popper-options="resourceLibrarySortPopperOptions"
					@change="handleResourceLibrarySortChange" popper-class="datasub-select-popper">
					<template #prefix>
						<img v-if="sortModel !== true" src="@/views/thinkTank/ThinkTankDetail/thinkDynamics/images/image down.png"
							class="resource-library-sort-prefix-img" alt="" @click.stop="toggleResourceLibrarySortPrefix" />
						<img v-else src="@/views/thinkTank/ThinkTankDetail/thinkDynamics/images/image up.png"
							class="resource-library-sort-prefix-img" alt="" @click.stop="toggleResourceLibrarySortPrefix" />
					</template>
					<el-option :key="'reslib-sort-asc'" label="正序" :value="true" />
					<el-option :key="'reslib-sort-desc'" label="倒序" :value="false" />
				</el-select>
			</div>
		</div>
		<div class="main">
			<div class="left">
				<div class="select-box">
					<div class="header">
						<div class="icon"></div>
						<div class="title">科技领域</div>
					</div>
					<div class="select-main">
						<el-checkbox-group class="checkbox-group" :model-value="selectedAreaListModel"
							@change="handleAreaGroupChange">
							<el-checkbox class="filter-checkbox all-checkbox" :label="RESOURCE_FILTER_ALL_AREA">
								{{ RESOURCE_FILTER_ALL_AREA }}
							</el-checkbox>
							<el-checkbox v-for="research in areaList" :key="research.id" class="filter-checkbox" :label="research.id">
								{{ research.name }}
							</el-checkbox>
						</el-checkbox-group>
					</div>
				</div>
				<div class="select-box">
					<div class="header">
						<div class="icon"></div>
						<div class="title">发布时间</div>
					</div>
					<div class="select-main">
						<el-checkbox-group class="checkbox-group" :model-value="selectedPubTimeListModel"
							@change="handleTimeGroupChange">
							<el-checkbox class="filter-checkbox all-checkbox" :label="RESOURCE_FILTER_ALL_TIME">
								{{ RESOURCE_FILTER_ALL_TIME }}
							</el-checkbox>
							<el-checkbox v-for="time in pubTimeList" :key="time.id" class="filter-checkbox" :label="time.id">
								{{ time.name }}
							</el-checkbox>
						</el-checkbox-group>
					</div>
				</div>
			</div>
			<div class="right">
				<div class="right-title">
					<img src="./assets/icon01.png" alt="" />
					<div>资助项目</div>
				</div>
				<div class="right-main">
					<div v-for="(item, i) in mainList" :key="item.id" class="right-item">
						<img :src="item.logoUrl" alt="" />
						<div class="right-item-title">{{ item.projectName }}</div>
						<div class="right-item-content">{{ item.abstractContent }}</div>
						<div class="right-item-pie">

							<AreaTag v-for="(val, idx) in item.areaList" :key="idx" :tagName="val" />
						</div>
						<div class="right-item-time">{{ formatDate(item.publicationDate) }}</div>
						<div class="right-item-money"
							:style="{ color: item.amount <= 1000 ? 'rgba(232, 189, 11, 1)' : item.amount <= 10000 ? 'rgba(255, 149, 77, 1)' : 'rgba(206, 79, 81, 1)' }">
							{{ '$' + item.amount + '万' }}</div>
					</div>
					<div class="page">
						<div class="count">共 {{ total }} 项</div>
						<el-pagination v-model:current-page="currentPage" :page-size="pageSize" :total="total"
							layout="prev, pager, next" background @current-change="handlePageChange" />
					</div>

				</div>

			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import {
	getProjectListNew, geFundSourceOrg, getAreaType
} from "@/api/scientificFunding/overview";
import {
	RESOURCE_FILTER_ALL_AREA,
	RESOURCE_FILTER_ALL_TIME,
	RESOURCE_FILTER_EARLIER,
	normalizeExclusiveAllOption,
	stripAllAreaForRequest,
	stripAllTimeForRequest,
	isSelectionCoveringAllOptions,
	expandEarlierNumericYears
} from "@/views/thinkTank/utils/resourceLibraryFilters";

/** 领域字典与接口 arealist 使用数字 id（1、2、3…） */
const normalizeAreaId = (id) => {
	const n = Number(id);
	return Number.isFinite(n) ? n : id;
};
const formatDate = (dateStr) => {
	if (!dateStr) return '';
	const [y, m, d] = dateStr.split('-');
	return `${y}年${m}月${d}日`;
};
/** 请求用：仅保留合法整数领域 id */
const toAreaIdListForRequest = (ids) => {
	const list = Array.isArray(ids) ? ids : [];
	return list
		.map((id) => normalizeAreaId(id))
		.filter((id) => typeof id === "number" && Number.isInteger(id));
};

const navList = ref([]);
/** null 表示「全部资助项目」，不传 orgId */
const activeItem = ref(null);
const isAllProjectsActive = computed(() => activeItem.value === null);

const areaList = ref([]);


// 来源机构列表
const handleGeFundSourceOrg = async () => {
	try {
		const res = await geFundSourceOrg();
		console.log("来源机构列表", res);
		if (res.code === 200 && res.data) {
			navList.value = res.data;
		}
	} catch (error) {
		console.error("获取来源机构列表error", error);
	}
};

const selectedAreaListModel = ref([RESOURCE_FILTER_ALL_AREA]);
const selectedPubTimeListModel = ref([RESOURCE_FILTER_ALL_TIME]);

const handleAreaGroupChange = (val) => {
	selectedAreaListModel.value = normalizeExclusiveAllOption(val, RESOURCE_FILTER_ALL_AREA).map((item) =>
		item === RESOURCE_FILTER_ALL_AREA ? item : normalizeAreaId(item)
	);
	handleGetProjectListNew();
};

const handleTimeGroupChange = (val) => {
	selectedPubTimeListModel.value = normalizeExclusiveAllOption(val, RESOURCE_FILTER_ALL_TIME);
	handleGetProjectListNew();
};

const pubTimeList = ref([
	{
		id: 2026,
		name: "2026年"
	},
	{
		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
	}
]);

/** 选择「全部时间」时，yearlist 传 2000～2026 逐年 */
const YEAR_ALL_RANGE_START = 2000;
const YEAR_ALL_RANGE_END = 2026;

const buildYearlistForRequest = (selectedTimeModel) => {
	const strippedTime = stripAllTimeForRequest(selectedTimeModel);
	// 仅勾选「全部时间」、未选具体年份时，传 2000～2026 逐年
	if (strippedTime.length === 0) {
		const out = [];
		for (let y = YEAR_ALL_RANGE_START; y <= YEAR_ALL_RANGE_END; y += 1) {
			out.push(String(y));
		}
		return out;
	}

	const hasEarlier = strippedTime.includes(RESOURCE_FILTER_EARLIER);
	const numericOnly = strippedTime.filter((id) => id !== RESOURCE_FILTER_EARLIER);
	const strippedNums = numericOnly
		.map((id) => Number(id))
		.filter((n) => Number.isInteger(n));

	// 勾选「更早」：展开为 2000～2020，并与已选数字年合并（可与其他年份同时选）
	if (hasEarlier) {
		const yearsSet = new Set(expandEarlierNumericYears());
		strippedNums.forEach((n) => yearsSet.add(n));
		return [...yearsSet]
			.sort((a, b) => a - b)
			.map((n) => String(n));
	}

	return strippedNums.map((n) => String(n));
};

/** null：占位「发布时间」且默认倒序；true 正序；false 倒序（与智库概览资源库一致） */
const sortModel = ref(null);

const resourceLibrarySortPopperOptions = {
	modifiers: [
		{ name: "preventOverflow", options: { mainAxis: false, altAxis: false } },
		{ name: "flip", enabled: false }
	]
};

const handleResourceLibrarySortChange = () => {
	handleGetProjectListNew();
};

const toggleResourceLibrarySortPrefix = () => {
	sortModel.value = sortModel.value === true ? false : true;
	handleGetProjectListNew();
};

// 获取行业领域列表
const handleGetAreaType = async () => {
	try {
		const res = await getAreaType();
		console.log("获取行业领域列表", res);
		if (res.code === 200 && res.data) {
			areaList.value = res.data.map((row) => ({
				...row,
				id: normalizeAreaId(row.id)
			}));
		}
	} catch (error) {
		console.error("获取行业领域列表error", error);
	}
};

const mainList = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const handlePageChange = p => {
	currentPage.value = p;
	handleGetProjectListNew()
};

const handleNavSelect = (orgId) => {
	activeItem.value = orgId;
	handleGetProjectListNew();
};

// 资助体系v2.0:资助项目列表分页
const handleGetProjectListNew = async () => {
	try {
		const strippedArea = toAreaIdListForRequest(
			stripAllAreaForRequest(selectedAreaListModel.value)
		);
		const allAreaIds = toAreaIdListForRequest(areaList.value.map((obj) => obj.id));
		const arealist =
			strippedArea.length === 0 || isSelectionCoveringAllOptions(strippedArea, allAreaIds)
				? allAreaIds
				: strippedArea;

		const yearlist = buildYearlistForRequest(selectedPubTimeListModel.value);

		const params = {
			arealist,
			currentPage: currentPage.value,
			pageSize: 10,
			yearlist,
			funSort: sortModel.value === true ? 'asc' : 'desc'
		};
		if (activeItem.value != null) {
			params.orgId = activeItem.value;
		}
		const res = await getProjectListNew(params);
		console.log("资助项目列表分页", res);
		if (res.code === 200 && res.data) {
			mainList.value = res.data.content
			total.value = res.data.totalElements
		}
	} catch (error) {
		console.error("获取资助项目列表分页error", error);
	}
};

onMounted(async () => {
	await handleGeFundSourceOrg()
	await handleGetAreaType()
	handleGetProjectListNew()
});

</script>

<style scoped lang="scss">
* {
	margin: 0;
	padding: 0;
}
:global(.datasub-select-popper .el-select-dropdown__item) {
	padding-left: 20px;
}
.reslib-page {
	width: 1600px;

	position: relative;

	.reslib-sort-box {
		position: absolute;
		top: 7px;
		right: 0px;

		.select-box {
			height: 42px;
			box-sizing: border-box;
			padding: 5px 0;

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

				.resource-library-sort-prefix-img {
					width: 8px;
					height: 8px;
					margin-right: 4px;
					cursor: pointer;
				}

				:deep(.el-select__wrapper) {
					min-height: 30px;
					box-shadow: none;
				}

				:deep(.el-select-dropdown) {
					left: 0 !important;
					top: 100% !important;
					transform: none !important;
				}
			}
		}
	}

	.nav {

		height: 42px;
		display: flex;
		align-items: center;

		margin-bottom: 34px;

		.nav-item {

			text-align: center;
			cursor: pointer;
			padding: 8px 20px;
			font-size: 20px;
			font-weight: 400;
			font-family: "Microsoft YaHei";
			line-height: 26px;
			color: rgb(59, 65, 75);
		}

		.active {
			background-color: rgb(5, 95, 194);
			border-radius: 21px;
			color: #fff;
			font-weight: 700;
		}
	}

	.main {
		width: 1600px;

		display: flex;
		margin-bottom: 100px;

		.left {
			width: 360px;
			margin-right: 16px;
			height: 100%;
			padding-bottom: 24px;
			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;

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

				.header {
					display: flex;
					gap: 17px;

					.icon {
						margin-top: 4px;
						width: 8px;
						height: 16px;
						background: var(--color-main-active);
						border-radius: 0 4px 4px 0;
					}

					.title {
						height: 24px;
						color: var(--color-main-active);
						font-family: "Source Han Sans CN";
						font-size: 16px;
						font-weight: 700;
						line-height: 24px;
						letter-spacing: 1px;
						text-align: left;
					}
				}

				.select-main {
					margin-left: 24px;
					margin-top: 12px;

					.checkbox-group {
						display: grid;
						grid-template-columns: repeat(2, 160px);
						gap: 8px 4px;

						:deep(.all-checkbox) {
							width: 160px;
							height: 24px;
							margin: 0;
						}

						:deep(.filter-checkbox) {
							width: 160px;
							height: 24px;
							margin-right: 0 !important;
						}

						:deep(.el-checkbox__label) {
							font-size: 16px;
						}
					}
				}
			}
		}

		.right {
			width: 1224px;

			border-radius: 10px;
			background-color: #fff;
			box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);

			.right-title {
				width: 1224px;
				height: 48px;
				border-bottom: 1px solid rgb(235, 238, 242);
				position: relative;

				img {
					width: 22px;
					height: 19px;
					position: absolute;
					top: 15px;
					left: 20px;
				}

				div {
					width: 120px;
					height: 48px;
					margin-left: 60px;
					font-size: 20px;
					font-weight: 700;
					font-family: "Microsoft YaHei";
					line-height: 26px;
					color: rgb(5, 95, 194);
					padding: 11px 0;
				}
			}

			.right-main {
				width: 1224px;

				padding: 19px 34px 20px 29px;
				position: relative;

				.right-item {
					width: 1161px;
					height: 124px;
					border-bottom: 1px solid rgb(234, 236, 238);
					margin-bottom: 8px;
					position: relative;

					img {
						width: 32px;
						height: 32px;
						position: absolute;
						top: 9px;
						left: 7px;
					}

					.right-item-title {
						position: absolute;
						top: 10px;
						left: 56px;
						font-size: 20px;
						font-weight: 700;
						font-family: "Microsoft YaHei";
						line-height: 26px;
						color: rgb(59, 65, 75);
					}

					.right-item-content {
						white-space: nowrap;
						/* 保持在一行内 */
						overflow: hidden;
						/* 隐藏超出部分 */
						text-overflow: ellipsis;
						/* 超出部分显示省略号 */
						width: 992px;
						/* 设置一个固定的宽度或百分比 */
						position: absolute;
						top: 44px;
						left: 56px;
						font-size: 16px;
						font-weight: 400;
						font-family: "Microsoft YaHei";
						line-height: 24px;
						color: rgb(95, 101, 108);
					}

					.right-item-pie {
						position: absolute;
						top: 76px;
						left: 56px;
						display: flex;
						gap: 8px;

						.right-item-pie-item {
							padding: 2px 8px;
							border-radius: 4px;
							margin-right: 8px;
							border: 1px solid;
							font-size: 14px;
							font-weight: 400;
							font-family: "Microsoft YaHei";
							line-height: 20px;
						}

						.cl1 {
							background-color: rgba(230, 255, 251, 1);
							border-color: rgba(135, 232, 222, 1);
							color: rgba(19, 168, 168, 1);
						}

						.cl2 {
							background-color: rgba(255, 241, 240, 1);
							border-color: rgba(255, 163, 158, 1);
							color: rgba(245, 34, 45, 1);
						}

						.cl3 {
							background-color: rgba(249, 240, 255, 1);
							border-color: rgba(211, 173, 247, 1);
							color: rgba(114, 46, 209, 1);
						}

						.cl4 {
							background-color: rgba(230, 255, 251, 1);
							border-color: rgba(135, 232, 222, 1);
							color: rgba(19, 168, 168, 1);
						}

						.cl5 {
							background-color: rgba(230, 244, 255, 1);
							border-color: rgba(145, 202, 255, 1);
							color: rgba(22, 119, 255, 1);
						}

						.cl6 {
							background-color: rgba(240, 245, 255, 1);
							border-color: rgba(173, 198, 255, 1);
							color: rgba(47, 84, 235, 1);
						}
					}

					.right-item-time {
						position: absolute;
						top: 13px;
						right: 0;
						font-size: 16px;
						font-weight: 400;
						font-family: "Microsoft YaHei";
						line-height: 24px;
						color: rgb(95, 101, 108);
					}

					.right-item-money {
						position: absolute;
						top: 76px;
						right: 0;
						font-size: 18px;
						font-weight: 700;
						font-family: "Microsoft YaHei";
						line-height: 24px;
					}
				}

				.page {
					width: 1161px;
					height: 40px;
					display: flex;
					align-items: center;
					justify-content: space-between;


					margin-top: 29px;



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

					:deep(.el-pagination) {
						display: flex;
						align-items: center;
					}

					:deep(.el-pagination.is-background .el-pager li) {
						min-width: 32px;
						height: 32px;
						line-height: 32px;
						border-radius: 6px;
						margin: 0 6px;
						border: 1px solid rgba(0, 0, 0, 0.15);
						background-color: #fff;
						color: rgb(95, 101, 108);
						font-size: 16px;
						font-weight: 400;
						font-family: "Microsoft YaHei";
					}

					:deep(.el-pagination.is-background .el-pager li.is-active) {
						background-color: #fff;
						color: rgba(22, 119, 255, 1);
						border-color: rgba(22, 119, 255, 1);
						// box-shadow: 0 0 0 2px rgba(47, 122, 229, 0.15) inset;
					}

					:deep(.el-pagination.is-background .el-pager li.is-ellipsis) {
						border: none;
						background-color: transparent;
						color: rgb(95, 101, 108);
						min-width: 16px;
						margin: 0 6px;
					}

					:deep(.el-pagination.is-background .btn-prev),
					:deep(.el-pagination.is-background .btn-next) {
						min-width: 32px;
						height: 32px;
						border-radius: 6px;
						border: 1px solid rgba(0, 0, 0, 0.15);
						background-color: #fff;
						color: rgb(95, 101, 108);
						font-size: 16px;
						font-family: "Microsoft YaHei";
						margin: 0 6px;
					}

					:deep(.el-pagination.is-background .btn-prev.is-disabled),
					:deep(.el-pagination.is-background .btn-next.is-disabled) {
						color: rgba(95, 101, 108, 0.45);
						border-color: rgb(235, 238, 242);
						background-color: #fff;
					}
				}

			}


		}
	}
}
</style>
