<script>
	import indexUtil from "@/utils/indexUtil/index.js"
	import {
		deviceControl,
		dcMsgType,
		dcEventType
	} from "@/utils/indexUtil/dc.js"
	import mqttUtil from "@/utils/mqttUtil.js"

	export default {
		data() {
			return {
				ijs: new indexUtil(), //全局地块列表管理
				dc: new deviceControl(this.dcEventHandler), // 设备控制类
				mqtt: new mqttUtil(this.mqttMsgHandler), //Mqtt
			}
		},
		globalData: {},
		onLaunch: function() {
			console.log('App Launch')
		},
		onShow: function() {
			console.log('App Show')
			const that = this;

			uni.$off("notify-update-land");
			uni.$on("notify-update-land", (data) => {
				// console.error("index监听地块更新：", data)
				// uni.$emit("index-showLoading", true);
				uni.showLoading();
				that.getWoList(data, null);
			});
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			getWoList(land, wo) {
				const that = this;
				if (land && wo) {
					that.dc.setData(land, wo);
				}
				that.ijs.getWoList(land).then(res => {
					that.dc.setData(land, res.data);
					uni.hideLoading();
				}).catch(() => {
					uni.hideLoading();
				});
			},
			dcEventHandler(type, params, item) {
				switch (type) {
					case dcEventType.interface: // 界面操作
						uni.$emit("open-angle-slider", params)
						break;
					case dcEventType.refresh: // 命令刷新设备
						this.ijs.sendDeviceRefresh(item, params);
						break;
					case dcEventType.refreshApi: // 接口刷新阀门
						break;
					case dcEventType.send: // 命令控制设备
						this.ijs.sendDeviceControl(params);
						break;
					default:
						// 消息通知
						if (params.success == dcMsgType.ok) {
							this.$modal.msgSuccess(params.message);
						} else if (params.success == dcMsgType.err) {
							this.$modal.msgError(params.message);
						} else {
							this.$modal.msgWarning(params.message);
						}
						break;
				}
			},
			//Mqtt连接
			mqttLink(userId) {
				this.mqtt.link(userId);
			},
			//Mqtt订阅
			mqttSubscribes(topic) {
				if (topic) {
					this.mqtt.subscribes(topic);
				} else {
					const topic = this.dc.topic;
					if (topic.newV.length) {
						this.mqtt.subscribes(topic.newV);
					}
					if (topic.oldV.length) {
						this.mqtt.subscribes(topic.oldV);
					}
				}
			},
			//Mqtt取消订阅
			mqttUnsubscribes(topic) {
				this.mqtt.unsubscribes(topic);
			},
			//Mqtt断开连接
			mqttEnd() {
				this.mqtt.over();
			},
			//Mqtt消息回调
			mqttMsgHandler(topic, data) {
				console.error("mqttMsgHandler:", {
					topic: topic,
					data: JSON.parse(data),
				});
				this.dc.handleMessage(topic, JSON.parse(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>