<template>
	<div class="list-page">
		<div class="search-box">
			<div style="display: flex; justify-content: center">
				<el-select v-model="currentCCLVersion" style="width: 388px; height: 32px; margin-right: 14px">
					<el-option v-for="item in cclVersionList" :key="item.key" :label="item.value" :value="item.key" />
				</el-select>
				<el-input v-model="searchKeyword" class="search-input" placeholder="搜索物项或ECCN编码" :suffix-icon="Search" />
			</div>
			<div class="filters">
				<el-checkbox v-model="viewNew" label="查看最近更新内容" />
				<el-select placeholder="全部类别" v-model="currentCCLType" style="width: 388px; height: 32px; margin-right: 14px">
					<el-option v-for="item in CCLTypeList" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</div>
		</div>
		<div class="main">
			<div class="left">
				<div class="title">
					<div class="box"></div>
					<div class="text">科技领域</div>
				</div>
				<div class="checkbox-group">
					<el-checkbox
						v-for="(item, index) in techFields"
						:key="index"
						v-model="item.checked"
						:label="item.name"
						@change="handleFilterChange(item, techFields, 'tech')"
					/>
				</div>
				<div class="title">
					<div class="box"></div>
					<div class="text">管控原因</div>
				</div>
				<div class="checkbox-group">
					<el-checkbox
						v-for="(item, index) in controlReason"
						:key="index"
						v-model="item.checked"
						:label="item.name"
						@change="handleFilterChange(item, controlReason, 'reason')"
					/>
				</div>
			</div>
			<div class="right">
				<AnalysisBox title="CCL清单列表" :showAllBtn="false">
					<div class="right-table">
						<div class="list" v-for="(item, i) in cclList" :key="i">
							<div class="list-title" @click="item.isExpand = !item.isExpand">
								<span>类别 {{ item.cclCode }}-{{ item.cclTitleZh }}</span>
								<img src="../../assets/downArrow_white.png" alt v-if="item.isExpand" />
								<img src="../../assets/upArrow_white.png" alt v-else />
							</div>

							<div style="width: 100%" v-if="item.isExpand">
								<div
									style="width: 100%; position: relative"
									v-for="(element, index) in item.cclChildren"
									:key="index"
								>
									<div class="dot" v-if="element.changeFlag"></div>
									<div class="list-desc">{{ element.cclCode }}. {{ element.cclTitleZh }}</div>

									<div class="list-content" v-for="(ele, j) in element.cclChildren" :key="j">
										<div class="content-title" @click="ele.isExpand = !ele.isExpand">
											<div class="code-zone">
												<div class="dot" v-if="ele.changeFlag"></div>
												<span class="code">{{ ele.cclCode }}</span>
											</div>
											<span class="name">{{ ele.cclTitleZh }}</span>
											<img src="../../assets/upArrow_gray.png" alt v-if="ele.isExpand" />
											<img src="../../assets/downArrow_gray.png" alt v-else />
										</div>
										<div class="content-body" v-if="ele.isExpand">
											<!-- <img src="../../assets/cclDetail.png" alt /> -->
											<div v-if="ele.cclDescription" v-html="ele.cclDescription"></div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</AnalysisBox>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { Search, Select } from "@element-plus/icons-vue";
import defaultIcon from "../../../../../assets/icons/default-avatar.png";
import {
	getECCNCategory,
	getAreaType,
	getControlReason,
	getCclQuery,
	getCCLVersionList,
	getExportControlList,
	get50PercentEntityCount
} from "@/api/exportControlV2.0.js";
import dayjs from "dayjs";

const router = useRouter();

const currentCCLType = ref("");
const CCLTypeList = ref([]);
const getTypeList = async () => {
	try {
		const res = await getECCNCategory();
		if (res && res.code === 200) {
			console.log("-----getTypeList", res.data);
			CCLTypeList.value = [{ id: "", name: "全部类别" }].concat(res.data);
			currentCCLType.value = "";
		}
	} catch (error) {
		console.error("获取类别字典失败:", error);
	}
};

const techFields = ref([]);
const getTechFields = async () => {
	try {
		const res = await getAreaType();
		if (res && res.code === 200) {
			console.log("-----getTechFields", res.data);
			techFields.value = [{ id: "all", name: "全部领域", checked: true }].concat(res.data);
			// 默认选中第一个
			// techFields.value[0].checked = true;
		}
	} catch (error) {
		console.error("获取科技领域字典失败:", error);
	}
};

const controlReason = ref([]);
const getControlReasonList = async () => {
	try {
		const res = await getControlReason();
		if (res && res.code === 200) {
			console.log("-----getControlReasonList", res.data);
			controlReason.value = [{ id: "all", name: "全部", checked: true }].concat(res.data);
			// 默认选中第一个
			// controlReason.value[0].checked = true;
		}
	} catch (error) {
		console.error("获取管控原因字典失败:", error);
	}
};

const searchKeyword = ref("");
const onlyChina = ref(false);
const viewNew = ref(true);

// 获取ccl清单列表
// const getCclList = async () => {
// 	let techDomains = [];
// 	const allTech = techFields.value.find(item => item.id === "all"); // ✅ 修正点1
// 	if (!allTech || !allTech.checked) {
// 		techDomains = techFields.value.filter(item => item.checked && item.id !== "all").map(item => item.id); // 注意：这里 map 的是 value，假设后端需要的是 value 字段
// 	}

// 	let controls = [];
// 	const allReason = controlReason.value.find(item => item.id === "all"); // ✅ 修正点2
// 	if (!allReason || !allReason.checked) {
// 		controls = controlReason.value.filter(item => item.checked && item.id !== "all").map(item => item.id);
// 	}
// 	// let techDomains = techFields.value.filter(item => item.checked).map(item => +item.id);
// 	// let controls = controlReason.value.filter(item => item.checked).map(item => +item.id);
// 	const params = {
// 		categoryCode: currentCCLType.value,
// 		techDomainIds: techDomains,
// 		keyword: searchKeyword.value || "",
// 		controlIds: controls,
// 		isLatest: viewNew.value,
// 		recordId: currentCCLVersion.value || ""
// 	};
// 	console.log("cclList参数:", params);
// 	try {
// 		const res = await getCclQuery(params);

// 		if (res && res.code === 200) {
// 			console.log("----getCclList", res.data);
// 			cclList.value = res.data;
// 			// 给数据添加isExpand字段
// 			cclList.value.forEach(item => {
// 				item.isExpand = true;
// 				item.cclChildren.forEach(ele => {
// 					ele.cclChildren.forEach(i => {
// 						i.isExpand = false;
// 					});
// 				});
// 			});
// 		}
// 	} catch (error) {
// 		console.error("获取ccl清单列表失败:", error);
// 	}
// };

// 获取 ccl 清单列表
const getCclList = async () => {
	let techDomains = [];
	const allTech = techFields.value.find(item => item.id === "all");
	if (!allTech || !allTech.checked) {
		techDomains = techFields.value.filter(item => item.checked && item.id !== "all").map(item => item.id);
	}

	let controls = [];
	const allReason = controlReason.value.find(item => item.id === "all");
	if (!allReason || !allReason.checked) {
		controls = controlReason.value.filter(item => item.checked && item.id !== "all").map(item => item.id);
	}

	const params = {
		categoryCode: currentCCLType.value,
		techDomainIds: techDomains,
		keyword: searchKeyword.value || "",
		controlIds: controls,
		isLatest: viewNew.value,
		recordId: currentCCLVersion.value || ""
	};

	try {
		const res = await getCclQuery(params);
		if (res && res.code === 200) {
			console.log("----getCclList", res.data);
			cclList.value = res.data;

			// ✅ 新增：处理 changeFlag 向上继承逻辑
			cclList.value.forEach(item => {
				item.isExpand = true;
				item.changeFlag = false; // 初始化第一层

				item.cclChildren.forEach(ele => {
					ele.changeFlag = false; // 初始化第二层

					ele.cclChildren.forEach(i => {
						i.isExpand = false;
						// 如果第三层有 changeFlag 为 true，标记第二层
						if (i.changeFlag) {
							ele.changeFlag = true;
						}
					});

					// 如果第二层 changeFlag 为 true，标记第一层
					if (ele.changeFlag) {
						item.changeFlag = true;
					}
				});
			});

			console.log("----getCclList 11", cclList.value);
		}
	} catch (error) {
		console.error("获取 ccl 清单列表失败:", error);
	}
};

// 商业管制清单-CCL清单列表-清单版本
const cclVersionList = ref([]);
// 当前选中的清单版本
const currentCCLVersion = ref("");
// 获取清单版本列表
const getCCLVersionListApi = async () => {
	try {
		const res = await getCCLVersionList();
		if (res && res.code === 200) {
			console.log("----getCCLVersionList", res.data);
			cclVersionList.value = res.data.map(item => {
				return {
					key: item.key,
					value: `清单版本-${dayjs(item.value).format("YYYY年MM月DD日")}`
					// value: `清单版本-${item.value}`
				};
			});
			currentCCLVersion.value = res.data[0].key;
		}
	} catch (error) {
		console.error("获取清单版本列表失败:", error);
	}
};

// 筛选逻辑处理
const handleFilterChange = (item, listRef, type) => {
	const list = listRef;
	const allItem = list.find(i => i.id === "all"); // ✅ 关键修正
	if (!allItem) return;

	if (item.id === "all") {
		if (item.checked) {
			list.forEach(i => {
				if (i.id !== "all") i.checked = false;
			});
		} else {
			const hasOtherChecked = list.some(i => i.id !== "all" && i.checked);
			if (!hasOtherChecked && list.length > 1) {
				const firstNonAll = list.find(i => i.id !== "all");
				if (firstNonAll) firstNonAll.checked = true;
			}
		}
	} else {
		if (item.checked) {
			allItem.checked = false;
		} else {
			const hasAnyChecked = list.some(i => i.id !== "all" && i.checked);
			if (!hasAnyChecked) {
				allItem.checked = true;
			}
		}
	}

	getCclList();
};

watch(viewNew, newValue => {
	getCclList();
});

watch(currentCCLType, newValue => {
	console.log(newValue);
	getCclList();
});

watch(currentCCLVersion, newValue => {
	console.log(newValue);
	getCclList();
});

// const searchDebounceTimer = ref(null);
// watch(searchKeyword, () => {
//   if (searchDebounceTimer.value) {
//     clearTimeout(searchDebounceTimer.value);
//   }
//   searchDebounceTimer.value = setTimeout(() => {
//     currentPage.value = 1;
//     getExportControlListApi();
//   }, 300);
// });
watch(searchKeyword, newValue => {
	console.log("-----searchKey", newValue);
	getCclList();
});

// 模拟清单列表
const cclList = ref([
	{
		name: "类别 0-核材料、设施和设备、枪支、弹药[以及其他物品]",
		desc: 'A."最终产品"、"设备"、"附件"、"附加装置"、"零件"、"组件"和"系统"',
		isExpand: true,
		list: [
			{
				code: "0A002",
				name: '发电或推进设备，"专门设计"用于与太空、海洋或移动"核反应堆"一起使用。（这些项目"受 ITAR 管辖。"参见 22 CFR 第 120 至 130 部分。）',
				isExpand: false,
				isDot: false
			},
			{
				code: "0A501",
				name: "枪支（不包括 0A502 霰弹枪、0A506 半自动步枪、0A507 半自动手枪和 0A508 半自动霰弹枪）及相关商品（不包括在 Eccn 0A509 中列举或以其他方式描述的与半自动相关的商品，用于 Eccn 0A506、0A507 或 0A508）如下（参见受控物品清单）",
				isExpand: true,
				isDot: true
			},
			{
				code: "0A501",
				name: "枪支（不包括 0A502 霰弹枪、0A506 半自动步枪、0A507 半自动手枪和 0A508 半自动霰弹枪）及相关商品（不包括在 Eccn 0A509 中列举或以其他方式描述的与半自动相关的商品，用于 Eccn 0A506、0A507 或 0A508）如下（参见受控物品清单）",
				isExpand: false,
				isDot: true
			}
		]
	}
]);

onMounted(async () => {
	// 获取类别字段
	await getTypeList();
	// 获取科技领域字典
	await getTechFields();
	// 获取管控原因字典
	await getControlReasonList();
	// 获取ccl清单列表
	getCclList();
	// 获取清单版本列表
	getCCLVersionListApi();
});
</script>

<style scoped lang="scss">
// * {
// 	margin: 0;
// 	padding: 0;
// }

.list-page {
	width: 1601px;
	padding-bottom: 50px;
	margin: 0 auto;
	padding-top: 16px;

	.search-box {
		margin-bottom: 16px;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.search-input {
			width: 388px;
			height: 32px;

			:deep(.el-input__wrapper) {
				padding: 0 11px;
				// border: 1px solid rgba(0, 0, 0, 0.2);
				background-color: #fff;
				border-radius: 3px;
			}

			:deep(.el-input__inner) {
				// font-size: 16px;
				font-weight: 400;
				font-family: "Microsoft YaHei";
				line-height: 24px;
				color: rgb(95, 101, 108);
			}
		}

		.filters {
			display: flex;
			align-items: center;

			.el-checkbox {
				margin-right: 20px;
				color: rgb(59, 65, 75);
			}

			.time-select {
				width: 160px;
				height: 32px;
			}

			:deep(.el-select) {
				.el-select__placeholder {
					color: rgb(95, 101, 108); // 修改 placeholder 文字颜色
					// font-size: 16px; // 修改字体大小
					font-family: "Microsoft YaHei";
					font-weight: 400;
				}

				.el-input__inner {
					// font-size: 16px;
					font-family: "Microsoft YaHei";
					color: rgb(95, 101, 108);
				}
			}
		}
	}

	.main {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: flex-start;

		.left {
			padding-bottom: 20px;
			width: 388px;
			height: auto;
			border-radius: 10px;
			box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
			background-color: #fff;

			.checkbox-group {
				display: flex;
				flex-wrap: wrap;
				padding: 0 0 0 24px;

				.el-checkbox {
					width: 50%;
					margin-right: 0;
					margin-bottom: 4px;
					font-size: 16px;
					font-weight: 400;
					font-family: "Microsoft YaHei";
					line-height: 24px;
					color: rgb(95, 101, 108);
				}

				.custom-date-picker {
					width: 100%;
					margin-top: 8px;
					padding-right: 24px;
					box-sizing: border-box;

					:deep(.el-date-editor) {
						width: 100%;
						height: 32px;
						box-shadow: none;
						border: 1px solid #dcdfe6;
						border-radius: 4px;
						padding: 0 10px;

						&:hover {
							border-color: #c0c4cc;
						}

						&.is-active {
							border-color: #409eff;
						}

						.el-range-input {
							font-size: 14px;
							font-family: "Microsoft YaHei";
							color: rgb(95, 101, 108);
						}

						.el-range-separator {
							color: rgb(95, 101, 108);
							line-height: 30px;
						}

						.el-input__icon {
							line-height: 32px;
							color: rgb(95, 101, 108);
						}
					}
				}
			}
		}

		.right {
			width: 1196px;
			height: auto;
			.title {
				width: 100%;
				height: 56px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 14px 12px 16px 0;
				box-sizing: border-box;

				.left-wrapper {
					display: flex;
					align-items: center;

					.box {
						width: 8px;
						height: 20px;
						background-color: rgb(5, 95, 194);
						border-bottom-right-radius: 4px;
						border-top-right-radius: 4px;
						margin-right: 14px;
					}

					.text {
						font-size: 20px;
						font-weight: 700;
						font-family: "Microsoft YaHei";
						line-height: 26px;
						color: rgb(5, 95, 194);
					}
				}

				.right-wrapper {
					display: flex;
					align-items: center;

					.stats {
						display: flex;
						align-items: center;
						margin-right: 24px;

						span {
							font-size: 16px;
							font-weight: 400;
							font-family: "Microsoft YaHei";
							line-height: 24px;
							margin-left: 4px;
							color: rgb(95, 101, 108);
						}
					}

					.btn {
						width: 60px;
						height: 28px;

						img {
							width: 28px;
							height: 28px;
							cursor: pointer;
						}

						img:first-child {
							margin-right: 4px;
						}
					}
				}
			}

			.right-table {
				margin-top: 11px;
				padding: 5px 21px 0 21px;
				max-height: 1987px;
				overflow: auto;
				box-sizing: border-size;
				// background: red;

				.list {
					width: 100%;
					height: auto;
					margin-bottom: 14px;

					.list-title {
						width: 100%;
						height: 54px;
						background: rgb(5, 95, 194);
						color: white;
						padding: 14px 23px 16px 29px;
						display: flex;
						align-items: center;
						justify-content: space-between;
						border-radius: 4px;

						span {
							font-family: Microsoft YaHei;
							font-style: Bold;
							font-size: 18px;
							font-weight: 700;
							line-height: 24px;
							letter-spacing: 0px;
							text-align: left;
						}
					}
					.dot {
						width: 8px;
						height: 8px;
						border-radius: 50%;
						border: 2px solid rgb(206, 79, 81);
						background-color: rgb(206, 79, 81);
						z-index: 1;
						position: absolute;
						left: 10px;
						top: 8px;
					}

					.list-desc {
						margin-left: 28px;
						margin-top: 14px;
						margin-bottom: 16px;
						font-family: Microsoft YaHei;
						font-style: Bold;
						font-size: 16px;
						font-weight: 700;
						line-height: 24px;
						letter-spacing: 0px;
						text-align: left;
						color: black;
					}

					.list-content {
						width: 100%;
						margin-bottom: 12px;

						.content-title {
							background: rgb(234, 236, 238);
							display: flex;
							align-items: flex-start;
							justify-content: space-around;
							// padding: 9px 0px;
							position: relative;
							.code-zone {
								width: 75px;
								display: flex;
								margin-top: 11px;
								align-items: center;
								justify-content: space-around;

								.dot {
									width: 8px;
									height: 8px;
									border-radius: 50%;
									border: 2px solid rgb(206, 79, 81);
									background-color: rgb(206, 79, 81);
									z-index: 1;
									position: absolute;
									left: 10px;
									top: 20px;
								}

								.code {
									font-family: Microsoft YaHei;
									font-style: Bold;
									font-size: 16px;
									font-weight: 700;
									line-height: 26px;
									letter-spacing: 0px;
									text-align: left;
									color: rgba(59, 65, 75, 1);
								}
							}

							.name {
								width: 984px;
								margin-top: 9px;
								font-family: Microsoft YaHei;
								font-style: Regular;
								font-size: 16px;
								font-weight: 400;
								line-height: 30px;
								letter-spacing: 0px;
								text-align: justify;
								color: rgba(59, 65, 75, 1);
							}

							img {
								margin-top: 20px;
							}
						}

						.content-body {
							margin-left: 90px;
							// margin-right: 92px;

							img {
								width: 984px;
								height: 1047px;
							}
						}
					}
				}
			}

			.tight-footer {
				padding: 16px 24px;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.total-text {
					font-size: 14px;
					font-weight: 400;
					color: #5f656c;
					font-family: "Microsoft YaHei";
				}

				:deep(.el-pagination) {
					--el-pagination-button-bg-color: #fff;
					--el-pagination-hover-color: #0e78f1;
					--el-pagination-font-size: 14px;

					.el-pager li {
						border: 1px solid #dcdfe6;
						border-radius: 4px;
						margin: 0 4px;
						font-weight: 400;
						color: #5f656c;
						min-width: 32px;
						height: 32px;
						line-height: 30px;

						&.is-active {
							background-color: #0e78f1;
							color: #fff;
							border-color: #0e78f1;
						}

						&:hover:not(.is-active) {
							color: #0e78f1;
							border-color: #0e78f1;
						}
					}

					.btn-prev,
					.btn-next {
						border: 1px solid #dcdfe6;
						border-radius: 4px;
						padding: 0;
						margin: 0 4px;
						min-width: 32px;
						height: 32px;
						line-height: 30px;
						text-align: center;

						&:hover {
							color: #0e78f1;
							border-color: #0e78f1;
						}

						&[disabled] {
							border-color: #e4e7ed;
							color: #c0c4cc;
						}
					}
				}
			}
		}
	}
}

.title {
	width: 100%;
	height: 56px;
	display: flex;
	align-items: center;
	padding: 14px 12px 16px 0;

	.box {
		width: 8px;
		height: 16px;
		background-color: rgb(5, 95, 194);
		border-bottom-right-radius: 4px;
		border-top-right-radius: 4px;
		margin-right: 14px;
	}

	.text {
		font-size: 16px;
		font-weight: 700;
		font-family: "Microsoft YaHei";
		line-height: 24px;
		color: rgb(5, 95, 194);
	}
}
</style>
