<template>
	<view class="container">
		<view class="line"></view>
		<view class="show-selected">
			<view class="title-selected">已选择：</view>
			<view class="air-selected-name">{{show_airs}}</view>
		</view>
		<view class="btn">
			<view class="btn-bg" @tap="confirm_selection">确认选择</view>
		</view>
		<view class="line"></view>
		<view class="title-tip">请选择</view>
		<view class="line"></view>
		<view class="tree-box">
			<scroll-view scroll-y="true" class="tree-scroll" :style="{height: screenHeight}">
				<view class="item-loudong" v-for="(item1, index1) in treeData" :key="index1">
					<view class="loudong" :id="item1.id" @tap="handle_toggle_items">
						<view class="title-loudong">
							<uni-icons type="plus-filled" size="22" color="#2979ff"
								:style="{display: item1.isShow ? 'none' : ''}"></uni-icons>
							<uni-icons type="minus-filled" size="22" color="#2979ff"
								:style="{display: item1.isShow ? '' : 'none'}"></uni-icons>
							<view class="txt-loudong">{{item1.label}}</view>
						</view>
						<uni-icons type="bottom" size="22" color="#2979ff"
							:style="{display: item1.isShow ? '' : 'none'}"></uni-icons>
						<uni-icons type="top" size="22" color="#2979ff" :style="{display: item1.isShow ? 'none' : ''}">
						</uni-icons>
					</view>
					<view class="item-loucheng" v-for="(item2, index2) in item1.children" :key="index2"
						:style="{display: item1.isShow ? '' : 'none'}">
						<view class="loucheng" :id="item2.id" @tap="handle_toggle_items">
							<view class="title-loucheng">
								<uni-icons type="plus-filled" size="22" color="#2979ff"
									:style="{display: item2.isShow ? 'none' : ''}"></uni-icons>
								<uni-icons type="minus-filled" size="22" color="#2979ff"
									:style="{display: item2.isShow ? '' : 'none'}"></uni-icons>
								<view class="txt-loucheng">{{item2.label}}</view>
							</view>
							<uni-icons type="bottom" size="22" color="#2979ff"
								:style="{display: item2.isShow ? '' : 'none'}"></uni-icons>
							<uni-icons type="top" size="22" color="#2979ff"
								:style="{display: item2.isShow ? 'none' : ''}"></uni-icons>
						</view>
						<view class="item-jiaoshi" v-for="(item3, index3) in item2.children" :key="index3"
							:style="{display: item2.isShow ? '' : 'none'}">
							<view class="jiaoshi" :id="item3.id" @tap="handle_toggle_items">
								<view class="title-jiaoshi">
									<uni-icons type="plus-filled" size="22" color="#2979ff"
										:style="{display: item3.isShow ? 'none' : ''}"></uni-icons>
									<uni-icons type="minus-filled" size="22" color="#2979ff"
										:style="{display: item3.isShow ? '' : 'none'}"></uni-icons>
									<view class="txt-jiaoshi">{{item3.label}}</view>
								</view>
								<uni-icons type="bottom" size="22" color="#2979ff"
									:style="{display: item3.isShow ? '' : 'none'}"></uni-icons>
								<uni-icons type="top" size="22" color="#2979ff"
									:style="{display: item3.isShow ? 'none' : ''}"></uni-icons>
							</view>
							<view v-for="(item4, index4) in item3.children" :key="index4"
								:style="{display: item3.isShow ? '' : 'none'}">
								<view class="item-kongtiao" v-if="item4.isUsering">
									<view :style="{color: item4.isUsering ? '#747578' : '#2979ff'}">
										{{item4.label}}（使用中）
									</view>
									<checkbox :id="item4.id" :checked="true" :disabled="true" />
								</view>
								<view class="item-kongtiao" v-else>
									<view :style="{color: item4.isUsering ? '#747578' : '#2979ff'}">
										{{item4.label}}
									</view>
									<checkbox :value="index4" :id="item4.id" :checked="item4.isChecked"
										@tap="handle_kongtiao" />
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 用于返回到上一页面的结果变量
				airs_selected: '',
				show_airs: '', // 用于显示已经选择的空调
				screenHeight: '', // 屏幕的高度
				// tree
				treeData: [] // 树形选择器的数据
			};
		},
		onLoad() {
			uni.showLoading({
				title: '加载中'
			})

			// 模拟异步请求
			setTimeout(() => {
				this.treeData = [{
					id: 1,
					label: '科技楼',
					isShow: false,
					children: [{
						id: 11,
						label: '5F',
						isShow: false,
						children: [{
							id: 111,
							label: '501',
							isShow: false,
							children: [{
								id: 1111,
								label: '空调-01',
								isChecked: false,
								isUsering: false
							}, {
								id: 1112,
								label: '空调-02',
								isChecked: true,
								isUsering: true
							}]
						}, {
							id: 112,
							label: '502',
							isShow: false,
							children: [{
								id: 1121,
								label: '空调-01',
								isChecked: false,
								isUsering: false
							}]
						}]
					}]
				}, {
					id: 2,
					label: '志胜楼',
					isShow: false,
					children: [{
						id: 21,
						label: '1F',
						isShow: false,
						children: [{
							id: 211,
							label: '101',
							isShow: false,
							children: [{
								id: 2111,
								label: '空调-01',
								isChecked: false,
								isUsering: false
							}, {
								id: 2112,
								label: '空调-02',
								isChecked: false,
								isUsering: false
							}]
						}, {
							id: 212,
							label: '102',
							isShow: false,
							children: [{
								id: 2121,
								label: '空调-01',
								isChecked: false,
								isUsering: false
							}, {
								id: 2122,
								label: '空调-02',
								isChecked: false,
								isUsering: false
							}]
						}]
					}]
				}];

				setTimeout(() => {
					uni.hideLoading();
				}, 500);
			}, 500);
		},
		onShow() {
			// 从新计算高度
			this.calc_screen_height()
		},
		methods: {
			/**
			 * 获取空调的全称，勾选返回空调全称，不勾返回-空调全称，递归调用
			 * @param {Object} obj
			 * @param {Object} id
			 * @param {Object} parentName
			 */
			get_airs_full_name(obj, id, parentName) {
				for (var i = 0; i < obj.length; i++) {
					if (obj[i].id == id) {
						if (parentName == '') {
							return obj[i].label
						}

						if (obj[i].isChecked) {
							obj[i].isChecked = false
							return '-' + parentName + ' ' + obj[i].label
						} else {
							obj[i].isChecked = true
							return parentName + ' ' + obj[i].label
						}
					}

					let selfName = ''
					if (typeof obj[i].children != 'undefined' && obj[i].children.length > 0) {
						if (parentName == '') {
							selfName = this.get_airs_full_name(obj[i].children, id, obj[i].label)
						} else {
							selfName = this.get_airs_full_name(obj[i].children, id, parentName + '-' + obj[i].label)
						}

						if (typeof selfName != 'undefined') {
							return selfName
						}
					}
				}
			},
			/**
			 * 更新airs_selected中的数据
			 * @param {Object} param
			 */
			update_airs_selected(param) {
				let tmp_airs_selected = ''
				if (param.indexOf('-') == 0) { // 删除airs_selected中的数据
					// 把前面的'-'去除
					let del_val = param.substring(1)
					// 需要删除的值进行拆分成：【楼栋-楼层-房间，空调】
					let room = del_val.split(' ')
					if (this.airs_selected.trim() != '') {
						let arrAirs = this.airs_selected.trim().split(',')
						let airs = ''
						for (var i = 0; i < arrAirs.length; i++) {
							airs = arrAirs[i].trim() // 删除空格后，赋给临时变量
							// 如果找到指定的房间，则删除
							if (airs.indexOf(room[0]) == 0) {
								// 删除 楼栋-楼层-房间 中的空调
								airs = airs.replace(' ' + room[1], '')
								// 如果只剩下 楼栋-楼层-房间，没有了空调，则置为空
								if (airs == room[0]) {
									airs = ''
								}
							}

							if (airs != '') {
								// 保存到临时变量tmp_airs_selected中
								tmp_airs_selected += airs + ','
							}
						}
					}
				} else { // 添加、合并到airs_selected中
					// 如果为空，直接加入
					if (this.airs_selected.trim() == '') {
						tmp_airs_selected = param + ','
					} else {
						let arrAirs = this.airs_selected.trim().split(',')
						let num = 0
						// 需要添加的数据
						let room = param.split(' ')
						for (var i = 0; i < arrAirs.length; i++) {
							let airs = arrAirs[i].trim().split(' ')
							// 如果找到指定的房间，则合并
							if (airs[0] == room[0]) {
								// 临时数组, 为排序做准备
								let tmp_arr = []
								// 数组转字符串, 即拼接
								tmp_arr.push(room[1])
								for (var j = 1; j < airs.length; j++) {
									tmp_arr.push(airs[j])
								}
								// 数组排序
								tmp_arr.sort()
								// 生成字符串
								tmp_airs_selected += room[0]
								for (var k = 0; k < tmp_arr.length; k++) {
									tmp_airs_selected += ' ' + tmp_arr[k]
								}
								// 加入分隔符
								tmp_airs_selected += ','
							} else {
								num++ // 计数
								tmp_airs_selected += arrAirs[i] + ','
							}
						}
						// 如果没有找到同一房间的，则直接拼接要添加的数据
						if (num == arrAirs.length) {
							tmp_airs_selected += param + ','
						}
					}
				}
				// 更新变量airs_selected
				this.airs_selected = tmp_airs_selected.substring(0, tmp_airs_selected.length - 1)
				// 更新显示框的内容
				this.show_selected_airs()
			},
			/**
			 * 选择空调
			 * @param {Object} e
			 */
			handle_kongtiao(e) {
				// console.log(e.currentTarget.id);
				// 获取id
				let id = e.currentTarget.id
				// 获取勾选的值
				let airsFullName = this.get_airs_full_name(this.treeData, id, '')
				if (typeof airsFullName != 'undefined') {
					// 更新airs_selected中的数据
					this.update_airs_selected(airsFullName)
				} else {
					uni.showToast({
						title: '选取无效！',
						duration: 1500
					})
				}
			},
			/**
			 * 选项的展开与收起，进行切换，递归调用
			 * @param {Object} obj
			 * @param {Object} id
			 */
			toggle_item(obj, id) {
				for (var i = 0; i < obj.length; i++) {
					if (obj[i].id == id) {
						if (obj[i].isShow) {
							obj[i].isShow = false
						} else {
							obj[i].isShow = true
						}
						return
					}

					if (typeof obj[i].children != 'undefined' && obj[i].children.length > 0) {
						this.toggle_item(obj[i].children, id)
					}
				}
			},
			/**
			 * 选项的展开与收起，进行切换
			 * @param {Object} e
			 */
			handle_toggle_items(e) {
				// console.log(e.currentTarget.id);
				// 获取id
				let id = e.currentTarget.id
				this.toggle_item(this.treeData, id)
			},
			/**
			 * 确认选择，将结果返回到前一页面显示
			 */
			confirm_selection() {
				// 触发全局的自定义事件，附加参数都会传给监听器回调函数。
				if (this.airs_selected != '') {
					uni.$emit('selectAirs', {
						airs: this.airs_selected
					})
				}

				// 返回空调列表页面
				uni.navigateBack({
					delta: -1
				})
			},
			/**
			 * 超出左边显示...
			 */
			show_selected_airs() {
				// 显示到上方
				this.show_airs = this.airs_selected.split('').reverse().join('')
			},
			/**
			 * 计算屏幕的高度
			 */
			calc_screen_height() {
				uni.getSystemInfo({
					success: res => {
						let h = ((res.screenHeight * (750 / res.windowWidth)) - 480) //将px 转换rpx
						this.screenHeight = Math.floor(h) + 'rpx'
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		font-size: 28rpx;
		font-family: "Microsoft YaHei-3970(82674968)";
		width: 730rpx;
		padding: 10rpx;

		.line {
			height: 20rpx;
		}

		.show-selected {
			display: flex;
			padding: 20rpx;
			border-radius: 10rpx;
			border: 1px solid #c7c9ce;
			font-size: 32rpx;

			.title-selected {
				color: #686b71;
				white-space: nowrap;
			}

			.air-selected-name {
				width: 600rpx;
				font-weight: bold;
				white-space: nowrap;
				text-overflow: ellipsis;
				direction: rtl;
				unicode-bidi: bidi-override;
				overflow: hidden;
			}
		}

		.btn {
			display: flex;
			justify-content: flex-end;

			.btn-bg {
				margin-top: 30rpx;
				padding: 20rpx 40rpx;
				border-radius: 10rpx;
				font-size: 32rpx;
				color: #ffffff;
				background-color: #2979ff;
			}
		}

		.title-tip {
			font-size: 36rpx;
		}

		.tree-box {
			border-radius: 10rpx;
			border: 1px solid #c7c9ce;
			color: #2979ff;

			.tree-scroll {
				border-radius: 10rpx;
				overflow: scroll;
			}

			.item-loudong {
				display: flex;
				flex-direction: column;
				padding: 10rpx 0 0 10rpx;

				.loudong {
					display: flex;
					align-items: center;
					justify-content: space-between;
					border: 1rpx solid #c7c9ce;
					padding: 10rpx;
					height: 60rpx;
					width: 636rpx;
					font-size: 30rpx;

					.title-loudong {
						display: flex;
					}

					.txt-loudong {
						padding-left: 5rpx;
					}
				}

				.item-loucheng {
					display: flex;
					flex-direction: column;
					margin-left: 60rpx;

					.loucheng {
						display: flex;
						align-items: center;
						justify-content: space-between;
						border: 1rpx solid #c7c9ce;
						padding: 10rpx;
						height: 60rpx;
						width: 578rpx;
						font-size: 30rpx;

						.title-loucheng {
							display: flex;
						}

						.txt-loucheng {
							padding-left: 5rpx;
						}
					}

					.item-jiaoshi {
						display: flex;
						flex-direction: column;
						margin-left: 60rpx;

						.jiaoshi {
							display: flex;
							align-items: center;
							justify-content: space-between;
							border: 1rpx solid #c7c9ce;
							padding: 10rpx;
							height: 60rpx;
							width: 520rpx;
							font-size: 30rpx;

							.title-jiaoshi {
								display: flex;
							}

							.txt-jiaoshi {
								padding-left: 5rpx;
							}
						}

						.item-kongtiao {
							display: flex;
							justify-content: space-between;
							align-items: center;
							border: 1rpx solid #c7c9ce;
							margin-left: 60rpx;
							padding: 10rpx 10rpx 10rpx 30rpx;
							height: 60rpx;
							width: 442rpx;
							font-size: 32rpx;
						}
					}
				}
			}
		}
	}
</style>
