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

	export default {
		data() {
			return {
				mqtt: null,
				mqttObj: {
					topics: []
				}
			}
		},
		globalData: {},
		onLaunch: function() {
			console.log('App Launch')
			// #ifdef H5
			this.mqtt = new mqttUtil();
			// #endif

			// 监听mqtt连接命令
			uni.$on("mqtt-link", () => {
				this.mqttLink();
			});
			// 监听mqtt连接订阅命令
			uni.$on("mqtt-subscribes", topics => {
				this.mqttSubscribes();
			});
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			setTime: function() {
				console.error(this.globalData.num);
				// setTimeout(() => {
				// 	this.globalData.num++
				// 	console.error(this.globalData.num);
				// 	this.setTime();
				// }, 1000)
			},
			mqttLink() {
				// 处理 wx.connectSocket promisify 兼容问题，强制返回 SocketTask
				uni.connectSocket = (function(connectSocket) {
					return function(options) {
						console.log(options)
						options.success = options.success || function() {}
						return connectSocket.call(this, options)
					}
				})(uni.connectSocket)

				console.error("mqttLink");
				// #ifdef H5
				this.mqtt.link();
				this.mqtt.client.on("connect", error => {
					console.log("连接成功")
					console.error("client:", this.mqtt.client);
				})
				this.mqtt.client.on("error", error => {
					console.log("连接异常")
				})
				this.mqtt.client.on("reconnect", error => {
					console.log("重新连接")
				})
				this.mqtt.client.on("message", (topic, message) => {
					console.log("接受消息")
					console.log("message：", message.toString())
					this.mqttSendMsg(message);
				})
				// #endif

			},
			mqttSubscribes(topics) {
				this.mqttObj.topics = topics;
				console.error("mqttSubscribes:", topics);
			},
			mqttSendMsg(msg) {
				uni.$emit("mqtt-msg", msg);
			},
		}
	}
</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>