<template>
	<!-- 听力 -->
	<view>
		<!-- 外层循环 -->
		<view v-for="(item,index) in listHearing" :key="item.id">
			<!-- 听力标题渲染 -->
			<view class="view_bages">
				<view>{{item.title}}</view>
			</view>
			<view class="substance">
				<!-- 渲染Text -->
				<text :class="{ 'active': itemActive[item.id] === TextIndex  }"
					v-for="(TextItem,TextIndex) in item.tests" :key="TextIndex"
					@click="Bages_addActive(TextIndex,item.id) ">
					{{TextItem.name}}
				</text>
			</view>
			<!-- 渲染part -->
			<view v-for="(TextItem,TextIndex) in item.tests" :key="TextIndex">
				<view v-for="(partitem,partindex) in TextItem.parts" :key="partindex"
					v-if="itemActive[item.id] === TextIndex">
					<view>
						<view class="Part1">
							<view class="imaflex" @click="icon(partitem.id)">
								<!-- part前面的图表 -->
								<view class="image">
									<image src="http://tmp/IFVuR12hLLNO034931f24322ab271b1f57fdf626bcbf.png" mode=""
										v-if="image"></image>
									<image src="http://tmp/8OOgvfEpdnT2e4e421b97006c70b30a9df99e51a6df1.png" mode=""
										v-else></image>
								</view>
								<view>{{partitem.name}}</view>
							</view>
							<!-- part的多选框 -->
							<view>
								<u-checkbox  @change="checkboxChange(partitem,$event)"  v-model="partitem.checked"
									shape="circle"></u-checkbox>
							</view>
						</view>
						<view class="partshow" v-if="selectedItems.includes(partitem.id)">
							<view class="Part2" v-for="(quesitem,quesindex) in partitem.modules" :key="quesindex">
								<view class="imaflex">
									<view>{{quesitem.number}}{{quesitem.typeText}}</view>
								</view>
								<view>
									<u-checkbox @change="handleCheckboxChange(quesitem)"
										v-model="quesitem.subsets"></u-checkbox>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				listHearing: [],
				checked: [],
				subsets: [],
				itemActive: {},
				image: true,
				tk: null,
				selectwrite: [],
				selectedItems: [],

			}
		},
		created() {
			this.hearing()
		},
		methods: {
			updatawrite(data){
				this.selectwrite=data
				
			},
			// 听力调取接口渲染
			hearing() {
				this.$u.get('https://api.admin-v2.langsi.online/admin-api/ielts/paper/list', {
					classify: 2
				}).then(res => {
					this.listHearing = res.data
					let activeindex = {}
					let arr = res.data
					for (let parper of arr) {
						let test = parper.tests[0]
						activeindex[parper.id] = 0
					}
					this.itemActive = activeindex
					this.updateSubsetsInListHearing()
				const uniquePartIds = new Set();
				
				// Loop through listHearing and collect unique part IDs
				this.listHearing.forEach((paper) => {
				  paper.tests.forEach((test) => {
				    test.parts.forEach((part) => {
				      const hasSelectedQuesitem = part.modules.some((quesitem) => quesitem.subsets);
				      
				      if (hasSelectedQuesitem) {
				        uniquePartIds.add(part.id);
				      }
				    });
				  });
				});
				
				// Convert the Set to an array and update selectedItems
				this.selectedItems = Array.from(uniquePartIds);
						console.log( this.selectedItems ,' this.selectedItems ');
				})
			},
			// 听力test点击事件
			Bages_addActive(TextIndex, id) {
				this.itemActive[id] = TextIndex
				this.$forceUpdate()
			},
			// 点击变化图表
			 icon(id) {
			    this.image = !this.image;
			    if (this.image) {
			      this.selectedItems = this.selectedItems.filter(item => item !== id);
			    } else {
			      this.selectedItems.push(id);
			    }
				console.log(this.selectedItems,'this.selectedItemsthis.selectedItems');
			  },
			checkboxChange(partitem, e) {
				if (e.value) {
					this.listHearing.forEach((paper) => {
						paper.tests.forEach((test, testIndex) => {
							test.parts.forEach((part) => {
								if (part.id === partitem.id) {
									part.modules.forEach((quesitem, quesIndex) => {
										this.addToSelectWrite(
											quesitem,
											partitem.id,
											testIndex + 1,
											paper.title
										);
									});
								}
							});
						});
					});
				} else {
					partitem.modules.forEach((quesitem) => {
						this.removeFromSelectWrite(quesitem.id);
					});
				}
				this.$forceUpdate();
				

				// 在这里执行额外的操作，遍历 selectwrite 中的每一项，更新 listHearing 中的 subsets
				this.updateSubsetsInListHearing();
					this.$parent.updataread(this.selectwrite)
			},
			handleCheckboxChange(quesitems) {
				const existingIndex = this.selectwrite.findIndex(item => item.id === quesitems.id);

				if (existingIndex !== -1) {
					// 如果已存在，将 subsets 设为 false，并清除该项
					this.selectwrite.splice(existingIndex, 1);
					quesitems.subsets = false;
				} else {
					// 如果不存在，添加该项，并将 subsets 设为 true
					this.listHearing.forEach((paper) => {
						paper.tests.forEach((test, testIndex) => {
							test.parts.forEach((part) => {
								part.modules.forEach((quesitem, quesIndex) => {
									if (quesitem.id == quesitems.id) {
										this.addToSelectWrite(
											quesitems,
											quesitems.id, // 使用 quesitem 的 id
											testIndex + 1, // 使用内层循环的 testIndex
											paper.title // 使用 quesitem 的 paperTitle
										);
									}
								});
							});
						});
					});
					quesitems.subsets = true;
				}

				console.log(this.selectwrite, 'selectwriteselectwrite');
				this.updateSubsetsInListHearing()
				this.$parent.updataread(this.selectwrite)
			},



			// 在这里添加一个新的方法，用于更新 listHearing 中的 subsets
			updateSubsetsInListHearing() {
				this.listHearing.forEach((paper) => {
					paper.tests.forEach((test) => {
						test.parts.forEach((part) => {
							part.modules.forEach((quesitem) => {
								const selected = this.selectwrite.find((item) => {
									return item.id === quesitem.id;
								});
								if (selected) {
									quesitem.subsets = true;
								} else {
									quesitem.subsets = false;
								}
							});
						});
					});
				});

				// 额外的逻辑，遍历 listHearing 中的每一个 part，判断是否全部 modules 的 subsets 都为 true
				this.listHearing.forEach((paper) => {
					paper.tests.forEach((test) => {
						test.parts.forEach((part) => {
							part.checked = part.modules.every((quesitem) => quesitem.subsets);
						});
					});
				});
				console.log(this.selectwrite,'selectwriteselectwrite');
				
			},

			// 添加信息到selectwrite数组
			addToSelectWrite(quesitem, partId, testIndex, paperTitle) {
				// Split the guideText into words
				
				const item = {
					id: quesitem.id,
					paperId: quesitem.paperId,
					papername: paperTitle,
					partId: partId,
					testId: quesitem.testId,
					testname: `Test ${testIndex}`,
					typeName: quesitem.typeText,
					questionname: quesitem.number,
				};

				this.selectwrite.push(item);
			},

			removeFromSelectWrite(itemId) {
				const index = this.selectwrite.findIndex((item) => item.id === itemId);
				if (index !== -1) {
					this.selectwrite.splice(index, 1);
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.view_bages {
		font-size: 40rpx;
		font-weight: 400;
		color: #2E4975;
	}

	.substance {
		margin: 20rpx 0;

		text {
			padding: 10rpx 30rpx;
			margin-right: 20rpx;
			background: #FFFFFF;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
		}

	}




	.Part1 {
		display: flex;
		justify-content: space-between;
		padding: 24rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		margin-top: 30rpx;
	}

	.Part2 {
		display: flex;
		justify-content: space-between;
		padding: 24rpx 0;
		border-bottom: 2rpx solid #F2F2F2;
	}

	.partshow {
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		margin-top: 15rpx;
		padding: 15rpx 30rpx;
	}

	.substance .active {
		background: #2D7CE6;
		color: #fff;
	}

	.imaflex {
		display: flex;
	}

	.image {
		width: 20rpx;
		height: 20rpx;
		margin-right: 10rpx;
	}
</style>