<template>
	<view class="tree_container">
		<block v-for="item in $props.treeData" :key="item.id">
			<view class="">
				<view :class="{'tree_label': true, 'active': item.id === $props.activeId}" @click="nodeClick(item)">
					<template v-if="item.children && item.children.length > 0">
						<view class="tree_icon">
							<view :class="{'icon': true ,'down': isOpen(item.id)}">
								<u-icon name="arrow-down-fill" color="#adafb6" size="26"></u-icon>
							</view>
						</view>
					</template>
					<text>{{item.title}}</text>
				</view>

				<!-- #ifdef H5 -->
				<view class="tree_item" :style="{'grid-template-rows': isOpen(item.id) ? '1fr' : '0fr'}">
				<!-- #endif -->

					<!-- #ifdef APP -->
					<view class="tree_item" :style="{'display': isOpen(item.id) ? 'block' : 'none'}">
					<!-- #endif -->

						<!-- #ifdef MP-WEIXIN -->
						<view class="tree_item" :style="{'display': isOpen(item.id) ? 'block' : 'none'}">
						<!-- #endif -->
							<template v-if="item.children && item.children.length > 0">
								<MyTree :treeData="item.children" @node-click="$emit('node-click', $event)"
									:activeId="$props.activeId"></MyTree>
							</template>
						</view>
					</view>
		</block>
	</view>
</template>

<script setup lang="ts">
	import { defineProps, ref } from 'vue';

	const $props = defineProps(["treeData", 'activeId'])
	console.log('$props :>> ', $props);
	const $emit = defineEmits(["node-click"])

	const expandedKeys = ref([])
	const treeData = $props.treeData


	const isOpen = (id) => {
		// 判断节点id在不在数组中，在则显示，不在则隐藏
		return expandedKeys.value.includes(id)
	}


	const nodeClick = (item) => {
		$emit("node-click", item)

		if (item.children && item.children.length) {
			let index = expandedKeys.value.indexOf(item.id)
			if (index > -1) {
				// 如果当前节点id存在数组中，则删除
				expandedKeys.value.splice(index, 1)
			} else {
				// 如果当前节点id不存在数组中，则添加
				expandedKeys.value.push(item.id)
			}
		}

	}
</script>

<style scoped lang="scss">
	.tree_label {
		padding: 10upx 40upx;
		position: relative;

		&.active {
			background-color: var(--subjectColor);
			border-radius: 10upx;
			color: #fff;


			:deep(.u-icon__icon) {
				color: #fff !important;
			}
		}
	}

	.tree_item {
		margin-top: 10upx;
		padding-left: 40upx;
	}

	// 头部搜索
	.tree_item {
		display: grid;
		grid-template-rows: 0fr;
		transition: all 0.3s;
		// overflow: hidden;

		&>view {
			min-height: 0;
			overflow: hidden;
		}

		// &>div,
		// &>form {
		// }
	}

	.tree_icon {
		position: absolute;
		left: 5upx;
		top: 50%;
		transform: translateY(-50%);
		margin-right: 20upx;
		transform-origin: center;

		.icon {
			transition: all 0.3s;
			transform: rotate(-90deg);
		}

		.down {
			transform: rotate(0deg);
		}
	}
</style>