<template>
	<div class="resource-library-section">
		<div class="home-content-footer-header">
			<div class="btn-box">
				<div class="btn" :class="{ btnActive: activeTabName === cate.name }" v-for="cate in tabList" :key="cate.name" @click="handleClickTab(cate)">
					{{ cate.name }}
				</div>
			</div>
		</div>
		<div class="home-content-footer-main" :class="{ 'committee-full-layout': activeTabName === '委员会' }">
			<div class="left" v-if="leftFilters.length">
				<div class="select-box" v-for="group in leftFilters" :key="group.key">
					<div class="select-box-header">
						<div class="icon"></div>
						<div class="title">{{ group.title }}</div>
					</div>
					<div class="select-main">
						<el-checkbox-group class="checkbox-group" v-model="group.model.value" @change="group.onChange">
							<el-checkbox v-for="opt in group.options" :key="opt.id" :label="opt.id" class="filter-checkbox">
								{{ opt.name }}
							</el-checkbox>
						</el-checkbox-group>
					</div>
				</div>
			</div>
			<div class="right" :class="{ 'right-full': activeTabName === '委员会' }">
				<div class="right-header" v-if="activeTabName !== '委员会'">
					<div class="right-header-box">
						<el-select v-model="footerSelect1" placeholder="选择委员会" style="width: 240px" @change="handleFooterSelect1Change">
							<el-option v-for="item in postOrgList" :key="item.departmentId" :label="item.departmentName" :value="item.departmentId" />
						</el-select>
					</div>
					<template v-if="activeTabName === '国会法案'">
						<div class="right-header-box">
							<el-select v-model="footerSelect2" placeholder="选择提出议员" style="width: 240px" @change="handleFooterSelect2Change">
								<el-option v-for="item in postMemberList" :key="item.memberId" :label="item.memberName" :value="item.memberId" />
							</el-select>
						</div>
						<div class="right-header-box right-header-sort" style="margin-left: auto">
							<el-checkbox v-model="isInvolveCn" true-label="Y" false-label="N" class="involve-checkbox" @change="handleInvolveCnChange">只看涉华法案</el-checkbox>
							<el-select v-model="releaseTime" placeholder="选择排序方式" style="width: 150px" @change="handlePxChange">
								<template #prefix>
									<div style="display: flex; align-items: center; height: 100%">
										<img :src="desc" style="width: 14px; height: 14px" />
									</div>
								</template>
								<el-option v-for="item in releaseTimeList" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</div>
					</template>
					<template v-else-if="activeTabName === '国会议员'">
						<div class="right-header-box right-header-sort" style="margin-left: auto">
							<el-select v-model="memberSortFun" placeholder="选择排序方式" style="width: 150px" @change="handleMemberSortFunChange">
								<template #prefix>
									<div style="display: flex; align-items: center; height: 100%">
										<img :src="desc" style="width: 14px; height: 14px" />
									</div>
								</template>
								<el-option v-for="item in memberSortFunList" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</div>
					</template>
				</div>
				<div class="right-header" v-else>
					<div class="right-header-box right-header-sort" style="margin-left: auto">
						<el-checkbox
							v-model="committeeIsInvolveCn"
							class="involve-checkbox"
							@change="handleCommitteeInvolveCnChange"
						>
							只看涉华委员会
						</el-checkbox>
					</div>
				</div>
				<div class="right-main" v-loading="loading">
					<template v-if="activeTabName === '国会法案'">
						<div class="right-main-box" v-for="item in bills" :key="item.billId">
							<div v-if="item.riskSignal" class="risk-tag" :class="getRiskTagClass(item.riskSignal)">{{ item.riskSignal }}</div>
							<div class="bill-cover">
								<img class="bill-image" :src="getBillImageUrl(item)" alt="" @error="handleBillImageError" />
								<div class="bill-id" :title="item.billId">{{ item.billId || "-" }}</div>
							</div>
							<div class="bill-content">
								<div class="header">
									<div class="title" @click="onClickToDetail(item)" :title="item.name">{{ item.name }}</div>
									<div class="en-title" :title="item.eName">{{ item.eName }}</div>
								</div>
								<div class="main">
									<div class="item"><div class="item-left">提案人：</div><div class="item-right">{{ item.tcr }}</div></div>
									<div class="item"><div class="item-left">委员会：</div><div class="item-right">{{ item.wyh }}</div></div>
									<div class="item"><div class="item-left">相关领域：</div><div class="item-right1"><div class="tag" v-for="(val, idx) in item.areaList" :key="`${item.billId}-${val}-${idx}`">{{ val }}</div></div></div>
									<div class="item"><div class="item-left">最新动议：</div><div class="item-right"><CommonPrompt :content="item.zxdy" /></div></div>
									<div class="item">
										<div class="item-left">法案进展：</div>
										<div class="item-right2">
											<div class="tag" v-for="(val, idx) in getReversedProgress(item.progress)" :key="`${item.billId}-${val}-${idx}`" :style="{ zIndex: item.progress.length - idx }">{{ val }}</div>
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="right-footer">
							<div class="footer-left">{{ `共 ${total} 项` }}</div>
							<div class="footer-right">
								<el-pagination @current-change="handleCurrentChange" :page-size="pageSize" :current-page="currentPage" background layout="prev, pager, next" :total="total" />
							</div>
						</div>
					</template>
					<div v-else-if="activeTabName === '国会议员'">
						<div class="member-grid">
							<div class="member-card" v-for="item in memberList" :key="item.id">
								<div class="member-card-top">
									<div class="member-avatar-wrap">
										<img class="member-avatar" :src="item.avatar || defaultAvatar" alt="avatar" @click="handleClickAvatar(item)" />
										<div class="member-icon-row">
											<img v-if="item.partyIcon" class="member-mini-icon-img" :src="item.partyIcon" alt="party" />
											<img v-if="item.chamberIcon" class="member-mini-icon-img" :src="item.chamberIcon" alt="chamber" />
										</div>
									</div>
									<div class="member-main">
										<div class="member-title-row">
											<div class="member-name">{{ item.name || '-' }}</div>
											<div class="member-link">{{ item.billCountText || '0项提案 >' }}</div>
										</div>
										<div class="member-meta">{{ item.partyText || '-' }} · {{ item.chamberText || '-' }} · {{ item.termText || '-' }}</div>
										<div class="member-committee">{{ item.committeeText || '-' }}</div>
										<div class="member-tags">
											<div class="member-tag" v-for="(tag, idx) in item.focusTags" :key="`${item.id}-${tag}-${idx}`">{{ tag }}</div>
										</div>
									</div>
								</div>
								<div class="member-card-bottom" @click="handleClickLatestProposal(item)">
									<div class="member-latest">最新提案：{{ item.latestProposal || '-' }}</div>
									<div class="member-arrow">></div>
								</div>
							</div>
						</div>
						<div class="right-footer">
							<div class="footer-left">{{ `共 ${memberTotal} 项` }}</div>
							<div class="footer-right">
								<el-pagination @current-change="handleMemberCurrentChange" :page-size="memberPageSize" :current-page="memberCurrentPage" background layout="prev, pager, next" :total="memberTotal" />
							</div>
						</div>
					</div>
					<div v-else-if="activeTabName === '议员合作关系'">
						<div class="coop-list">
							<div class="coop-card" v-for="item in coopPagedList" :key="item.id">
								<div class="coop-card-header">
									<div class="coop-members">
										<div class="coop-member">
											<img class="coop-avatar" :src="item.left.avatar || defaultAvatar" alt="avatar-left" @click="handleClickAvatar(item.left)" />
											<div class="coop-member-name" :title="item.left.name">{{ item.left.name }}</div>
										</div>
										<div class="coop-dot">·</div>
										<div class="coop-member">
											<img class="coop-avatar" :src="item.right.avatar || defaultAvatar" alt="avatar-right" @click="handleClickAvatar(item.right)" />
											<div class="coop-member-name" :title="item.right.name">{{ item.right.name }}</div>
										</div>
									</div>
									<div class="coop-count">
										{{ item.totalText }}
									</div>
									<slot name="coop-extra" :relation="item" />
								</div>
								<div class="coop-proposals">
									<div
										class="coop-proposal-item"
										v-for="proposal in item.proposals"
										:key="proposal.billId"
										@click="handleClickCoopProposal(proposal)"
									>
										<div class="coop-proposal-main">
											<div class="coop-proposal-title">
												<span class="year">{{ proposal.year }}</span>
												<span class="code">{{ proposal.code }}</span>
											</div>
											<div class="coop-proposal-subtitle" :title="proposal.title">
												{{ proposal.title }}
											</div>
										</div>
										<div class="coop-proposal-arrow">></div>
									</div>
								</div>
							</div>
						</div>
						<div class="right-footer">
							<div class="footer-left">{{ `共 ${coopTotal} 项` }}</div>
							<div class="footer-right">
								<el-pagination
									@current-change="handleCoopCurrentChange"
									:page-size="coopPageSize"
									:current-page="coopCurrentPage"
									background
									layout="prev, pager, next"
									:total="coopTotal"
								/>
							</div>
						</div>
					</div>
					<div v-else-if="activeTabName === '委员会'">
						<div class="coop-list committee-list">
							<div class="coop-card" v-for="item in committeeList" :key="item.id">
								<div class="coop-card-header">
									<div class="coop-members">
										<div class="coop-member">
											<img class="coop-avatar" :src="item.avatar || defaultAvatar" alt="committee-avatar" />
											<div class="coop-member-info">
												<div class="coop-member-name" :title="item.name">{{ item.name }}</div>
												<div v-if="item.nameEn" class="coop-member-name-en" :title="item.nameEn">
													{{ item.nameEn }}
												</div>
											</div>
										</div>
									</div>
									<!-- <div class="coop-summary" :title="item.desc">
										{{ item.desc }}
									</div> -->
									<div class="coop-count">
										{{ `${item.proposalSize ?? (item.bills || []).length}项重点法案` }}
									</div>
								</div>
								<div class="coop-proposals">
									<div
										class="coop-proposal-item"
										v-for="bill in item.bills"
										:key="`${item.id}-${bill.billId || bill.title}`"
										@click="handleClickCommitteeBill(bill)"
									>
										<div class="coop-proposal-main">
											<div class="coop-proposal-subtitle" :title="bill.title">
												{{ bill.title }}
											</div>
										</div>
										<div class="coop-proposal-arrow">></div>
									</div>
								</div>
							</div>
						</div>
						<div class="right-footer">
							<div class="footer-left">{{ `共 ${committeeTotal} 项` }}</div>
							<div class="footer-right">
								<el-pagination
									@current-change="handleCommitteeCurrentChange"
									:page-size="committeePageSize"
									:current-page="committeeCurrentPage"
									background
									layout="prev, pager, next"
									:total="committeeTotal"
								/>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { getHylyList, getPostOrgList, getPostMemberList, getBills, getBillsPerson, getBillsPersonRel, getBillsIsCnCommittee } from "@/api/bill/billHome";
import CommonPrompt from "../commonPrompt/index.vue";
import desc from "./assets/icons/icon-desc.png";
import defaultAvatar from "@/assets/icons/default-icon1.png";
import defaultBill from "../assets/images/image1.png";
import zyyIcon from "@/assets/icons/zyy.png";
import cyyIcon from "@/assets/icons/cyy.png";
import ghdIcon from "@/assets/icons/ghd.png";
import mzdIcon from "@/assets/icons/mzd.png";

const router = useRouter();

const props = defineProps({
	onClickToDetail: { type: Function, required: true },
	onAfterPageChange: { type: Function, default: null }
});

const tabList = [
	{ name: "国会法案" },
	{ name: "国会议员" },
	{ name: "议员合作关系" },
	{ name: "委员会" }
];
const activeTabName = ref("国会法案");
const handleClickTab = tab => {
	activeTabName.value = tab.name;
	if (tab.name === "国会议员") {
		memberCurrentPage.value = 1;
		handleGetBillsPerson();
		return;
	}
	if (tab.name === "国会法案") {
		currentPage.value = 1;
		handleGetBills();
		return;
	}
	if (tab.name === "议员合作关系") {
		coopCurrentPage.value = 1;
		handleGetCoopList();
		return;
	}
	if (tab.name === "委员会") {
		handleGetCommitteeList();
	}
};

// sortFun: true 正序 / false 倒序（法案接口字段）
const releaseTime = ref(true);
const releaseTimeList = ref([
	{ label: "发布时间正序", value: true },
	{ label: "发布时间倒序", value: false }
]);
const isInvolveCn = ref("Y");
const committeeIsInvolveCn = ref(false);

const cateKuList = ref([]);
const activeAreaList = ref(["全部领域"]);
const dpList = ref([{ id: "全部党派", name: "全部党派" }, { id: "Democratic", name: "民主党" }, { id: "Republican", name: "共和党" }]);
const activeDpList = ref(["全部党派"]);
const yyList = ref([{ id: "全部议院", name: "全部议院" }, { id: "S", name: "参议院" }, { id: "H", name: "众议院" }]);
const activeYyList = ref(["全部议院"]);
const pubTime = ref([{ id: "全部时间", name: "全部时间" }, { id: "2025", name: "2025年" }, { id: "2024", name: "2024年" }, { id: "2023", name: "2023年" }, { id: "2022", name: "2022年" }, { id: "2021", name: "2021年" }]);
const activePubTime = ref(["全部时间"]);

const areaOptions = computed(() => [{ id: "全部领域", name: "全部领域" }, ...(cateKuList.value || [])]);

const leftFilters = computed(() => {
	if (activeTabName.value === "委员会") {
		return [{ key: "chamber", title: "议院", model: activeYyList, options: yyList.value, onChange: handleYyChange }];
	}

	const filters = [{ key: "area", title: "科技领域", model: activeAreaList, options: areaOptions.value, onChange: handleAreaChange }];
	if (activeTabName.value !== "议员合作关系") {
		filters.push({ key: "party", title: "党派", model: activeDpList, options: dpList.value, onChange: handleDpChange });
		filters.push({ key: "chamber", title: "议院", model: activeYyList, options: yyList.value, onChange: handleYyChange });
	}
	if (activeTabName.value === "国会法案") {
		filters.push({ key: "pubTime", title: "发布时间", model: activePubTime, options: pubTime.value, onChange: handlePubTimeChange });
	}
	return filters;
});

const footerSelect1 = ref("全部委员会");
const footerSelect2 = ref("全部提出议员");
const postOrgList = ref([{ departmentName: "全部委员会", departmentId: "全部委员会" }]);
const postMemberList = ref([{ memberName: "全部提出议员", memberId: "全部提出议员" }]);
const memberList = ref([]);
// sortFun: boolean（议员接口字段），当前接口表现与“正序/倒序”相反，发参时取反
const memberSortFun = ref(false);
const memberSortFunList = ref([
	{ label: "提案数量正序", value: true },
	{ label: "提案数量倒序", value: false }
]);
const memberTotal = ref(0);
const memberPageSize = ref(15);
const memberCurrentPage = ref(1);

// 议员合作关系列表
const coopList = ref([]);
const coopTotal = ref(0);
const coopPageSize = ref(6);
const coopCurrentPage = ref(1);
const coopPagedList = computed(() => coopList.value || []);

const committeeList = ref([]);
const committeeTotal = ref(0);
const committeePageSize = ref(6);
const committeeCurrentPage = ref(1);

const bills = ref([]);
const total = ref(0);
const pageSize = ref(4);
const currentPage = ref(1);
const loading = ref(false);
const abortController = ref(null);
let requestToken = 0;

const beginAbortableRequest = () => {
	if (abortController.value) abortController.value.abort();
	abortController.value = new AbortController();
	requestToken += 1;
	const token = requestToken;
	loading.value = true;
	return { token, signal: abortController.value.signal };
};

const endAbortableRequest = token => {
	if (token === requestToken) loading.value = false;
};

const getRiskTagClass = riskSignal => {
	if (riskSignal === "特别重大风险") return "risk-tag-critical";
	if (riskSignal === "重大风险") return "risk-tag-high";
	if (riskSignal === "较大风险") return "risk-tag-medium";
	return "";
};

const getBillImageUrl = item => item?.imageUrl || defaultBill;
const handleBillImageError = e => {
	const img = e?.target;
	if (!img) return;
	if (img.dataset?.fallbackApplied === "1") return;
	img.dataset.fallbackApplied = "1";
	img.src = defaultBill;
};

const handleClickAvatar = member => {
	if (!member?.id) return;
	window.sessionStorage.setItem("curTabName", member.name || "");
	const routeData = router.resolve({
		path: "/characterPage",
		query: {
			personId: member.id
		}
	});
	window.open(routeData.href, "_blank");
};

const getReversedProgress = progress => (Array.isArray(progress) ? [...progress].reverse() : []);

const handleClickCommitteeBill = bill => {
	if (!bill?.billId) return;
	props.onClickToDetail({
		billId: bill.billId,
		name: bill.title || ""
	});
};

// 获取委员会列表
const handleGetCommitteeList = async () => {
	const { token, signal } = beginAbortableRequest();

	const params = {
		currentPage: committeeCurrentPage.value,
		pageSize: committeePageSize.value,
		isInvolveCn: committeeIsInvolveCn.value
	};

	if (!activeYyList.value.includes("全部议院")) params.congressIds = activeYyList.value.join(",");

	try {
		const res = await getBillsIsCnCommittee(params, signal);
		if (res.code === 200 && res.data && Array.isArray(res.data.content)) {
			committeeList.value = res.data.content.map(item => {
				const billInfoPage = item.billInfoPage || [];
				const bills = billInfoPage.slice(0, 4).map(bill => ({
					billId: bill.billId,
					title: bill.billName || "-"
				}));
				const descText = billInfoPage[0]?.originDepart || "";
				return {
					id: item.id,
					nameEn:item.nameEn || "",
					avatar: "",
					name: item.name || "-",
					desc: descText,
					proposalSize: Number(item.proposalSize || 0),
					bills
				};
			});
			committeeTotal.value = res.data.totalElements || 0;
		} else {
			committeeList.value = [];
			committeeTotal.value = 0;
		}
	} catch (error) {
		if (error.name !== "AbortError") {
			committeeList.value = [];
			committeeTotal.value = 0;
		}
	} finally {
		endAbortableRequest(token);
	}
};

// 获取议员合作关系数据
const handleGetCoopList = async () => {
	const { token, signal } = beginAbortableRequest();

	const params = {
		currentPage: coopCurrentPage.value,
		pageSize: coopPageSize.value
	};

	if (!activeAreaList.value.includes("全部领域")) params.domainIds = activeAreaList.value;

	try {
		const res = await getBillsPersonRel(params, signal);
		if (res.code === 200 && res.data && Array.isArray(res.data.content)) {
			const list = res.data.content.map(item => {
				const memberInfoList = item.memberInfoList || [];
				const left = memberInfoList[0] || {};
				const right = memberInfoList[1] || {};
				const billsNum = Number(item.billsNum || 0);
				const proposals = (item.billInfoList || []).slice(0, 4).map(bill => {
					const proposedDate = bill.proposedDate ? String(bill.proposedDate) : "";
					const year = proposedDate ? proposedDate.slice(0, 4) : "";
					const codeParts = [];
					if (bill.type) codeParts.push(bill.type);
					if (bill.number) codeParts.push(bill.number);
					return {
						billId: bill.billId,
						year,
						code: codeParts.join("."),
						title: bill.billName
					};
				});
				const id = [left.id, right.id].filter(Boolean).join("-");
				const leftName = left.name || "-";
				const rightName = right.name || "-";
				return {
					id: id || Math.random().toString(36).slice(2),
					left: {
						id: left.id,
						name: leftName,
						avatar: left.imageUrl || ""
					},
					right: {
						id: right.id,
						name: rightName,
						avatar: right.imageUrl || ""
					},
					total: billsNum,
					totalText: `${billsNum}项共同提案`,
					summary: `${leftName} 与 ${rightName} 在 ${billsNum} 项法案上合作`,
					proposals
				};
			});
			coopList.value = list;
			coopTotal.value = res.data.totalElements || list.length;
		} else {
			coopList.value = [];
			coopTotal.value = 0;
		}
	} catch (error) {
		if (error.name !== "AbortError") {
			coopList.value = [];
			coopTotal.value = 0;
		}
	} finally {
		endAbortableRequest(token);
	}
};

const handleGetHylyList = async () => {
	try {
		const res = await getHylyList();
		cateKuList.value = res.data || [];
	} catch (error) {}
};

const handleGetPostOrgList = async () => {
	try {
		const res = await getPostOrgList();
		if (res.code === 200) {
			const list = (res.data || []).filter(item => item.departmentId);
			postOrgList.value = [{ departmentName: "全部委员会", departmentId: "全部委员会" }, ...list];
		}
	} catch (error) {}
};

const handleGetPostMemberList = async () => {
	try {
		const res = await getPostMemberList();
		if (res.code === 200) {
			const list = (res.data || []).filter(item => item.memberId);
			postMemberList.value = [{ memberName: "全部提出议员", memberId: "全部提出议员" }, ...list];
		}
	} catch (error) {}
};

// 获取资源库法案列表
const handleGetBills = async () => {
	const { token, signal } = beginAbortableRequest();

	const params = {
		currentPage: currentPage.value,
		pageSize: pageSize.value,
		isInvolveCn: isInvolveCn.value
	};

	if (!activeYyList.value.includes("全部议院")) params.congressIds = activeYyList.value.join(",");
	if (footerSelect1.value !== "全部委员会") params.departmentId = footerSelect1.value;
	if (!activeDpList.value.includes("全部党派")) params.partyIds = activeDpList.value.join(",");
	if (footerSelect2.value !== "全部提出议员") params.personId = footerSelect2.value;
	if (!activeAreaList.value.includes("全部领域")) params.researchIds = activeAreaList.value.join(",");
	params.sortFun = releaseTime.value;
	if (!activePubTime.value.includes("全部时间")) params.years = activePubTime.value.join(",");

	try {
		const res = await getBills(params, signal);
		if (res.code === 200 && res.data && res.data.content) {
			bills.value = res.data.content.map(item => ({
				billId: item.billId,
				name: item.billName,
				eName: item.billNameEn,
				tcr: item.personName,
				wyh: item.congressName,
				areaList: item.hylyList || [],
				zxdy: item.latestAction,
				progress: item.stageList || [],
				riskSignal: item.riskSignal || "",
				imageUrl: item.imageUrl || ""
			}));
			total.value = res.data.totalElements;
		} else {
			bills.value = [];
			total.value = 0;
		}
	} catch (error) {
		if (error.name !== "AbortError") {
			bills.value = [];
			total.value = 0;
		}
	} finally {
		endAbortableRequest(token);
	}
};

// 获取资源库国会议员列表
const handleGetBillsPerson = async () => {
	const { token, signal } = beginAbortableRequest();

	const params = {
		currentPage: memberCurrentPage.value,
		pageSize: memberPageSize.value,
		sortFun: !memberSortFun.value
	};

	if (footerSelect1.value !== "全部委员会") params.committeeId = footerSelect1.value;
	if (!activeYyList.value.includes("全部议院")) params.congressIds = activeYyList.value;
	if (!activeDpList.value.includes("全部党派")) params.partyIds = activeDpList.value;
	if (!activeAreaList.value.includes("全部领域")) params.domainIds = activeAreaList.value;

	const formatDateYm = dateStr => {
		if (!dateStr) return "";
		const date = String(dateStr).slice(0, 10);
		const parts = date.split("-");
		if (parts.length < 2) return dateStr;
		return `${parts[0]}.${parts[1]}`;
	};

	try {
		const res = await getBillsPerson(params, signal);
		if (res.code === 200 && res.data && res.data.content) {
			memberList.value = res.data.content.map(item => {
				const partyMap = { Democratic: "民主党", Republican: "共和党" };
				const partyText = partyMap[item.partyId] || item.partyId || "-";
				const chamberText = item.congressType || "-";
				const start = formatDateYm(item.startTime);
				const end = formatDateYm(item.endTime);
				const termText = start || end ? `${start}${end ? `-${end}` : ""}` : "-";
				const focusTags = (item.domainNames || []).slice(0, 3);
				const proposalSize = Number(item.proposalSize || 0);
				const partyIcon = item.partyId === "Democratic" ? mzdIcon : item.partyId === "Republican" ? ghdIcon : "";
				const chamberIcon = chamberText === "众议院" ? zyyIcon : chamberText === "参议院" ? cyyIcon : "";
				return {
					id: item.id,
					name: item.name || "-",
					avatar: item.imageUrl || "",
					partyIcon,
					chamberIcon,
					proposalSize,
					billCountText: `${proposalSize.toLocaleString()}项提案 >`,
					partyText,
					chamberText,
					termText,
					committeeText: item.position || "-",
					focusTags,
					latestProposal: item.latestBillInfo?.billName || "-",
					latestProposalBillId: item.latestBillInfo?.billId || "",
					party: item.partyId,
					chamber: item.congressType,
					term: `${item.startTime || ""}${item.endTime ? ` 至 ${item.endTime}` : ""}`,
					committee: item.position,
					focus: (item.domainNames || []).join("、")
				};
			});
			memberTotal.value = res.data.totalElements || 0;
		} else {
			memberList.value = [];
			memberTotal.value = 0;
		}
	} catch (error) {
		if (error.name !== "AbortError") {
			memberList.value = [];
			memberTotal.value = 0;
		}
	} finally {
		endAbortableRequest(token);
	}
};

const resetPages = () => {
	currentPage.value = 1;
	memberCurrentPage.value = 1;
	coopCurrentPage.value = 1;
	committeeCurrentPage.value = 1;
};

const refreshByActiveTab = () => {
	if (activeTabName.value === "议员合作关系") {
		handleGetCoopList();
		return;
	}
	if (activeTabName.value === "委员会") {
		handleGetCommitteeList();
		return;
	}
	if (activeTabName.value === "国会议员") {
		handleGetBillsPerson();
		return;
	}
	handleGetBills();
};

const normalizeWithAll = (val, allLabel, targetRef) => {
	if (val.includes(allLabel) && val.length > 1) {
		targetRef.value = val[val.length - 1] === allLabel ? [allLabel] : val.filter(item => item !== allLabel);
	} else if (val.length === 0) {
		targetRef.value = [allLabel];
	} else {
		targetRef.value = val;
	}
	resetPages();
	refreshByActiveTab();
};

const handleAreaChange = val => normalizeWithAll(val, "全部领域", activeAreaList);
const handleDpChange = val => normalizeWithAll(val, "全部党派", activeDpList);
const handleYyChange = val => normalizeWithAll(val, "全部议院", activeYyList);
const handlePubTimeChange = val => normalizeWithAll(val, "全部时间", activePubTime);

const handleFooterSelect1Change = val => {
	footerSelect1.value = val;
	resetPages();
	refreshByActiveTab();
};
const handleFooterSelect2Change = val => {
	footerSelect2.value = val;
	currentPage.value = 1;
	handleGetBills();
};
const handlePxChange = val => {
	releaseTime.value = val;
	currentPage.value = 1;
	handleGetBills();
};
const handleInvolveCnChange = val => {
	isInvolveCn.value = val;
	currentPage.value = 1;
	handleGetBills();
};

const handleCommitteeInvolveCnChange = val => {
	committeeIsInvolveCn.value = val;
	committeeCurrentPage.value = 1;
	handleGetCommitteeList();
};

const handleCurrentChange = page => {
	currentPage.value = page;
	handleGetBills();
	props.onAfterPageChange && props.onAfterPageChange();
};

const handleClickLatestProposal = item => {
	if (!item?.latestProposalBillId) return;
	props.onClickToDetail({
		billId: item.latestProposalBillId,
		name: item.latestProposal
	});
};

const handleMemberSortFunChange = val => {
	memberSortFun.value = val;
	memberCurrentPage.value = 1;
	handleGetBillsPerson();
};

const handleClickCoopProposal = proposal => {
	if (!proposal?.billId) return;
	props.onClickToDetail({
		billId: proposal.billId,
		name: proposal.title || proposal.code || ""
	});
};

const handleCoopCurrentChange = page => {
	coopCurrentPage.value = page;
	handleGetCoopList();
	props.onAfterPageChange && props.onAfterPageChange();
};

const handleMemberCurrentChange = page => {
	memberCurrentPage.value = page;
	handleGetBillsPerson();
	props.onAfterPageChange && props.onAfterPageChange();
};

const handleCommitteeCurrentChange = page => {
	committeeCurrentPage.value = page;
	handleGetCommitteeList();
	props.onAfterPageChange && props.onAfterPageChange();
};

onMounted(() => {
	handleGetHylyList();
	handleGetPostOrgList();
	handleGetPostMemberList();
	handleGetBills();
});
</script>

<style lang="scss" scoped>
.home-content-footer-header {
	width: 1600px;
	margin: 0 auto;
	margin-top: 37px;
	margin-bottom: 36px;
	height: 42px;
	display: flex;
	justify-content: space-between;

	.btn-box {
		display: flex;
		gap: 24px;
		width: 1000px;

		.btn {
			height: 42px;
			line-height: 42px;
			padding: 0 20px;
			color: var(--text-primary-80-color);
			font-family: Microsoft YaHei;
			font-size: 20px;
			font-weight: 400;
			border-radius: 21px;
			cursor: pointer;

			&:hover {
				background: rgba(20, 89, 187, 0.1);
			}
		}

		.btnActive {
			background: var(--color-main-active);
			color: var(--bg-white-100);
			font-weight: 700;

			&:hover {
				color: var(--bg-white-100);
				background: var(--color-main-active);
			}
		}
	}
}

.home-content-footer-main {
	width: 1600px;
	min-height: 1401px;
	margin: 0 auto;
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	padding-bottom: 39px;

	&.committee-full-layout {
		.right {
			.right-main {
				height: auto;
			}
		}
	}

	.left {
		width: 360px;
		padding-bottom: 33px;
		box-sizing: border-box;
		border: 1px solid rgba(234, 236, 238, 1);
		border-radius: 10px;
		box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
		background: var(--bg-white-100);

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

			.select-box-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 {
					color: var(--color-main-active);
					font-family: Microsoft YaHei;
					font-size: var(--font-size-base);
					font-weight: 700;
					line-height: 24px;
					letter-spacing: 1px;
					text-align: left;
				}
			}

			.select-main {
				margin-left: 25px;
				margin-top: 16px;

				.checkbox-group {
					display: flex;
					flex-wrap: wrap;

					.filter-checkbox {
						width: 50%;
						margin-right: 0;
						margin-bottom: 4px;

						:deep(.el-checkbox__label) {
							color: var(--text-primary-65-color);
							font-size: var(--font-size-base);
							font-weight: 400;
							font-family: "Microsoft YaHei";
							line-height: 24px;
						}
					}
				}
			}
		}
	}

	.right {
		margin-left: 20px;
		width: calc(100% - 380px);
		min-width: 0;

		.right-header {
			height: 48px;
			display: flex;
			gap: 18px;

			.right-header-sort {
				display: flex;
				align-items: center;
				gap: 20px;
			}

			.proposal-sort-btn {
				height: 40px;
				padding: 0 12px;
				border-radius: 6px;
				border: 1px solid #dcdfe6;
				background: var(--bg-white-100);
				display: inline-flex;
				align-items: center;
				gap: 8px;
				cursor: pointer;
				user-select: none;
				transition: background 0.15s ease;

				&:hover {
					background: rgba(20, 89, 187, 0.04);
				}
			}

			.proposal-sort-icon {
				width: 14px;
				height: 14px;
				flex-shrink: 0;
			}

			.proposal-sort-text {
				color: var(--text-primary-65-color);
				font-family: "Microsoft YaHei";
				font-size: var(--font-size-base);
				line-height: 24px;
				white-space: nowrap;
			}

			.proposal-sort-order {
				color: var(--text-primary-80-color);
				font-family: "Microsoft YaHei";
				font-size: var(--font-size-base);
				line-height: 24px;
				white-space: nowrap;
			}

			.involve-checkbox {
				height: 40px;
				display: inline-flex;
				align-items: center;
				margin-right: 0;

				:deep(.el-checkbox__inner) {
					width: 18px;
					height: 18px;
					border-radius: 5px;
				}

				:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
					background-color: #1677ff;
					border-color: #1677ff;
				}

				:deep(.el-checkbox__inner::after) {
					box-sizing: content-box;
				}

				:deep(.el-checkbox__label) {
					color: var(--text-primary-65-color);
					font-family: "Microsoft YaHei";
					font-size: var(--font-size-base);
					font-weight: 400;
					line-height: 24px;
					padding-left: 10px;
				}
			}
		}

		.right-main {
			min-height: 1264px;

			.member-grid,
			.coop-list,
			.committee-list {
				display: grid;
				column-gap: 16px;
				row-gap: 16px;
			}

			.member-grid,
			.coop-list {
				display: grid;
				column-gap: 16px;
				row-gap: 16px;

				.member-card {
					height: 200px;
					padding: 10px 16px 0;
					box-sizing: border-box;
					border-radius: 10px;
					box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
					background: var(--bg-white-100);
					overflow: hidden;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.member-card-top {
						display: flex;
						gap: 16px;
					}

					.member-avatar-wrap {
						width: 88px;
						display: flex;
						flex-direction: column;
						align-items: center;
						flex-shrink: 0;
						position: relative;
						/* padding-bottom: 22px; */
						margin-top: 5px;
					}

					.member-avatar {
						width: 88px;
						height: 88px;
						border-radius: 50%;
						object-fit: cover;
						cursor: pointer;
					}

					.member-icon-row {
						position: absolute;
						left: 50%;
						bottom: 18px;
						transform: translateX(-50%);
						display: flex;
						gap: 2px;
						align-items: center;
					}

					.member-mini-icon-img {
						width: 16px;
						height: 16px;
						padding: 2px;
						box-sizing: border-box;
						object-fit: contain;
						border-radius: 50%;
						background: var(--bg-white-100);
					}

					.member-main {
						flex: 1;
						min-width: 0;
						padding-top: 2px;
					}

					.member-title-row {
						display: flex;
						align-items: baseline;
						justify-content: space-between;
						align-items: center;
						gap: 8px;
					}

					.member-name {
						color: var(--text-primary-80-color);
						font-family: "Source Han Sans CN";
						font-size: 18px;
						font-weight: 700;
						line-height: 24px;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.member-link {
						flex-shrink: 0;
						color: #1459bb;
						font-size: var(--font-size-base);
						line-height: 24px;
					}

					.member-meta,
					.member-committee {
						margin-top: 6px;
						color: var(--text-primary-65-color);
						font-size: var(--font-size-base);
						line-height: 24px;
						font-weight: 400;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.member-tags {
						margin-top: 10px;
						display: flex;
						gap: 8px;
						flex-wrap: wrap;
					}

					.member-tag {
						height: 24px;
						padding: 5px 8px;
						border-radius: 4px;
						background: var(--color-primary-10);
						color: var(--color-main-active);
						font-size: 14px;
						font-weight: 400;
						line-height: 14px;
					}

					.member-card-bottom {
						height: 52px;
						margin: 10px -16px 0;
						padding: 0 16px;
						display: flex;
						align-items: center;
						justify-content: space-between;
						border-top: 1px solid #eaeced;
						color: var(--text-primary-65-color);
						font-size: var(--font-size-base);
						cursor: pointer;

						&:hover {
							background: rgba(20, 89, 187, 0.04);
						}
					}

					.member-latest {
						flex: 1;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						padding-right: 8px;
					}

					.member-arrow {
						font-size: var(--font-size-base);
						line-height: 1;
						color: var(--text-primary-65-color);
					}

					.member-info {
						color: #5f656c;
						font-family: "Microsoft YaHei";
						font-size: 15px;
						font-weight: 400;
						line-height: 28px;
					}
				}
			}

			.member-grid {
				grid-template-columns: repeat(3, 1fr);
			}

			.coop-list {
				grid-template-columns: 1fr;

				.coop-card {
					padding: 16px 20px 14px;
					box-sizing: border-box;
					border-radius: 10px;
					box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
					background: var(--bg-white-100);
					display: flex;
					flex-direction: column;
					gap: 12px;
				}

				.coop-card-header {
					display: flex;
					align-items: center;
					gap: 16px;
				}

				.coop-members {
					display: flex;
					align-items: center;
					gap: 12px;
					min-width: 0;
				}

				.coop-member {
					display: flex;
					align-items: center;
					gap: 8px;
					min-width: 0;
				}

				.coop-member-info {
					display: flex;
					flex-direction: column;
					min-width: 0;
				}

				.coop-avatar {
					width: 40px;
					height: 40px;
					border-radius: 50%;
					object-fit: cover;
					flex-shrink: 0;
					cursor: pointer;
				}

				.coop-member-name {
					max-width: none;
					color: var(--text-primary-80-color);
					font-family: "Source Han Sans CN";
					font-size: var(--font-size-base);
					font-weight: 700;
					line-height: 24px;
					white-space: normal;
					overflow: visible;
					text-overflow: clip;
					word-break: break-word;
                }

				.coop-dot {
					color: #9da3ac;
					font-size: 18px;
					line-height: 1;
				}

				.coop-summary {
					flex: 1;
					min-width: 0;
					color: var(--text-primary-65-color);
					font-family: "Microsoft YaHei";
					font-size: 14px;
					font-weight: 400;
					line-height: 22px;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.coop-member-name-en {
					color: var(--text-primary-65-color);
					font-family: "Microsoft YaHei";
					font-size: 14px;
					font-weight: 400;
					line-height: 22px;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.coop-count {
					flex-shrink: 0;
					color: #1459bb;
					font-family: "Microsoft YaHei";
					font-size: 14px;
					font-weight: 500;
					line-height: 22px;
					margin-left: auto;
				}

				.coop-proposals {
					padding-top: 10px;
					border-top: 1px solid #eaeced;
					display: grid;
					grid-template-columns: repeat(2, minmax(0, 1fr));
					column-gap: 14px;
					row-gap: 12px;
				}

				.coop-proposal-item {
					position: relative;
					height: 64px;
					padding: 8px 34px 8px 20px;
					box-sizing: border-box;
					border-radius: 8px;
					background: rgb(247, 248, 249);
					display: flex;
					align-items: center;
					cursor: pointer;
					transition: background 0.15s ease;

					&::before {
						content: "";
						position: absolute;
						left: 0px;
						top: 12px;
						bottom: 12px;
						width: 3px;
						background: rgb(5, 95, 194);
					}
				}

				.coop-proposal-item:hover {
					background: rgba(20, 89, 187, 0.06);
				}

				.coop-proposal-main {
					flex: 1;
					min-width: 0;
				}

				.coop-proposal-title {
					display: flex;
					align-items: center;
					gap: 8px;
					color: var(--text-primary-80-color);
					font-family: "Microsoft YaHei";
					font-size: 15px;
					font-weight: 700;
					line-height: 22px;
				}

				.coop-proposal-title .year {
					color: #9da3ac;
					font-weight: 400;
				}

				.coop-proposal-subtitle {
					margin-top: 2px;
					color: var(--text-primary-65-color);
					font-family: "Microsoft YaHei";
					font-size: 14px;
					font-weight: 400;
					line-height: 22px;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.coop-proposal-arrow {
					position: absolute;
					right: 12px;
					top: 50%;
					transform: translateY(-50%);
					color: #c0c4cc;
					font-size: var(--font-size-base);
					line-height: 1;
				}
			}

			.committee-list {
				grid-template-columns: 1fr;

				.committee-card {
					padding: 20px 24px;
					border-radius: 10px;
					box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
					background: var(--bg-white-100);
				}

				.committee-info {
					display: flex;
					gap: 16px;
					align-items: flex-start;
					padding-bottom: 16px;
					border-bottom: 1px solid #eaeced;
				}

				.committee-avatar {
					width: 64px;
					height: 64px;
					border-radius: 50%;
					object-fit: cover;
					flex-shrink: 0;
				}

				.committee-name {
					color: var(--text-primary-80-color);
					font-family: "Microsoft YaHei";
					font-size: 20px;
					font-weight: 700;
					line-height: 28px;
				}

				.committee-desc {
					margin-top: 8px;
					color: var(--text-primary-65-color);
					font-family: "Microsoft YaHei";
					font-size: var(--font-size-base);
					font-weight: 400;
					line-height: 24px;
				}

				.committee-bill-grid {
					margin-top: 16px;
					display: grid;
					grid-template-columns: repeat(2, minmax(0, 1fr));
					gap: 12px;
				}

				.committee-bill-item {
					height: 48px;
					padding: 0 14px;
					border-radius: 6px;
					background: #f5f8fc;
					color: #3b414b;
					font-family: "Microsoft YaHei";
					font-size: 15px;
					font-weight: 400;
					line-height: 48px;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}

			.right-main-box {
				position: relative;
				width: 100%;
				height: 320px;
				padding: 12px 16px;
				box-sizing: border-box;
				border-radius: 10px;
				box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
				background: var(--bg-white-100);
				margin-bottom: 16px;
				overflow: hidden;
				display: flex;
				gap: 16px;
				align-items: center;

				.risk-tag {
					position: absolute;
					top: 12px;
					right: 16px;
					height: 28px;
					border-radius: 20px;
					display: inline-flex;
					align-items: center;
					gap: 6px;
					padding: 0 10px;
					box-sizing: border-box;
					font-family: "Microsoft YaHei";
					font-size: 14px;
					font-weight: 500;
					line-height: 28px;
					white-space: nowrap;

					&::before {
						content: "";
						width: 5px;
						height: 5px;
						border-radius: 50%;
						background: currentColor;
						flex-shrink: 0;
					}
				}

				.risk-tag-critical {
					background: var(--color-red-10);
					color: var(--color-red-100);
				}

				.risk-tag-high {
					background: var(--color-orange-10);
					color: var(--color-orange-100);
				}

				.risk-tag-medium {
					background: var(--color-yellow-10);
					color: var(--color-yellow-100);
				}

				.bill-cover {
					width: 240px;
					flex-shrink: 0;
					position: relative;
					height: 100%;
					margin: 0;
					overflow: hidden;

					&::after {
						content: "";
						position: absolute;
						left: 0;
						right: 0;
						bottom: 0;
						height: 33.333%;
						background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.92) 60%, var(--bg-white-100));
						pointer-events: none;
					}
				}

				.bill-image {
					width: 240px;
					height: 100%;
					object-fit: none;
					display: block;
				}

				.bill-id {
					position: absolute;
					left: 0;
					right: 0;
					bottom: 0;
					height: 33.333%;
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 0 12px;
					box-sizing: border-box;
					color: var(--text-primary-80-color);
					font-family: "Source Han Sans CN";
					font-size: 20px;
					font-weight: 700;
					line-height: 26px;
					letter-spacing: 0px;
					text-align: center;
					max-width: 100%;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					z-index: 1;
				}

				.bill-content {
					flex: 1;
					min-width: 0;
					overflow: hidden;
					box-sizing: border-box;
				}

				.header {
					width: 100%;
					border-bottom: 1px solid rgba(234, 236, 238, 1);
					padding-bottom: 14px;
					padding-right: 120px;

					.title {
						cursor: pointer;
						height: 26px;
						color: var(--text-primary-80-color);
						font-family: Microsoft YaHei;
						font-size: 20px;
						font-weight: 700;
						line-height: 26px;
						letter-spacing: 0px;
						text-align: left;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					.en-title {
						margin-top: 8px;
						height: 24px;
						color: var(--text-primary-65-color);
						font-family: Microsoft YaHei;
						font-size: var(--font-size-base);
						font-weight: 400;
						line-height: 24px;
						letter-spacing: 0px;
						text-align: left;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}

				.main {
					width: 100%;
					margin-top: 10px;

					.item {
						margin-top: 12px;
						display: flex;
						align-items: flex-start;

						.item-left {
							width: 88px;
							color: var(--text-primary-80-color);
							font-family: "Microsoft YaHei";
							font-size: var(--font-size-base);
							font-weight: 700;
							line-height: 24px;
							letter-spacing: 1px;
							text-align: left;
						}

						.item-right {
							max-width: 1000px;
							margin-left: 10px;
							color: var(--text-primary-65-color);
							font-family: "Microsoft YaHei";
							font-size: var(--font-size-base);
							font-weight: 400;
							line-height: 24px;
							letter-spacing: 0px;
							text-align: left;
						}

						.item-right1 {
							margin-left: 10px;
							display: flex;
							gap: 8px;
							flex-wrap: wrap;

							.tag {
								height: 24px;
								line-height: 24px;
								padding: 0 8px;
								border-radius: 4px;
								background: var(--color-primary-10);
								color: var(--color-main-active);
								font-family: "Microsoft YaHei";
								font-size: 14px;
								font-weight: 400;
							}
						}

						.item-right2 {
							margin-left: 10px;
							display: flex;
							align-items: center;
							flex-wrap: wrap;

							.tag {
								height: 24px;
								line-height: 22px;
								padding: 0 10px 0 30px;
								background: var(--bg-white-100);
								color: var(--text-primary-65-color);
								border-top: 1px solid rgb(234, 236, 238);
								border-bottom: 1px solid rgb(234, 236, 238);
								position: relative;
								margin-left: -10px;
								font-family: "Microsoft YaHei";
								font-size: 14px;
								font-weight: 400;

								&::after {
									content: "";
									position: absolute;
									top: 50%;
									right: -8.485px;
									width: 16.97px;
									height: 16.97px;
									background: inherit;
									border-top: 1px solid rgb(234, 236, 238);
									border-right: 1px solid rgb(234, 236, 238);
									transform: translateY(-50%) rotate(45deg);
									z-index: 1;
									box-shadow: 2px -2px 2px rgba(0, 0, 0, 0.05);
									box-sizing: border-box;
								}

								&:first-child {
									margin-left: 0;
									padding-left: 10px;
									border-left: 1px solid rgb(234, 236, 238);
									border-radius: 4px 0 0 4px;
								}

								&:last-child {
									background: var(--text-primary-80-color);
									color: var(--bg-white-100);
									border-color: var(--text-primary-80-color);
									padding-right: 10px;
									border-radius: 0;
									border-right: none;

									&::after {
										display: block;
										border-color: var(--text-primary-80-color);
										box-shadow: none;
									}
								}

								&:first-child:last-child {
									margin-left: 0;
									padding: 0 10px;
									border-radius: 4px 0 0 4px;
									background: var(--text-primary-80-color);
									color: var(--bg-white-100);
									border: 1px solid var(--text-primary-80-color);
									border-right: none;
								}
							}
						}
					}
				}
			}
		}

		.right-footer {
			height: 85px;
			display: flex;
			justify-content: space-between;
			box-sizing: border-box;
			padding-top: 12px;

			.footer-left {
				color: var(--text-primary-80-color);
				font-family: "Microsoft YaHei";
				font-size: var(--font-size-base);
				font-weight: 400;
				line-height: 32px;
			}
		}
	}
}
</style>
