<template>
	<view id="emergencyEvacuationBigFullScreen">
		<view class="emergencyEvacuationBigFullScreen-page" v-if="mapType"
			:style="'width:'+mapWidth+'px;height:'+mapHeight+'px;transform: scale('+zoomData+');margin-top:-'+mapHeight/2+'px;margin-left:-'+mapWidth/2+'px;'">
			<view class="map-max-box" :style="'width:'+mapWidth+'px;height:'+mapHeight+'px;'">
				<!-- :style="'width:'+mapW+'px;height:'+mapH+'px;'" -->
				<view class="map-max-for-box for-map-box" v-if="item.type == 1" v-for="(item,index) in mapList"
					:key="index" :class="!item.policeType && checkSubId ==item.subId ? 'room-type-one':(
                           item.policeType && checkSubId !=item.subId ? 'room-type-two':(
                           item.policeType && checkSubId ==item.subId ? 'room-type-three':(
                           !item.loginAdmin ? 'room-type-noe':''
					   )))" :style="'top:'+item.y+'px;left:'+item.x+'px;width:'+(item.w-4)+'px;height:'+(item.h-4)+'px;'">
					<view class="map-max-for-min-box">
						<view class="map-for-name-p" :style="'margin-top:'+((item.h/2)-20)+'px;'">
							{{item.roomType == '-99'?item.roomName:item.subName}}</view>
						<view class="map-for-num-p">({{item.roomNum}})</view>
						<view class="position-box" src="@/images/evacuation3_2/icon_sysbjt_m.png"
							:class="minItem.toward=='top'?'center-move-door-p-t':(minItem.toward=='bottom'?'center-move-door-p-b':(minItem.toward=='left'?'center-move-door-p-l':(minItem.toward=='right'?'center-move-door-p-r':'')))"
							v-for="(minItem,minIndex) in item.doorList" :key="minIndex"
							:style="'top:'+minItem.y+'px;left:'+minItem.x+'px;width:'+minItem.w+'px;height:'+minItem.h+'px;'">
						</view>
					</view>
				</view>
				<view class="map-max-for-box for-map-box-one" v-if="item.type == 2" v-for="(item,index) in mapList"
					:key="index" :style="'top:'+item.y+'px;left:'+item.x+'px;width:'+item.w+'px;height:'+item.h+'px;'">
					<view class="map-max-for-min-box">
						<view class="position-box" @click="lighButton(minItem)"
							:class="minItem.state=='1'&&minItem.openType?'lightTopOn':(minItem.state=='1'&&!minItem.openType?'lightTopOff':
									(minItem.state=='2'&&minItem.openType?'lightBottomOn':(minItem.state=='2'&&!minItem.openType?'lightBottomOff':
									(minItem.state=='3'&&minItem.openType?'lightLeftOn':(minItem.state=='3'&&!minItem.openType?'lightLeftOff':
									(minItem.state=='4'&&minItem.openType?'lightRightOn':(minItem.state=='4'&&!minItem.openType?'lightRightOff':'')))))))"
							v-for="(minItem,minIndex) in item.lightList" :key="minIndex"
							:style="'top:'+minItem.y+'px;left:'+minItem.x+'px;width:'+minItem.w+'px;height:'+minItem.h+'px;'">
						</view>
					</view>
				</view>
				<view class="map-max-for-box for-map-box-two" v-if="item.type == 3" v-for="(item,index) in mapList"
					@click="checkRoom(item)"
					:key="index" :class="item.roomCheckType?'for-map-box-two-check':''"
					:style="'top:'+item.y+'px;left:'+item.x+'px;width:'+item.w+'px;height:'+item.h+'px;'">
				</view>
			</view>
		</view>
		<view class="position-button" @click="backButton">退出全屏</view>
		<view class="position-button-two" @click="executeEvacuation">已确定疏散出口,立即执行疏散</view>
	</view>
</template>

<script>
	import $mqtt from '@/utils/mqtt.min.js';
	import {
		getFloorData,
		getRedisEvacuation,
		openLight,
		closeLight,
		executeEvacuation
	} from '@/api/index.js'
	export default {
		data() {
			return {
				// 楼栋id
				buildingId: null,
				//楼层id
				floorId: null,
				//实验室ID
				subId:null,
				//当前选中实验室
				checkSubId: null,
				//页面开关
				mapType: false,
				mapList: [],
				//缩放相关数据
				zoomData: null,
				mapWidth: null, //40边框距离
				mapHeight: null, //40边框距离
				//弹层地图数据
				buildingOptions: {},
				//mqtt
				floorClient: {},
				evacuationTopic: "lab/newexit/line", //疏散
				//疏散按钮
				buttonType:false
			}
		},
		onLoad(option) {
			if(option.item){
				let obj = JSON.parse(decodeURIComponent(option.item));
				this.$set(this,'buildingId',obj.buildingId);
				this.$set(this,'floorId',obj.floorId);
				this.$set(this,'subId',obj.subId);
				this.$set(this,'checkSubId',obj.subId);
				if(obj.type == 2){
					this.$set(this,'buttonType',true);
				}else{
					this.$set(this,'buttonType',false);
				}
			}
		},
		onShow() {
			// this.offMQTT('on');
			this.getBuildingData();
		},
		methods: {
			mqttPageFunction(type){
				let self = this;
				if (type == 'FLOOR_EXITLINE') {
					this.getRedisEvacuation();
				} else if (type == 'FLOOR_OVER_EXITLINE') {
					uni.showToast({
						title: '疏散已结束',
						icon: "none",
						mask: true,
						duration: 2000
					});
					setTimeout(function() {
						self.getBuildingData();
					}, 2000);
				}
			},
			checkRoom(item){
				if(this.buttonType){
					item.roomCheckType = !item.roomCheckType;
					this.$forceUpdate();
				}
			},
			//开始疏散
			async executeEvacuation(){
				let self = this;
				let list = [];
				let doorPointNames = [];
				for(let i=0;i<self.mapList.length;i++){
					if(self.mapList[i].type == 3){
						if(!self.mapList[i].roomCheckType){
							list.push(self.mapList[i].key)
						}else{
							doorPointNames.push(self.mapList[i].key)
						}
					}
				}
				if(!doorPointNames[0]){
					uni.showToast({
						title: '请选择疏散出口',
						icon: "none",
						mask: true,
						duration: 2000
					});
					return
				}
				let obj = {
				buildId:this.buildingId,
				floorId:this.floorId,
				subId: this.subId,
				badPointNames:list,
				doorPointNames:doorPointNames,
				}
				const {	data } = await executeEvacuation(obj)
				if (data.code == 200) {
					uni.showToast({
						title: '执行成功',
						icon: "none",
						mask: true,
						duration: 2000
					});
					setTimeout(function(){
						uni.navigateBack();
					},2000);
				}
			},
			//疏散页面
			backButton() {
				uni.navigateBack()
			},
			//地图数据
			async getBuildingData() {
				let self = this;
				const {
					data
				} = await getFloorData(this.floorId)
				if (data.code == 200) {
					if (data.data.buildFloorLayoutVoList[0]) {
						let list = JSON.parse(data.data.labExitLineVertex.layoutJoinData)
						this.getWXSystemInfo(list);
						for (let i = 0; i < list.length; i++) {
							if (list[i].type == '2') {
								//楼道
								for (let o = 0; o < list[i].lightList.length; o++) {
									list[i].lightList[o].openType = false;
								}
							} else if (list[i].type == '1') {
								for (let o = 0; o < data.data.buildFloorLayoutVoList.length; o++) {
									if (list[i].key == data.data.buildFloorLayoutVoList[o].pointName) {
										list[i].id = data.data.buildFloorLayoutVoList[o].id;
										list[i].buildId = data.data.buildFloorLayoutVoList[o].buildId;
										list[i].floorId = data.data.buildFloorLayoutVoList[o].floorId;
										list[i].roomType = data.data.buildFloorLayoutVoList[o].roomType;
										list[i].roomName = data.data.buildFloorLayoutVoList[o].roomName;
										list[i].roomNum = data.data.buildFloorLayoutVoList[o].roomNum;
										list[i].subName = data.data.buildFloorLayoutVoList[o].subName;
										list[i].subId = data.data.buildFloorLayoutVoList[o].subId;
										list[i].online = data.data.buildFloorLayoutVoList[o].online;
										list[i].loginAdmin = data.data.buildFloorLayoutVoList[o].loginAdmin;
										list[i].policeType = false;
									}
								}
							} else if (list[i].type == 3) {
								list[i].roomCheckType = false;
							}
						}
						this.$set(this, 'mapList', JSON.parse(JSON.stringify(list)));
						this.$set(this, 'mapType', true);
						setTimeout(function() {
							self.getRedisEvacuation();
						}, 500);

					}
				}
			},
			//获取疏散数据
			async getRedisEvacuation() {
				let self = this;
				let obj = {
					buildId: this.buildingId,
					floorId: this.floorId,
				}
				const {
					data
				} = await getRedisEvacuation(obj)
				if (data.code == 200) {
					if (data.data.doorPointNames) {
						for (let o = 0; o < self.mapList.length; o++) {
							if (self.mapList[o].type == 2) {
								for (let x = 0; x < self.mapList[o].lightList.length; x++) {
									let num = 0;
									for (let i = 0; i < data.data.lightPointSet.length; i++) {
										if (data.data.lightPointSet[i]) { //处理后端返回的异常的NULL
											if (self.mapList[o].lightList[x].key == data.data.lightPointSet[i].key) {
												num++
											}
										}
									}
									self.mapList[o].lightList[x].openType = num != 0;
								}
							}
						}
						for (let i = 0; i < data.data.doorPointNames.length; i++) {
							for (let o = 0; o < self.mapList.length; o++) {
								if (self.mapList[o].type == 3) {
									if (data.data.doorPointNames[i] == self.mapList[o].key) {
										self.mapList[o].roomCheckType = true;
									}
								}
							}
						}
						this.$forceUpdate();
					}
				};
			},
			//灯点击事件
			lighButton(item) {
				let self = this;
				uni.showModal({
					content: '确定' + (item.openType ? '关闭' : '开启') + '该疏散灯?',
					cancelColor: "#999",
					confirmColor: "#0183FA",
					success: function(res) {
						if (res.confirm) {
							if (item.openType) {
								self.closeLight(item);
							} else {
								self.openLight(item);
							}
						} else if (res.cancel) {
						}
					}
				});
			},
			//开灯
			async openLight(item) {
				let obj = {
					buildId: this.buildingId,
					floorId: this.floorId,
					pointName: item.key
				};
				const {
					data
				} = await openLight(obj)
				if (data.code == 200) {
					uni.showToast({
						title: '操作成功',
						icon: "none",
						mask: true,
						duration: 2000
					});
				}
			},
			//关灯
			async closeLight(item) {
				let obj = {
					buildId: this.buildingId,
					floorId: this.floorId,
					pointName: item.key
				};
				const {
					data
				} = await closeLight(obj)
				if (data.code == 200) {
					uni.showToast({
						title: '操作成功',
						icon: "none",
						mask: true,
						duration: 2000
					});
				}
			},
			//计算缩放率
			getWXSystemInfo(list) {
				let self = this;
				wx.getSystemInfo({
					success: function(res) {
						self.zoomCalculate(list, res.windowHeight, res.windowWidth);
					}
				})
			},
			zoomCalculate(list, height, width) {
				let num = 0;
				let zoomType = 0;
				let maxWidth = 0
				let maxHeight = 0
				let zoomData = 1;
				if (height > width) {
					num = height / width
				} else {
					num = width / height
				}
				for (let i = 0; i < list.length; i++) {
					if ((list[i].x + list[i].w) > maxWidth) {
						maxWidth = list[i].x + list[i].w
					}
					if ((list[i].y + list[i].h) > maxHeight) {
						maxHeight = list[i].y + list[i].h
					}
				}
				this.$set(this, 'mapWidth', maxWidth);
				this.$set(this, 'mapHeight', maxHeight);
				  let zoomNumOne = height / maxHeight;
				  if(parseInt(this.accMul(zoomNumOne,maxHeight)) <= height && parseInt(this.accMul(zoomNumOne,maxWidth)) <= width){
				    zoomData = zoomNumOne;
				    this.$set(this,'zoomData',zoomNumOne);
				  }
				  let zoomNumTwo = width / maxWidth;
				  if(parseInt(this.accMul(zoomNumTwo,maxHeight)) <= height && parseInt(this.accMul(zoomNumTwo,maxWidth)) <= width){
				    zoomData = zoomNumTwo;
				    this.$set(this,'zoomData',zoomNumTwo);
				  }
				// if (maxWidth > maxHeight) {
				// 	if ((maxWidth / maxHeight) > num) {
				// 		// 以宽度缩放
				// 		zoomType = 1;
				// 	} else {
				// 		// 以高度缩放
				// 		zoomType = 2;
				//  }
				// } else {
				// 	if ((maxHeight / maxWidth) > num) {
				// 		// 以高度缩放
				// 		zoomType = 2;
				// 	} else {
				// 		// 以宽度缩放
				// 		zoomType = 1;
				// 	}
				// }

				// if (zoomType == 1) {
				// 	if (width > maxWidth) {
				// 		zoomData = maxWidth / width;
				// 	} else {
				// 		zoomData = width / maxWidth;
				// 	}
				// 	if (width > maxWidth) {
				// 		this.$set(this, 'zoomData', maxWidth / width);
				// 	} else {
				// 		this.$set(this, 'zoomData', width / maxWidth);
				// 	}
				// } else if (zoomType == 2) {
				//  if (height > maxHeight) {
				// 		zoomData = maxHeight / height;
				// 	} else {
				// 		zoomData = height / maxHeight;
				// 	}
				// 	if (height > maxHeight) {
				// 		this.$set(this, 'zoomData', maxHeight / height);
				// 	} else {
				// 		this.$set(this, 'zoomData', height / maxHeight);
				// 	}
				// }
			},
			  accMul(arg1,arg2){
				var m=0,s1=arg1.toString(),s2=arg2.toString();
				try{m+=s1.split(".")[1].length}catch(e){}
				try{m+=s2.split(".")[1].length}catch(e){}
				return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
			  },
			/*MQTT*/
			//订阅
			onMQTT() {
				let self = this;
				const mqttOptions = {
					keepalive: 30,
					clean: true, //保留会话
					connectTimeout: 600000, // 超时时间
					reconnectPeriod: 5000, // 重连间隔
					clientId: uni.getStorageSync('token') + 'lab/function/data',
          username: uni.getStorageSync('mqttUser'),
          password: uni.getStorageSync('mqttPassword'),
				}
				const connectUrl = uni.getStorageSync('mqttUrl');
				this.floorClient = $mqtt.connect('wxs://' + connectUrl, mqttOptions);
				this.floorClient.on('connect', () => {
					this.floorClient.subscribe(this.evacuationTopic + this.floorId, (err) => {
						if (!err) {
							console.log("疏散-订阅成功", )
							this.getBuildingData();
						}
					});
				});
				// 自动重连
				this.floorClient.on('reconnect', (msg) => {
					console.log('自动重连-reconnect-1', msg)
				});
				// 错误
				this.floorClient.on('error', () => {
					console.log('错误-error-1')
				});
				// 断开
				this.floorClient.on('end', () => {
					console.log('断开-end-1')
				});
				// 掉线
				this.floorClient.on('offline', (msg) => {
					console.log('掉线-offline-1', msg)
				});
				// 收到消息
				this.floorClient.on('message', (topic, message) => {
					let data = JSON.parse(message)
					if (data) {
						if (topic == (this.evacuationTopic + this.floorId)) {
							console.log('疏散通知', data)
							//疏散消息
							if (data.data == 'FLOOR_EXITLINE') {
								this.getRedisEvacuation();
							} else if (data.data == 'FLOOR_OVER_EXITLINE') {
								uni.showToast({
									title: '疏散已结束',
									icon: "none",
									mask: true,
									duration: 2000
								});
								setTimeout(function() {
									self.getBuildingData();
								}, 2000);
							}
						}
					}
				});
				// 全局监听是否有关闭mqtt的消息的事件
				uni.$on('closeMqtt', () => {
					this.floorClient.end(true); // 主动断开连接
				})
			},
			//关闭MQTT连接
			offMQTT(type) {
				if (this.floorClient.unsubscribe) {
					this.floorClient.unsubscribe(this.evacuationTopic + this.floorId, error => {
						if (error) {
							console.log('疏散连接-关闭错误', error)
						}
					});
					this.floorClient.end(true);
					this.$set(this, 'floorClient', {});
				}
				if (type) {
					this.onMQTT();
				}
			},
		},
		beforeDestroy() {
			//断开mqtt连接
			this.offMQTT();
		}
	}
</script>

<style lang="stylus" scoped>
	#emergencyEvacuationBigFullScreen {
		height: 100%;
		width: 100%;
		display: flex;
		overflow: hidden;

		.emergencyEvacuationBigFullScreen-page {
			// overflow: scroll;
			overflow: hidden;
			position: absolute;
			top: 50%;
			left: 50%;

			.map-max-box {
				position: relative;

				.map-max-for-box {
					position: absolute;
					display: flex;
					flex-direction: column;

					.map-max-for-min-box {
						position: relative;

						.position-box {
							position: absolute;
						}

						.map-for-name-p {
							padding: 0 10px;
							height: 20px;
							line-height: 20px;
							font-size: 14px;
							text-align: center;
							color: #333;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}

						.map-for-num-p {
							padding: 0 10px;
							height: 20px;
							line-height: 20px;
							font-size: 14px;
							text-align: center;
							color: #333;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}

						.center-move-door-p-t {
							background: url("../images/evacuation3_2/icon_sysbjt_m.png") !important;
							background-size: 100% !important;
							transform: rotate(180deg);
						}

						.center-move-door-p-b {
							background: url("../images/evacuation3_2/icon_sysbjt_m.png") !important;
							background-size: 100% !important;
						}

						.center-move-door-p-l {
							background: url("../images/evacuation3_2/icon_sysbjt_m.png") !important;
							background-size: 100% !important;
							transform: rotate(90deg);
						}

						.center-move-door-p-r {
							background: url("../images/evacuation3_2/icon_sysbjt_m.png") !important;
							background-size: 100% !important;
							transform: rotateZ(270deg);
						}

						.lightTopOn {
							background: url("../images/evacuation3_2//icon_sjt.png");
							background-size: 100%;
						}

						.lightTopOff {
							background: url("../images/evacuation3_2//icon_shang_hs.png");
							background-size: 100%;
						}

						.lightBottomOn {
							background: url("../images/evacuation3_2//icon_xjt.png");
							background-size: 100%;
						}

						.lightBottomOff {
							background: url("../images/evacuation3_2//icon_xia_hs.png");
							background-size: 100%;
						}

						.lightLeftOn {
							background: url("../images/evacuation3_2//icon_zuo.png");
							background-size: 100%;
						}

						.lightLeftOff {
							background: url("../images/evacuation3_2//icon_zou_hs.png");
							background-size: 100%;
						}

						.lightRightOn {
							background: url("../images/evacuation3_2//icon_yuo.png");
							background-size: 100%;
						}

						.lightRightOff {
							background: url("../images/evacuation3_2//icon_you_hs.png");
							background-size: 100%;
						}
					}
				}

				.for-map-box {
					border: 2px solid #fff;
					background: #CEF2FD;
				}

				.for-map-box-one {
					background: #CEFDD5;
				}

				.for-map-box-two {
					background: url("../images/evacuation3_2/icon_yjtd.png") center center no-repeat #006400;
					background-size: 60px 60px;
				}

				.for-map-box-two-check {
					background: url("../images/evacuation3_2/icon_yjtd.png") center center no-repeat rgba(50, 205, 50, 1);
					background-size: 80px 80px;
				}

				.room-type-one {
					//选中
					background: rgba(178, 235, 255, 1);
				}

				.room-type-two {
					//报警
					background: rgba(232, 0, 0, 0.4);
					box-shadow: 0 0 10px 1px #E80000 inset;
				}

				.room-type-three {
					//选中报警
					background: rgba(178, 235, 255, 1);
					box-shadow: 0 0 10px 1px #E80000 inset;
				}
			}
		}

		.position-button {
			position: fixed;
			top: 10px;
			right: 10px;
			width: 100px;
			line-height: 30px;
			font-size: 16px;
			background: rgba(0, 0, 0, 0.5);
			color: #fff;
			text-align: center;
			border-radius: 18px;
			border: none;
		}
		.position-button-two{
			position: fixed;
			bottom: 20px;
			left: 50%;
			width: 240px;
			line-height: 30px;
			font-size: 16px;
			text-align: center;
			color: #fff;
			background: #0183FA;
			border-radius: 4px;
			margin-left: -120px;
			border: none;
		}
	}
</style>
