<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-school" v-for="(item0, index0) in treeData" :key="index0">
					<view class="school" :id="item0.id" @tap="handle_toggle_items">
						<view>{{item0.label}}</view>
						<uni-icons type="top" size="22" color="#ffffff" :style="{display: item0.isShow ? '' : 'none'}">
						</uni-icons>
						<uni-icons type="bottom" size="22" color="#ffffff"
							:style="{display: item0.isShow ? 'none' : ''}">
						</uni-icons>
					</view>
					<!-- 楼栋 -->
					<view class="item-loudong" v-for="(item1, index1) in item0.children" :key="index1"
						:style="{display: item0.isShow ? '' : 'none'}">
						<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="top" size="22" color="#2979ff"
								:style="{display: item1.isShow ? '' : 'none'}"></uni-icons>
							<uni-icons type="bottom" 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="top" size="22" color="#2979ff"
									:style="{display: item2.isShow ? '' : 'none'}"></uni-icons>
								<uni-icons type="bottom" 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="get_air_in_the_room($event, item0.id + '|' + item1.id + '|' + item2.id + '|' + item3.id, item0.label + '|' + item1.label + '|'+ item2.label + '|' + item3.label, item3.isShow)">
									<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.split('-')[1]}}</view>
									</view>
									<uni-icons type="top" size="22" color="#2979ff"
										:style="{display: item3.isShow ? '' : 'none'}"></uni-icons>
									<uni-icons type="bottom" 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 ? '#dc0000' : '#2979ff'}">
											{{item4.label}}（使用中）
										</view>
										<checkbox :value="index4" :id="item4.id" :checked="item4.isChecked"
											@tap="handle_kongtiao" />
									</view>
									<view class="item-kongtiao" v-else>
										<view :style="{color: item4.isUsering ? '#dc0000' : '#2979ff'}">
											{{item4.label}}
										</view>
										<checkbox :value="index4" :id="item4.id" :checked="item4.isChecked"
											@tap="handle_kongtiao" />
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				ceshi: 'air',
				id_card: '', // 身份证号
				user_name: '', // 姓名
				airs_selected: '', //
				return_selected_airs: '', // 用于返回到上一页面的结果变量
				show_airs: '', // 用于显示已经选择的空调
				treeData: [], // 树形选择器的数据，目录树treeData
				airsData: [], // 点击教室的时候，获取该教室的空调数据
				screenHeight: '' // 屏幕的高度
			};
		},
		onLoad(options) {
			uni.showLoading({
				title: '加载中'
			})

			// 获取表格数据
			this.getTableData()

			setTimeout(() => {
				uni.hideLoading();
			}, 500);

			// 获取身份证号
			this.get_base_info(options)
		},
		onShow() {
			// 从新计算高度
			setTimeout(() => {
				this.calc_screen_height()
			}, 1500)
		},
		methods: {
			/**
			 * 获取身份证号
			 */
			get_base_info(options) {
				try {
					if (this.id_card == '' || typeof(this.id_card) == 'undefined') {
						const userinfo = uni.getStorageSync('userinfo_storage_key')
						if (userinfo) {
							this.id_card = userinfo.id_card
							this.user_name = userinfo.name
						} else {
							uni.navigateTo({
								url: '../index/index?from=' + options.from
							})

							uni.showToast({
								icon: 'none',
								title: '身份证号为空，请进行授权',
								duration: 3000
							});

							return
						}
					}
				} catch (e) {
					console.log('获取基本信息：' + e.message);
				}
			},
			/**
			 * 点击房间，显示空调
			 * @param {Object} e
			 * @param {Object} id
			 * @param {Object} label
			 * @param {Object} rooms
			 */
			async get_air_in_the_room(e, id, label, isShow) {
				let ids = id.split('|')
				let labels = label.split('|')
				// console.log(ids);
				// console.log(labels);
				// 展开或收起
				this.handle_toggle_items(e)

				// 展开时获取接口空调信息
				if (false === isShow) {
					const res = await this.$myRequest({
						host: this.ceshi,
						url: '/airManage/buildairqueryAirMes.action',
						method: 'POST',
						header: {
							'content-type': 'application/x-www-form-urlencoded'
						},
						data: {
							school: labels[0],
							build: labels[1],
							floors: labels[2],
							dom: labels[3]
						}
					})

					// console.log(res.data);
					let data = res.data
					if (typeof data.code === 'undefined') {
						uni.showToast({
							title: '未找到code!',
							icon: 'success'
						});
						return
					}

					if (data.code === 200 && typeof data.data !== 'undefined') {
						// 清空
						this.airsData = []
						for (var i = 0; i < data.data.length; i++) {
							this.airsData.push({
								isUsering: data.data[i].is_on == 1 ? true : false,
								label: data.data[i].air_name + '-' + data.data[i].air_config,
								isChecked: false,
								id: data.data[i].air_ip
							})
						}
						// 排序
						this.airsData.sort((a, b) => a.label.localeCompare(b.label))
						if (this.airsData.length > 0) {
							// 填充数据
							this.insert_into_treeData_rooms(this.treeData, ids[3])
						}
					} else {
						uni.showToast({
							title: '该房间未配空调'
						});
					}
				}
			},
			/**
			 * 填充空调到教室下面，供选择
			 * @param {Object} obj
			 * @param {Object} id
			 */
			insert_into_treeData_rooms(obj, id) {
				for (var i = 0; i < obj.length; i++) {
					if (obj[i].id == id) {
						obj[i].children = this.airsData
						return
					}

					if (typeof obj[i].children != 'undefined' && obj[i].children.length > 0) {
						this.insert_into_treeData_rooms(obj[i].children, id)
					}
				}
			},
			/**
			 * 树形选择器的数据
			 */
			async getTableData() {
				const res = await this.$myRequest({
					host: this.ceshi,
					url: '/airManage/buildqueryDom.action',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					}
				})

				// console.log(res.data);
				if (typeof res.data.code === 'undefined') {
					uni.showToast({
						title: '未找到code!',
						icon: 'success'
					});
					return
				}

				if (typeof res.data.data === 'undefined') {
					uni.showToast({
						title: '未返回数据data!',
						icon: 'success'
					});
					return
				}

				if (res.data.code === 200) {
					let data = res.data.data
					// 校区
					let school = JSON.parse(data)
					// console.log('school', school);
					if (typeof school !== 'undefined' && school !== '') {
						this.treeData = []
						let tmpSchool = []
						for (var i = 0; i < school.length; i++) {
							let nData = []
							let builds = school[i]["builds"]
							for (var j = 0; j < builds.length; j++) {
								let tmpBuilds = {}
								let tmpFloors = []
								let floors = builds[j]['floors']
								for (var k = 0; k < floors.length; k++) {
									let room = []
									let tmpRooms = []
									let rooms = floors[k].rooms
									for (var p = 0; p < rooms.length; p++) {
										room.push({
											id: school[i].id + '' + builds[j].id + '' + floors[k].id + '' + i +
												'' + j + '' + k + '' + p,
											isShow: false,
											label: rooms[p],
											children: []
										})
									}
									// 房间排序
									room.sort((a, b) => a.label.localeCompare(b.label));
									let floor = {
										id: floors[k].id,
										label: floors[k].floor,
										isShow: false,
										children: room
									}
									tmpFloors.push(floor)
								}
								// 楼层排序
								tmpFloors.sort((a, b) => {
									return a - b;
								})
								tmpBuilds.id = builds[j].id
								tmpBuilds.label = builds[j].building
								tmpBuilds.isShow = false
								tmpBuilds.children = []
								tmpBuilds.children = tmpFloors
								nData.push(tmpBuilds)
							}
							// 栋排序
							nData.sort((a, b) => a.label.localeCompare(b.label))
							tmpSchool.push({
								id: school[i].id,
								label: school[i].school,
								isShow: true,
								children: nData
							})
						}
						// 校区排序
						tmpSchool.sort((a, b) => b.label.localeCompare(a.label))
						this.treeData = tmpSchool
						// console.log(JSON.stringify(this.treeData));
					} else {
						this.treeData = []
						uni.showToast({
							title: '无符合的数据!'
						});
					}
				} else {
					uni.showToast({
						title: res.data.message,
						icon: 'success'
					});
				}
			},
			/**
			 * 获取空调的全称，勾选返回空调全称，不勾返回-空调全称，递归调用
			 * @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
						}
					}
				}
			},
			/**
			 * 获取空调的ids
			 * @param {Object} obj
			 * @param {Object} id
			 */
			get_airs_ids() {
				let airs_selected_ids = ''
				let obj0 = this.treeData
				for (var i = 0; i < obj0.length; i++) {
					if (typeof obj0[i].children !== 'undefined' && obj0[i].children.length > 0) {
						let obj1 = obj0[i].children
						for (var j = 0; j < obj1.length; j++) {
							if (typeof obj1[j].children !== 'undefined' && obj1[j].children.length > 0) {
								let obj2 = obj1[j].children
								for (var k = 0; k < obj2.length; k++) {
									if (typeof obj2[k].children !== 'undefined' && obj2[k].children.length > 0) {
										let obj3 = obj2[k].children
										for (var p = 0; p < obj3.length; p++) {
											if (typeof obj3[p].children !== 'undefined' && obj3[p].children.length > 0) {
												let obj4 = obj3[p].children
												for (var u = 0; u < obj4.length; u++) {
													if (obj4[u].isChecked) {
														airs_selected_ids += obj0[i].label + '-' + obj1[j].label + '-' +
															obj2[k]
															.label + '-' + obj3[p].label + '|' + obj4[u].label + '|' +
															obj4[u]
															.id + ','
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
				this.return_selected_airs = airs_selected_ids.substring(0, airs_selected_ids.length - 1)
			},
			/**
			 * 更新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, '')
				// 获取所有选中的id
				this.get_airs_ids()
				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.return_selected_airs !== '') {
					// 保存到数据库
					let arrAirs = this.return_selected_airs.trim().split(',').sort()
					for (var i = 0; i < arrAirs.length; i++) {
						let tmpAirs = arrAirs[i].split('|');
						let _this = this;
						// 绑定空调
						(function(t, air_ip) {
							setTimeout(function() {
								_this.bangding_airs(air_ip);
							}, 100 * t);
						})(i, tmpAirs[2])
					}

					uni.$emit('selectAirs', {
						sel_airs: this.return_selected_airs
					})
				}

				// 返回空调列表页面
				uni.navigateBack({
					delta: -1
				})
			},
			/**
			 * 绑定空调
			 * @param {Object} air_id
			 */
			async bangding_airs(air_id) {
				const res = await this.$myRequest({
					host: this.ceshi,
					url: '/airManage/usersbdair.action',
					method: 'POST',
					header: {
						'content-type': 'application/json'
					},
					data: {
						user_name: this.user_name,
						sfzh: this.id_card,
						air_ip: air_id
					}
				})

				// console.log(res.data);
				if (res.data.code == 200) {
					uni.showToast({
						icon: 'none',
						title: res.data.message,
						duration: 1500
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: res.data.message,
						duration: 1500
					})
				}
			},
			/**
			 * 超出左边显示"..."
			 */
			show_selected_airs() {
				// 显示到上方
				this.show_airs = this.airs_selected.split('').reverse().join('').replaceAll('（', '>').replaceAll('）', '<')
					.replaceAll('>', '）').replaceAll('<', '（')
			},
			/**
			 * 计算屏幕的高度
			 */
			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-school {
				display: flex;
				flex-direction: column;
				padding: 10rpx 0 0 10rpx;

				.school {
					display: flex;
					align-items: center;
					justify-content: space-between;
					background-color: #2979ff;
					color: #ffffff;
					padding: 10rpx 10rpx 10rpx 20rpx;
					height: 60rpx;
					width: 668rpx;
					font-size: 30rpx;
				}

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


					.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>
