<script>
	import indexUtil from "@/utils/indexUtil.js"
	import dc from "@/utils/deviceUtil/dc.js"
	import mqttUtil from "@/utils/mqttUtil.js"

	export default {
		data() {
			return {
				indexData: new indexUtil(this.indexDataHandler), //全局地块列表管理
				dc: new dc(), // 设备控制类
				mqtt: new mqttUtil(this.mqttMsgHandler), //Mqtt
			}
		},
		globalData: {},
		onLaunch: function() {
			console.log('App Launch')
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			//监听indexData的回调
			indexDataHandler(e, data) {
				if (e == this.indexData.eventType.land) {
					// console.error("地块更新通知:", this.indexData.selectItem)
					this.dc.setLandItem(this.indexData.selectItem, null);
				}
				if (e == this.indexData.eventType.device) {
					// console.error("设备更新通知:", this.indexData.device)
					this.dc.setStations(this.indexData.device.stations);
					this.dc.setFlapValves(this.indexData.device.flapValves);
					this.dc.setValves(this.indexData.selectItem.id, this.indexData.device.waterOutlets);

					const obj = this.dc.topic;
					if (obj.newV && obj.newV.length) {
						this.mqttSubscribes(obj.newV); //订阅主题
					}
					if (obj.oldV && obj.oldV.length) {
						this.mqttUnsubscribes(obj.oldV); //取消订阅主题
					}

					this.indexData.setStorage(3, {
						userId: this.indexData.userId,
						landId: this.indexData.selectItem.id,
						stations: this.dc.stations,
						flapValves: this.dc.flapValves,
						waterOutlets: this.dc.valves,
					});
				}
				uni.hideLoading();
				// console.error("indexDataHandler:", {
				// 	e: e,
				// 	data: data,
				// 	indexData: this.indexData,
				// 	dc: this.dc,
				// })
			},
			//Mqtt连接
			mqttLink(userId) {
				this.mqtt.link(userId);
			},
			//Mqtt订阅
			mqttSubscribes(topics) {
				this.mqtt.subscribes(topics);
			},
			//Mqtt取消订阅
			mqttUnsubscribes(topics) {
				this.mqtt.unsubscribes(topics);
			},
			//Mqtt断开连接
			mqttEnd() {
				this.mqtt.over();
			},
			//Mqtt消息回调
			mqttMsgHandler(topic, data) {
				console.error("mqttMsgHandler:", {
					topic: topic,
					data: data,
				});
			},
		}
	}
</script>

<style lang="scss">
	@import '@/uni_modules/uview-plus/index.scss';
	@import '@/static/scss/index.scss';
	@import '@/static/alifont/iconfont.css';
	@import '@/static/scss/app.css';
</style>