<script>
	// import '@/static/font/iconfont.js'
	import indexUtil from "@/utils/indexUtil/index.js"
	import {
		deviceControl,
		dcMsgType,
		dcEventType
	} from "@/utils/indexUtil/dc.js"
	import mqttUtil from "@/utils/mqttUtil.js"
	const mqttUrl = import.meta.env.VITE_BASE_MQTT;
	import {
		getNewAppVersion
	} from '@/api/index.js'

	export default {
		data() {
			return {
				ijs: new indexUtil(), //全局地块列表管理
				dc: new deviceControl(2, this.dcEventHandler), // 设备控制类
				mqtt: null, //Mqtt
				isFirseLink: true, //Mqtt第一次链接
				topics: null,
				mqttFun: {},
				landFun: {},
				version: {
					oldV: null,
					newV: null,
				},
			}
		},
		globalData: {},
		onLaunch: function() {
			console.log('App Launch')
			// #ifdef APP-PLUS
			plus.screen.lockOrientation("portrait-primary")
			// #endif
		},
		onShow: function() {
			console.log('App Show')
			const that = this;
			//监听公司点击
			uni.$off("notify-add-land");
			uni.$on("notify-add-land", (data) => {
				// console.error("notify-add-land：", data);
				that.getLand(data);
			});
			//监听地块选择
			uni.$off("notify-update-land");
			uni.$on("notify-update-land", (data) => {
				// console.error("notify-update-land：", data)
				// uni.$emit("index-showLoading", true);
				uni.showLoading();
				that.getWoList(data, null);
			});
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			initApp() {
				// this.ijs = new indexUtil(); //全局地块列表管理
				// this.dc = new deviceControl(2, this.dcEventHandler); // 设备控制类
				this.mqtt = new mqttUtil(mqttUrl, this.mqttStateHandler, this.mqttMsgHandler); //Mqtt

				// 检测新版本
				// #ifdef H5
				this.version.oldV = {
					versionName: "1.0.0", //网页版
					versionCode: "1",
					// versionCode: "9999999999",
				}
				// #endif
				// #ifdef APP-PLUS
				plus.runtime.getProperty(plus.runtime.appid, widgetInfo => {
					this.version.oldV = {
						versionName: widgetInfo.version,
						versionCode: widgetInfo.versionCode,
					}
				})
				getNewAppVersion().then(res => {
					this.setUpdateVersion(res.data);
				})
				// #endif
			},
			// 添加一个消息回调
			on(type, key, callBack) {
				switch (type) {
					case "land": //地块消息回调
						this.landFun[key] = callBack;
						break;
					case "mqtt": //mqtt消息回调
						this.mqttFun[key] = callBack;
						break;
				}
			},
			// 删除一个消息回调
			off(type, key) {
				switch (type) {
					case "land": //地块消息回调
						delete this.landFun[key]
						break;
					case "mqtt": //mqtt消息回调
						delete this.mqttFun[key]
						break;
				}
			},
			// 给某个回调函数发送数据
			sendMsgEvent(type, data) {
				let func = {};
				switch (type) {
					case "land": //地块消息回调
						func = this.landFun;
						break;
					case "mqtt": //mqtt消息回调
						func = this.mqttFun;
						break;
				}
				for (let _key in func) {
					if (typeof func[_key] === 'function') {
						func[_key](data);
					} else {
						delete func[_key]
					}
				}
			},
			getLand(e) {
				this.ijs.getLand(e.node).then(data => {
					// this.$refs.landRef.addLand(e, data);
					this.sendMsgEvent("land", {
						type: "add",
						data: {
							item: e,
							lands: data
						}
					});
				});
			},
			getWoList(land, wo) {
				const that = this;
				if (land && wo) {
					that.dc.setData(land, wo);
					that.mqttSubscribes();
					that.sendMsgEvent("land", {
						type: "wo",
						data: wo
					});
				}
				that.ijs.getWoList(land).then(res => {
					that.dc.setData(land, res.data);
					that.mqttSubscribes();
					that.sendMsgEvent("land", {
						type: "wo",
						data: 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).then(res => {
							if (res.data) {
								for (var key in res.data) {
									res.data[key].refresh = true;
									this.dc.dataObj[key] = res.data[key];
								}
							}
						}).catch(error => {
							this.dc.clearRefreshCountdown(params.deviceCode);
						});
						break;
					case dcEventType.refreshApi: // 接口刷新阀门
						this.ijs.refreshControlling().then(res => {
							if (res.data) {
								for (var key in res.data) {
									this.dc.dataObj[key] = res.data[key];
								}
							}
						});
						break;
					case dcEventType.send: // 命令控制设备
						this.ijs.sendDeviceControl(params).then(res => {
							this.setBtnPreloading(item, params.angleKey, params.params.index, params.params.value)
						}).catch(error => {
							this.dc.clearCountdown(params.angleKey);
						});
						break;
					default:
						// 消息通知
						this.$toast(params.message)
						break;
				}
			},
			//Mqtt连接
			mqttLink(userId) {
				this.mqtt.link(userId);
			},
			//Mqtt订阅
			mqttSubscribes(topics) {
				if (topics) {
					this.mqtt.subscribes(topics);
				} 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(topics) {
				this.mqtt.unsubscribes(topics);
			},
			//Mqtt断开连接
			mqttEnd() {
				this.mqtt.over();
			},
			//Mqtt状态回调
			mqttStateHandler(e) {
				this.sendMsgEvent("mqtt", {
					type: "state",
					connected: e,
				});
				if (this.isFirseLink) {
					this.mqttSubscribes();
				}
			},
			//Mqtt消息回调
			mqttMsgHandler(topic, data) {
				console.error("mqttMsgHandler:", {
					topic: topic,
					data: JSON.parse(data),
				});
				this.dc.handleMessage(topic, JSON.parse(data));
				this.sendMsgEvent("mqtt", {
					type: "msg",
					topic: topic,
					data: JSON.parse(data),
				});
			},
			setUpdateVersion(data) {
				if (data) {
					let isLatestVersion = Number(this.version.oldV.versionCode) >= Number(data.versionCode);
					if (isLatestVersion) {
						this.version.newV = null;
					} else {
						this.version.newV = {
							versionName: data.versionName, //版本名称
							versionCode: data.versionCode, //版本号
							versionUrl: data.versionUrl, //下载地址
							isForceUpdate: data.forceUpgrade == 0, //强制升级
						}
					}
				} else {
					this.version.newV = null;
				}
			},
		}
	}
</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>