<script>
	import {systemInfo} from '@/component/system-info.js'
    import $mqtt from '@/utils/mqtt.min.js';
    import { config } from '@/api/request/config.js'
	export default {
		onLaunch: function() {
			/* 获取设备信息 */
			const SystemInfomations = systemInfo()
			this.navHeight = SystemInfomations.navHeight + SystemInfomations.statusBarHeight //头部导航栏总高度
			uni.setStorageSync('navHeight', this.navHeight)
			//获取openid
			uni.login({
				success(loginRes) {
					console.log('获取code成功');
					uni.setStorageSync('code', loginRes.code);
				}
			})
			//小程序热更新
			if (wx.canIUse('getUpdateManager')) {
			  const updateManager = wx.getUpdateManager()
			  updateManager.onCheckForUpdate(function (res) {
			   if (res.hasUpdate) {
				updateManager.onUpdateReady(function () {
				 wx.showModal({
				  title: '更新提示',
				  content: '新版本已经准备好，是否重启应用？',
				  success: function (res) {
				   if (res.confirm) {
					updateManager.applyUpdate()
				   }
				  }
				 })
				})
				updateManager.onUpdateFailed(function () {
				 wx.showModal({
				  title: '已经有新版本了哟~',
				  content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
				 })
				})
			   }
			  })
			 } else {
			  wx.showModal({
			   title: '提示',
			   content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
			  })
			 }
		},
		onShow: function() {
		},
		onHide: function() {
		},
        data(){
		    return{
		        //MQTT数据
                client:{},
                //MQTT请求参数
                mtopicBigview:"lab/bigview",
                mtopicFunction:"lab/function/data",
                mtopicHardware:"lab/hardware/data",
				mtopicLine:"lab/riskPlan/trigger/notice",
                //监听数据
                watchObj:{},
				//当前通道数组
				mqttIdList:[],
            }
        },
        globalData:{
            mqttAlarmData:{},
            mqttSensorData:{},
            mqttDeviceData:{},
			warnData:{},
			lineData:{},
			mqttfireData:{},//灭火传感器状态异常
			mqttOnlineData:{},//设备是否在线
			mqttPerformData:{},//是否正在执行灭火操作
        },
		created() {
			
			
		},
        methods: {
			//删除报警监听
			delWarnData(){
				delete this.watchObj.warnData;
			},
		    //删除报警监听
            deleteAlarmWatch(){
                delete this.watchObj.mqttAlarmData;
            },
		    //删除传感器监听
            deleteSensorWatch(){
                delete this.watchObj.mqttSensorData;
            },
		    //删除设备监听
            deleteDeviceWatch(){
                delete this.watchObj.mqttDeviceData;
            },
		    //删除应急监听
            deleteLineData(){
                delete this.watchObj.lineData;
            },
			//删除一键灭火-传感器状态
			deletefireData(){
			    delete this.watchObj.mqttfireData;
			},
			//删除一键灭火-设备是否在线
			deleteOnlineData(){
			    delete this.watchObj.mqttOnlineData;
			},
			//删除一键灭火-是否正在执行灭火
			deletePerformData(){
			    delete this.watchObj.mqttPerformData;
			},
            //监听对应的mqtt数据
            watch:function(method,istr){
                this.watchObj = this.globalData;
                Object.defineProperty(this.watchObj,istr,{
                    configurable:true,
                    enumerable:true,
                    immediate: true,
                    deep: true,
                    set:function(value){
                        this._consumerGoodsStatus=value
                        method(value)
                    },
                    get:function(value){
                        return this._consumerGoodsStatus
                    }
                })
            },
            // 子页面调用
            appMqttOn(type,list){
            	let self = this;
            	if(this.mqttIdList){
            		this.offMQTT();
            	}
            	uni.setStorageSync('mqttIdList',JSON.stringify(list));
            	this.mqttIdList = list;
            	setTimeout(function(){
            		self.subscriptionMQTT();
            	},100);
            },
			//MQTT订阅
            subscriptionMQTT(){
                let self = this;
                const mqttOptions = {
                    keepalive: 30,
                    clean: true,//保留会话
                    connectTimeout: 5000, // 超时时间
                    reconnectPeriod:5000, // 重连间隔
                    clientId: uni.getStorageSync('token')+'lab/function/data',
                    username: uni.getStorageSync('mqttUser'),
                    password: uni.getStorageSync('mqttPassword'),
                }
                const connectUrl = uni.getStorageSync('mqttUrl');
                // this.client = $mqtt.connect('wxs://' + connectUrl, mqttOptions);
                this.client = $mqtt.connect('wxs://' + connectUrl, mqttOptions);
                this.client.on('connect', () => {
                    // 这是为了给自己发条消息，其它无作用
					for(let i=0;i<self.mqttIdList.length;i++){
						if(self.mqttIdList[i].type == 'lab/function/data'){
							//传感器
							for(let o=0;o<self.mqttIdList[i].idList.length;o++){
								self.client.subscribe(self.mqttIdList[i].type+self.mqttIdList[i].idList[o], (err) => {
								    if (!err) {
								        console.log("传感器信息订阅成功",self.mqttIdList[i].type+self.mqttIdList[i].idList[o])
								    }
								});
							}
						}else if(self.mqttIdList[i].type == 'lab/hardware/data'){
							//传感器
							for(let o=0;o<self.mqttIdList[i].idList.length;o++){
								self.client.subscribe(self.mqttIdList[i].type+self.mqttIdList[i].idList[o], (err) => {
								    if (!err) {
								        console.log("硬件订阅成功",self.mqttIdList[i].type+self.mqttIdList[i].idList[o])
								    }
								});
							}
						}else if(self.mqttIdList[i].type == 'lab/bigview'){
							self.client.subscribe(self.mqttIdList[i].type, (err) => {
							    if (!err) {
							        console.log("报警信息订阅成功",self.mqttIdList[i].type)
							    }
							});
						}else if(self.mqttIdList[i].type == 'lab/riskPlan/trigger/notice'){
							self.client.subscribe(self.mqttIdList[i].type, (err) => {
							    if (!err) {
							        console.log("应急疏散订阅成功",self.mqttIdList[i].type)
							    }
							});
						}else if(self.mqttIdList[i].type == 'lab/fireDevice/Warn/'){
							self.client.subscribe(self.mqttIdList[i].type+self.mqttIdList[i].fireCode, (err) => {
							    if (!err) {
							        console.log("火灾传感器状态-订阅成功",self.mqttIdList[i].type+self.mqttIdList[i].fireCode)
							    }
							});

						}else if(self.mqttIdList[i].type == 'lab/fireDevice/isOnline/'){
							self.client.subscribe(self.mqttIdList[i].type+self.mqttIdList[i].fireCode, (err) => {
							    if (!err) {
							        console.log("火灾设备是否在线-订阅成功",self.mqttIdList[i].type+self.mqttIdList[i].fireCode)
							    }
							});

						}else if(self.mqttIdList[i].type == 'lab/fireDevice/executing/'){
							self.client.subscribe(self.mqttIdList[i].type+self.mqttIdList[i].fireCode, (err) => {
							    if (!err) {
							        console.log("火灾是否正在执行灭火操作-订阅成功:",self.mqttIdList[i].type+self.mqttIdList[i].fireCode)
							    }
							});

						}
					}
                });
                // 自动重连
                this.client.on('reconnect', (msg) => {
                    console.log('自动重连-reconnect-1', msg)
                });
                // 错误
                this.client.on('error', () => {
                    console.log('错误-error-1')
                });
                // 断开
                this.client.on('end', () => {
                    console.log('断开-end-1')
                });
                // 掉线
                this.client.on('offline', (msg) => {
                    console.log('掉线-offline-1',msg)
                });
                // 收到消息
                this.client.on('message', (topic, message) => {
                    let data = JSON.parse(message)
					 //console.log('消息message',data);
					if(data){
						if(topic == 'lab/riskPlan/trigger/notice'){
							// console.log("应急",data);
							this.globalData.lineData = data.data;
						}else if(topic.search("lab/fireDevice/Warn/") != -1){
							 console.log("一键灭火-传感器状态",data);
							this.globalData.mqttfireData = data;
						}else if(topic.search("lab/fireDevice/isOnline/") != -1){
							 console.log("一键灭火-设备是否在线",data);
							this.globalData.mqttOnlineData = data;
						}else if(topic.search("lab/fireDevice/executing/") != -1){
							 console.log("一键灭火-是否正在执行灭火",data);
							this.globalData.mqttPerformData = data;
						}else if(topic == 'lab/bigview'){
							if(data.data == 'SUB_RISKPLAN_GROUP'){
								this.globalData.mqttAlarmData = data.data;
							}
						}else {
							if(data.data.subId){
							    this.globalData.mqttSensorData = data.data;
							}else{
								this.globalData.mqttDeviceData = data.data;
							}
						}
					}
                })
                // 全局监听是否有关闭mqtt的消息的事件
                uni.$on('closeMqtt',() => {
                    this.client.end(true); // 主动断开连接
                })
            },
            //取消订阅关闭MQTT连接
            offMQTT(){
				let self = this;
				if(self.mqttIdList[0]){
					uni.removeStorageSync('mqttIdList')
					for(let i=0;i<self.mqttIdList.length;i++){
						if(self.mqttIdList[i].type == 'lab/function/data'){
							//断开传感器
							for(let o=0;o<self.mqttIdList[i].idList.length;o++){
								self.client.unsubscribe(self.mqttIdList[i].type+self.mqttIdList[i].idList[o], error => {
									if (error) {
										console.log('Unsubscribe error mtopicBigview', error)
									}
								})
							}
						}else if(self.mqttIdList[i].type == 'lab/hardware/data'){
							//断开硬件
							for(let o=0;o<self.mqttIdList[i].idList.length;o++){
								self.client.unsubscribe(self.mqttIdList[i].type+self.mqttIdList[i].idList[o], error => {
									if (error) {
										console.log('Unsubscribe error mtopicBigview', error)
									}
								})
							}
						}else if(self.mqttIdList[i].type == 'lab/bigview'){
							//断开报警
							self.client.unsubscribe(self.mqttIdList[i].type, error => {
								if (error) {
									console.log('Unsubscribe error mtopicBigview', error)
								}
							})
						}else if(self.mqttIdList[i].type == 'lab/riskPlan/trigger/notice'){
							//断开疏散
							self.client.unsubscribe(self.mqttIdList[i].type, error => {
								if (error) {
									console.log('Unsubscribe error mtopicBigview', error)
								}
							})
						}
					}
					this.client.end(true);
					this.client = null;
					this.mqttIdList = [];
				}
            },
        }
	}
</script>

<style lang="stylus">
	page{
		height:100%;
		width:100%;
		background:#f5f5f5;
		font-family: PingFang SC;
		font-weight: 400;
		font-size:30rpx;
		color:#333;
	}
	img{
        margin:0;
        padding:0;
		display:block;
	}
	.name-box-p{
		display block
		overflow:hidden;
		text-overflow:ellipsis;
		white-space:nowrap;
	}
    view{
        margin:0;
        padding:0;
    }
    /*每个页面公共css */
    @import './styles/index.styl'
</style>
