<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:{},
				//当前通道数组
				mqttIdList:[],
            }
        },
        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
                    }
                })
            },
            // 子页面调用
            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: 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', () => {
                    // 这是为了给自己发条消息，其它无作用
					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/exit/line'){
							self.client.subscribe(self.mqttIdList[i].type, (err) => {
							    if (!err) {
							        console.log("应急疏散订阅成功",self.mqttIdList[i].type)
							    }
							});
						}
					}
                });
                // 自动重连
                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/exit/line'){
							// console.log("应急",data);
							this.globalData.lineData = data.data;
						}else if(topic == 'lab/bigview'){
							// console.log("报警",data);
							if(data.data == 'SUB_RISKPLAN_GROUP'){
								this.globalData.mqttAlarmData = data.data;
							}
						}else {
							if(data.data.subId){
								// console.log('传感器',data);
							    this.globalData.mqttSensorData = data.data;
							}else{
								// console.log("设备开关",data);
								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/exit/line'){
							//断开疏散
							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>
