<!-- 顶部警告 -->
<template>
	<view class="top-warn" v-if="pageType">
		<view class="left-title">预警</view>
		<view class="text-view">{{text}}</view>
		<view class="button-view" @click="buttonClick">处置</view>
	</view>
</template>

<script>
	import $mqtt from '@/utils/mqtt.min.js';
	import {
		controlsRestrictVerify
	} from '@/utils/index'
	import {
		laboratoryBigViewSelectTriggerInfo,
		laboratoryPlanCloseRiskPlan,
		laboratoryBigViewGetFloorByBigView,
	} from '@/pages_manage/api/index.js'

	export default {
		data() {
			return {
				pageType: false,
				text: "",
				buildId: "",
				floorId: "",
				subId: "",
				//预案MQTT
				mtopic: 'lab/risk/plan/change',
				client: {},
				planData: {},
			}
		},
		created() {

		},
		mounted() {
			this.offPlanMQTT('on');
			this.laboratoryBigViewSelectTriggerInfo();
		},
		methods: {
			//预案-MQTT连接
			offPlanMQTT(type) {
				let self = this;
				if (self.client.unsubscribe) {
					self.client.unsubscribe(self.mtopic, error => {
						if (error) {
							// console.log('mqtt关闭连接错误:', error)
						}
					})
					self.client.end();
					this.$set(this, 'client', {});
				}
				//判断传入参数如果存在 发起一次新的连接
				if (type) {
					this.planMQTT();
				}
			},
			//预案-MQTT订阅
			planMQTT() {
				let self = this;
				this.client = $mqtt.connect('wxs://' + uni.getStorageSync('mqttUrl'), {
					username: uni.getStorageSync('mqttUser'),
					password: uni.getStorageSync('mqttPassword')
				});
				this.client.on("connect", e => {
					this.client.subscribe(this.mtopic, (err) => {
						if (!err) {
							console.log("预案订阅成功:" + this.mtopic);
						} else {
							// console.log("连接错误:" + err);
						}
					});
				});
				this.client.on("message", (topic, message) => {
					console.log('message', message);
					console.log('topic,', topic);
					if (message) {
						if (topic == this.mtopic) {
							//预案触发
							console.log('触发预案')
							this.laboratoryBigViewSelectTriggerInfo();
						}
					}
				});
			},
			//获取预案数据
			async laboratoryBigViewSelectTriggerInfo(type) {
				let self = this;
				const {
					data
				} = await laboratoryBigViewSelectTriggerInfo();
				if (data.code == 200) {
					// console.log('条幅触发',data.data);
					if (data.data[0]) {
						// console.log('条幅触发-有');
						this.$set(this, 'planData', data.data);
						this.$set(this, 'text', data.data[1] ? '有多个实验室发生预案' : '有实验室发生预案');
						this.$set(this, 'pageType', true);
						//传感器
						let planSensorList = [];
						data.data.forEach((item) => {
							let list = JSON.parse(item.triggerUploadData)
							list.forEach((minItem) => {
								planSensorList.push(minItem.deviceNo)
						 })
						})
						uni.setStorageSync("planSensorList", planSensorList);
					} else {
						// console.log('条幅触发-无');
						this.$set(this, 'pageType', false);
						this.$set(this, 'planData', []);
						this.$set(this, 'text', '');
						uni.setStorageSync("planSensorList", []);
					}
				}
			},
			//条幅操作按钮
			buttonClick() {
				let self = this;
				let list = [];
				if (!controlsRestrictVerify('performEvacuation')) {
					list = ['查看'];
				} else {
					list = ['查看', '结束预案'];
				}
				uni.showActionSheet({
					itemList: list,
					success: function(res) {
						if (res.tapIndex == 0) {
							self.goPage();
						} else if (res.tapIndex == 1) {
							self.closePlan();
						}
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			//结束预案弹窗
			closePlan() {
				let self = this;
				if(self.planData[1]){
						let list = [];
						for(let i=0;i<self.planData.length;i++){
							list.push(self.planData[i].subName+'-'+self.planData[i].eventName)
						}
						uni.showActionSheet({
							itemList: list,
							success: function(res) {
								uni.showModal({
									content: '传感器数据监测异常，确定要强制结束预案?关闭报警后，3分钟内系统不再触发预案报警，请核实确认后再执行此操作?',
									cancelColor: "#999",
									confirmColor: "#0183FA",
									success: function(resData) {
										if (resData.confirm) {
											self.closeRiskPlan(res.tapIndex);
										} else if (resData.cancel) {
								
										}
									}
								});
							},
							fail: function(res) {
								// console.log(res.errMsg);
							}
						});
				}else{
					uni.showModal({
						content: '传感器数据监测异常，确定要强制结束预案?关闭报警后，3分钟内系统不再触发预案报警，请核实确认后再执行此操作?',
						cancelColor: "#999",
						confirmColor: "#0183FA",
						success: function(res) {
							if (res.confirm) {
								self.closeRiskPlan(0);
							} else if (res.cancel) {
					
							}
						}
					});
				}
			},
			//结束预案方法
			async closeRiskPlan(index) {
				console.log('index',index)
				let self = this;
				const {
					data
				} = await laboratoryPlanCloseRiskPlan({
					eventId: self.planData[index].eventId
				});
				if (data.code == 200) {
					uni.showToast({
						title: '操作成功',
						icon: "none",
						mask: true,
						duration: 2000
					});
					self.laboratoryBigViewSelectTriggerInfo();
				}
			},
			//查询实验室是否配置地图
			async laboratoryBigViewGetFloorByBigView(obj) {
				const {
					data
				} = await laboratoryBigViewGetFloorByBigView({
					id: obj.floorId
				})
				if (data.code == 200) {
					if(data.data[0]){
						if(data.data[0].buildLayoutVoList){
							if (data.data[0].buildLayoutVoList[0]) {
								uni.navigateTo({
									url: '/pages_manage/views/emergencyEvacuationBig?item=' + encodeURIComponent(JSON.stringify(
										obj))
								});
							}else{
								uni.showToast({
									title: '该实验室楼层未配置地图数据,请联系管理员.',
									icon: "none",
									mask: true,
									duration: 4000
								});
							}
						}else{
							uni.showToast({
								title: '该实验室楼层未配置地图数据,请联系管理员.',
								icon: "none",
								mask: true,
								duration: 4000
							});
						}
					}else{
						uni.showToast({
							title: '该实验室楼层未配置地图数据,请联系管理员.',
							icon: "none",
							mask: true,
							duration: 4000
						});
					}
				}
			},
			//页面跳转
			goPage() {
				let self = this;
				if(self.planData[1]){
					let list = [];
					for(let i=0;i<self.planData.length;i++){
						list.push(self.planData[i].subName+'-'+self.planData[i].eventName)
					}
					uni.showActionSheet({
						itemList: list,
						success: function(res) {
							let obj = {
								buildId: self.planData[res.tapIndex].buildId,
								floorId: self.planData[res.tapIndex].floorId,
								subId: self.planData[res.tapIndex].subId,
								groupId: self.planData[res.tapIndex].eventId,
							}
							self.laboratoryBigViewGetFloorByBigView(obj);
						},
						fail: function(res) {
							// console.log(res.errMsg);
						}
					});
				}else{
					let obj = {
						buildId: self.planData[0].buildId,
						floorId: self.planData[0].floorId,
						subId: self.planData[0].subId,
						groupId: self.planData[0].eventId,
					}
					self.laboratoryBigViewGetFloorByBigView(obj);
				}
				// let obj = {
				// 	buildId: this.planData[0].buildId,
				// 	floorId: this.planData[0].floorId,
				// 	subId: this.planData[0].subId,
				// 	groupId: this.planData[0].eventId,
				// }
				// uni.navigateTo({
				// 	url: '/pages_manage/views/emergencyEvacuationBig?item=' + encodeURIComponent(JSON.stringify(
				// 		obj))
				// });
			},
		},
		onHide() {
			//清除定时器
			let self = this;
			console.log('onHide')
			self.offPlanMQTT();
		},
		beforeDestroy() {
			//清除定时器
			let self = this;
			console.log('beforeDestroy')
			self.offPlanMQTT();
		},
	}
</script>

<style lang="stylus" scoped>
	.top-warn {
		height: 80rpx;
		line-height: 80rpx;
		background rgba(2550, 0, 0, 0.2);
		margin: 20rpx 30rpx 0;
		display flex;
		overflow hidden;
		border-radius: 20rpx;

		.left-title {
			width: 100rpx;
			height: 40rpx;
			text-align: center;
			line-height: 40rpx;
			margin: 20rpx 18rpx 0 30rpx;
			color: #fff;
			font-size: 28rpx;
			background-color: #FF0000;
			border-radius: 10rpx;
		}

		.text-view {
			color: #FF0000;
			flex: 1;
			white-space: nowrap;
		}

		.button-view {
			width: 120rpx;
			height: 48rpx;
			line-height: 48rpx;
			color: #FF0000;
			border: 1px solid #FF0000;
			text-align center;
			border-radius: 50rpx;
			margin: 16rpx 12rpx 0 0;
		}
	}
</style>
