<script>
	import '@/common/request/request.js';
	import piniaPro from '@/stores/piniaPro.js';
	import {
		globalStore
	} from "@/stores/globalData.js";
	const globalData = globalStore(piniaPro);

	import config from '@/common/config/config.js';
	// var mqtt = require('./static/mqtt/dist/mqtt.min.js');
	export default {
		globalData: {
			client: null,
			phone:null
		},
		onLaunch: function() {
			// console.log('App Launch')
		},
		onShow: function() {
			// uni.$request({ //刷新token
			// 	url: config.baseUrl + "service-miniapp/customer/refresh",
			// 	method: 'POST',
			// }).then(res => {
			// 	if (res.data.code == 401 || res.data.msg == "Error token") {
			// 		//退出清除用户数据
			// 		uni.removeStorageSync("token"); //"用户Token"
			// 		uni.removeStorageSync("userInfo");
			// 		globalData.isLogin = false
			// 		console.log('用户Token清空====退出');
			// 		return;
			// 	} else {
			// 		uni.setStorageSync("token", res.data.msg); //"用户Token"  
			// 		console.log('用户Token已更新');
			// 		globalData.isLogin = true
			// 		console.log(globalData.isLogin, 'globalData.isLogin======已登录')
					
			// 		// 秦欧定制  交接班推送连接
			// 		let userInfo= uni.getStorageSync('userInfo')
			// 		getApp().phone=userInfo.phone
			// 		console.log(getApp().phone,'getApp().phone');
			// 		getApp().onClick_connect()
			// 		if(config.style===1){
			// 			let userInfo= uni.getStorageSync('userInfo')
			// 			getApp().phone=userInfo.phone
			// 			console.log(getApp().phone,'getApp().phone');
			// 			getApp().onClick_connect()
			// 		}
			// 		// 秦欧定制  交接班推送连接
			// 		return;
			// 	}
			// })
			// console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			//
			randomString(len) {
				len = len || 32;
				var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
				var maxPos = $chars.length;
				var pwd = '';
				for (let i = 0; i < len; i++) {
					pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
				}
				return pwd;
			},
			onClick_connect () {
				const host = config.mqtt_host
			   const options = {
			   	clientId: getApp().phone + '_' + getApp().randomString(8),
			   	password: 'public',
			   	username: 'admin',
			   	connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
			   }
			
			    //开始连接
			    getApp().globalData.client = mqtt.connect(host, options);
			    getApp().globalData.client.on('connect', function (connack) {
			      console.log("连接成功！")
			      //订阅主题
			      getApp().onClick_SubOne();
			    })
			
			    //接收服务器消息通知
			    getApp().globalData.client.on("message", function (topic, payload) {
			     console.log(" 收到 topic:" + topic + " , payload :" + payload)
			      //that.globalData.topicMessage = "" + payload;
			      let topicData = "" + payload;
			      uni.showModal({
			        title: '提示',  
			        content: '您有新的交接班待确认！',
			        cancelText: '取消',
			        confirmText: '去看看',
			        success: function (res) {
			          if (res.cancel) {} else {  
			            uni.reLaunch({
			              url: '/pagesCenter/shiftTurnover/associateList'
			            })
			          }
			        }
			      })
			    })
			
			    //服务器连接异常的回调
			    getApp().globalData.client.on("error", function (error) {
			      console.log(" 服务器 error 的回调" + error)
			    })
			
			    //服务器重连连接异常的回调
			    getApp().globalData.client.on("reconnect", function () {
			      console.log(" 服务器 reconnect的回调")
			    })
			
			    //服务器连接异常的回调
			    getApp().globalData.client.on("offline", function (errr) {
			      console.log(" 服务器offline的回调")
			    })
			
			  },
			onClick_SubOne() {
				let subTopic = 'changeShifts/' + getApp().phone;
				if (getApp().globalData.client && getApp().globalData.client.connected) {
					//仅订阅单个主题             
					getApp().globalData.client.subscribe(subTopic, function(err, granted) {
						if (!err) {
							console.log("订阅主题成功！")
						} else {
							uni.showToast({
								title: '订阅主题失败',
								icon: 'fail',
								duration: 2000
							})
						}
					})
				} else {
					uni.showToast({
						title: '请先连接服务器',
						icon: 'none',
						duration: 2000
					})
				}
			},
		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	@import "@/uni_modules/uview-plus/index.scss";
	@import "@/colorui/main.css";
	@import "@/colorui/icon.css";
</style>