<script>
    import $mqtt from '@/utils/mqtt.min.js';
    import { config } from '@/api/request/config.js'
	export default {
		onLaunch: function() {
			console.log('App Launch')
      //获取openid
      uni.login({
        success(loginRes) {
          console.log('获取code成功');
          uni.setStorageSync('code', loginRes.code);
        }
      })
		},
		onShow: function() {
			this.onMQTT();

			console.log('App Show')
		},
		onHide: function() {
            this.offMQTT();
			console.log('App Hide')
		},
        data(){
		    return{
		        //MQTT数据
                client:{},
                //MQTT请求参数
                mtopicBigview:"lab/bigview",
                mtopicFunction:"lab/function/data",
                mtopicHardware:"lab/hardware/data",
				mtopicLine:"lab/exit/line",
                //监听数据
                watchObj:{},
            }
        },
        globalData:{
            mqttAlarmData:{},
            mqttSensorData:{},
            mqttDeviceData:{},
			warnData:{},
			lineData:{},
        },
        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;
            },
            //监听对应的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
                    }
                })
            },
            //MQTT订阅
            subscriptionMQTT(){
                let self = this;
                const mqttOptions = {
                    keepalive: 30,
                    clean: true,//保留会话
                    connectTimeout: 5000, // 超时时间
                    reconnectPeriod:5000, // 重连间隔
                    clientId: uni.getStorageSync('token')+'lab/function/data',
                    username: config.username,
                    password: config.password,
                }
                const connectUrl = config.mqtt_url;
                // this.client = $mqtt.connect('wxs://' + connectUrl, mqttOptions);
                this.client = $mqtt.connect('wxs://' + connectUrl, mqttOptions);
                this.client.on('connect', () => {
                    // 这是为了给自己发条消息，其它无作用
                    this.client.subscribe(this.mtopicBigview, (err) => {
                        if (!err) {
                            console.log("报警信息订阅成功",this.mtopicBigview)
                        }
                    });
                    this.client.subscribe(this.mtopicFunction, (err) => {
                        if (!err) {
                            console.log("传感器信息订阅成功",this.mtopicFunction)
                        }
                    });
                    this.client.subscribe(this.mtopicHardware, (err) => {
                        if (!err) {
                            console.log("设备信息订阅成功",this.mtopicHardware)
                        }
                    });
					//订阅应急疏散变更信息
                    this.client.subscribe(this.mtopicLine, (err) => {
                        if (!err) {
                            console.log("设备信息订阅成功",this.mtopicLine)
                        }
                    });
                });
                // 自动重连
                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) => {
                    // 把arrayBuffer转成字符串
                    let data = JSON.parse(message)
                    if(topic == this.mtopicBigview){
                        console.log("报警",data);
                        if(data.data == 'SUB_RISKPLAN_GROUP'){
                            this.globalData.mqttAlarmData = data.data;
                        }
                    }
                    if(topic == this.mtopicFunction){
                        // console.log("传感器",data);
                        this.globalData.mqttSensorData = data.data;
                    }
                    if(topic == this.mtopicHardware){
                        // console.log("设备开关",data);
                        this.globalData.mqttDeviceData = data.data;
                    }
                    if(topic == this.mtopicLine){
                        console.log("应急",data);
                        this.globalData.lineData = data.data;
                    }
                    // if(data.data.subId){
                    // 	for(let i=0;i<self.dataList.length;i++){
                    // 		if(self.dataList[i].id == data.data.subId){
                    // 		    self.$set(self.dataList[i],'sensorFunctionStatusList',data.data.functionStatuses);
                    // 		    console.log("找到了",data)
                    // 		}
                    // 	}
                    // }
                })
                // 全局监听是否有关闭mqtt的消息的事件
                uni.$on('closeMqtt',() => {
                    this.client.end(true); // 主动断开连接
                })
            },
			onMQTT(){
				console.log("onMQTT");
				if(this.client.unsubscribe){
					this.client.unsubscribe(this.mtopicBigview, error => {
						if (error) {
							console.log('Unsubscribe error mtopicBigview', error)
						}
					})
					this.client.unsubscribe(this.mtopicFunction, error => {
						if (error) {
							console.log('Unsubscribe error mtopicFunction', error)
						}
					})
					this.client.unsubscribe(this.mtopicHardware, error => {
						if (error) {
							console.log('Unsubscribe error mtopicHardware', error)
						}
					})
					this.client.unsubscribe(this.mtopicLine, error => {
						if (error) {
							console.log('Unsubscribe error mtopicLine', error)
						}
					})
					this.client.end();
					this.client = {};
				}
				this.subscriptionMQTT();
			},
            //取消订阅关闭MQTT连接
            offMQTT(){
                console.log("offMQTT");
				this.client.unsubscribe(this.mtopicBigview, error => {
					if (error) {
						console.log('Unsubscribe error mtopicBigview', error)
					}
				})
				this.client.unsubscribe(this.mtopicFunction, error => {
					if (error) {
						console.log('Unsubscribe error mtopicFunction', error)
					}
				})
				this.client.unsubscribe(this.mtopicHardware, error => {
					if (error) {
						console.log('Unsubscribe error mtopicHardware', error)
					}
				})
				this.client.unsubscribe(this.mtopicLine, error => {
					if (error) {
						console.log('Unsubscribe error mtopicLine', error)
					}
				})
				this.client.end();
				this.client = {};
            },
        }
	}
</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>
