<template>
	<view class="index_main" :style="{minHeight:screenH + 'px'}">
		<view class="back-top"></view>
		<!-- 轮播图 -->
		<view class="swiper_nav">
			<swiper autoplay :duration="1000">
				<swiper-item v-for="(item, index) in swiperImg" :key="index">
					<image :src="item" style="width: 100%;height: 100%;"></image>
				</swiper-item>
			</swiper>
		</view>
		<!-- 皖送e餐 志愿者服务 -->
		<view class="main_menu" v-if="showFirstMenus">
			<view class="main_menu_item" v-for="(item,index) in firstMenus" :key="index" v-if="item.visible" @click="jumpRouter(item)">
				<image :src="item.icon"></image>
				<view class="main_menu_name">{{item.name}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getAppUserPermissionInfo,
		getUserInfo
	} from '@/common/api.js';
	import {
		callbackRequest,
		callbackRequestNoLoading,
		setStorage,
		getStorage,
		// alertTip
	} from '@/common/util.js';
	export default {
		data() {
			return {
				screenH: '',
				swiperImg: [
					require('@/static/images/system/top.png')
				],
				permissions: [],
				roleList: [],
				firstMenus: [],
				secondMenus: [],
				showFirstMenus: true
			}
		},
		onLoad() {
			// this.getAppUserPermissionInfo()
			// this.getUserInfo()
		},
		mounted() {
			uni.getSystemInfo({
				success: (res) => {
					this.screenH = res.windowHeight
				}
			});
		},
		methods: {
			// 菜单权限
			getAppUserPermissionInfo() {
				setStorage('userInfo', 'a866a82704044ae0a1a12ddc2a2e4346')
				let userId = getStorage('userInfo') ? getStorage('userInfo') : 'a866a82704044ae0a1a12ddc2a2e4346';
				callbackRequest({
					method: getAppUserPermissionInfo,
					userId: userId,
				}).then(res => {
					uni.hideLoading();
					if (res.returnCode == 1) {
						let returnData = res.returnData;
						this.permissions = returnData.appMenus.length > 0 ? returnData.appMenus : [];
						this.roleList = returnData.roles;
						uni.setStorageSync('permissions', this.permissions);
						this.$nextTick(() => {
							this.handleMenus();
							uni.setStorageSync('roles', returnData.roles);
						});
					} else {
						uni.showToast({title: '权限获取失败',icon: 'none',duration: 2000})
					}
				});
			},
			
			getUserInfo() {
				return new Promise((resove, reject) => {
					let params = {
						method: getUserInfo,
					}
					callbackRequest(params).then(res => {
						let userinfo = res.returnData
						uni.setStorageSync('userInfos', userinfo)
						resove()
					});
				})
			},
			
			jumpRouter(row) {
				if(row.path == 'wan_e_food') {
          this.$tab.navigateTo('/pages/index')
				}
				if(row.path == 'wan_e_food') {
					
				}
				if(row.path == 'stage') {
					// uni.navigateTo({
					// 	url: '/pages/stage/index',
					// 	success: (res) => {
					// 		 res.eventChannel.emit('pagesChange', { data: row.children })
					// 	}
					// })
				}
			},
			
			handleMenus() {
				let chunkSize = 8;
				// 一级菜单
				let firstMenusTemp = [];
				// 二级菜单
				let secondMenusTemp = [];
				// 首页菜单
				let permissionsOfIndex = this.permissions.filter(item => item.path == 'app_index' && item.visible);
				// 过滤掉首页菜单
				let permissionsOfOther = this.permissions.filter(item => item.path != 'app_index');
				let showBanner = false;
				console.log('一级菜单',permissionsOfIndex)
				if (permissionsOfIndex && permissionsOfIndex.length > 0) {
					if (permissionsOfIndex[0].children && permissionsOfIndex[0].children.length > 0) {
						permissionsOfIndex[0].children.forEach(child => {
							// 首页轮播图
							if (child.path == "top_banners" && child.visible) {
								showBanner = true;
							}
							// 一级菜单
							if (child.path == "first_menus" && child.visible) {
								firstMenusTemp = child.children;
							}
						})
					}
				}
				this.firstMenus = firstMenusTemp;
				for (var i = 0; i < permissionsOfOther.length; i ++) {
					secondMenusTemp.push(permissionsOfOther[i]);
				}
				
				this.secondMenus = secondMenusTemp;
				console.log('二级菜单', this.secondMenus)
				
				if (this.secondMenus.length == 1) {
					// let params = !this.secondMenus[0][0].children ? '' : this.secondMenus[0][0].children[0].path;
					let params = this.getLastPathBtn(permissionsOfOther)
					let rolePath = this.getLastPath(permissionsOfOther)
					console.log('直跳截取处理', params, rolePath)
					if (rolePath) {
						let path = rolePath.replace(/\?+$/, ''); // 去掉结尾的所有问号
						// 检查问号，选择合适的拼接符
						let delimiter = path.includes('?') ? '&' : '?';
						// 拼接最终的 URL
						let url = path + delimiter + 'role=' + params;
						uni.redirectTo({
							url: url
						})
					}
					return;
				}
				
				if (firstMenusTemp.length == 0 || !showBanner) {
					// this.images = [
					// 	this.defaultBanner
					// ];
				}
				// 2.没有配置一级菜单时，隐藏一级菜单
				this.showFirstMenus = firstMenusTemp.length == 0 ? false : true;
			},
			
			getLastPathBtn(tree) {
				if (!Array.isArray(tree) || tree.length !== 1) {
					return false;
				}
				const rootNode = tree[0];
				if (!rootNode.path || !rootNode.children || rootNode.children.length !== 1) {
					return false;
				}
				function traverse(node) {
					if (node.children && node.children.length === 1) {
						return traverse(node.children[0]);
					} else if (node.children && node.children.length > 1) {
						return false;
					} else {
						return node.path;
					}
				}
				return traverse(rootNode);
			},
			
			getLastPath(tree) {
				let lastPath = null;
				let _this = this
			
				function traverse(node) {
					// 如果当前节点是我们想要的类型，更新最后的路径 type 1目录 2菜单 3按钮
					// 如果当前节点是我们想要的类型，更新最后的路径
					if (node.type == 2) {
						lastPath = node.path;
					}
			
					// 递归遍历子节点
					if (node.type == 2 && node.children && node.children.length == 1) {
						// 当数组是菜单且子节点长度等于1的时候，继续往下递归数组，说明当前数组不是最后一层
						for (let child of node.children) {
							traverse(child);
						}
					} else if (node.type == 2 && node.children && node.children.length > 1 && _this.someTypeTrue(node.children)) {
						console.log('1111', node)
						// 当数组是菜单且子节点长度大于1的时候，就得看下面的子节点是否为都是按钮,都是按钮则返回当前路径
						lastPath = false
					} else if (node.type == 2 && node.children && node.children.length > 1 && !_this.someTypeTrue(node.children)) {
						console.log('2222', node)
						lastPath = node.path;
					} else {
						console.log('3333', node)
						lastPath = lastPath
					}
				}
			
				// 遍历每个根节点
				for (let root of tree) {
					traverse(root);
				}
			
				return lastPath;
			},
			
			// 判断下一层子节点是否全是按钮
			someTypeTrue(arr) {
				const result = arr.some(item => item.type == 3) ? false : true;
				return result
			},
			
			jumpPage(item) {
				if(!item.path) {
          uni.showToast({
            title: '敬请期待',
            icon: 'none'
          })
					return
				}
				uni.navigateTo({
					url: item.path
				})
			}
		}
	}
</script>

<style scoped lang="scss">
.index_main {
	background: #F2F6FA;
	overflow: auto;
	padding: 24rpx 0;
	box-sizing: border-box;
}
.back-top {
	position: fixed;
	width: 100%;
	height: 578rpx;
	background: linear-gradient( 180deg, #D2EAFF 0%, rgba(208,233,254,0) 100%);
	top: 0;
	left: 0;
}
.swiper_nav {
	width: 100%;
	height: 300rpx;
	background: #FFFFFF;
	border-radius: 20rpx;
	padding: 0 24rpx;
	box-sizing: border-box;
}
.main_menu {
	display: flex;
	justify-content: space-between;
	margin-top: 24rpx;
	padding: 0 12rpx;
	box-sizing: border-box;
}
.main_menu_item {
	z-index: 99;
	margin: 0 12rpx;
	padding: 28rpx 0;
	flex: 1;
	height: 208rpx;
	background: #FFFFFF;
	border-radius: 20rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: space-between;
	.main_menu_name {
		font-family: PingFang SC, PingFang SC;
		font-weight: bold;
		font-size: 30rpx;
		color: #0E1A24;
		font-style: normal;
		text-transform: none;
	}
	image {
		display: flex;
		width: 88rpx;
		height: 88rpx;
		border-radius: 34rpx;
	}
}
.yiz_menu {
	width: calc(100% - 48rpx);
	min-height: 480rpx;
	background: #FFFFFF;
	border-radius: 20rpx;
	margin-top: 24rpx;
	margin-left: 24rpx;
}
.yiz_menu_tle {
	font-family: PingFang SC, PingFang SC;
	font-weight: bold;
	font-size: 32rpx;
	color: #0E1A24;
	font-style: normal;
	text-transform: none;
	padding: 28rpx 28rpx 0 28rpx;
}
.yiz_menu_nav {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	.yiz_menu_nav_item {
		width: calc(100% / 4);
		margin-top: 48rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		image {
			display: block;
			width: 88rpx;
			height: 88rpx;
			border-radius: 34rpx;
		}
		.yiz_menu_name {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #0E1A24;
			font-style: normal;
			text-transform: none;
			margin-top: 20rpx;
		}
	}
}
</style>
