<script>
	/* eslint-disable */
	import Vue from 'vue';
	import {
		configList,
		bindingEquipment
	} from '@/api/basic';
	import {
		verifyAccessToken
	} from '@/api/login'
	import {
		mapMutations
	} from 'vuex';
	export default {
		onLaunch() {
			this.initData();
			this.checkApk();
		},
		onHide() {},
		methods: {
			//...mapMutations(['setNotifyNum']),
			// 数据初始化
			initData() {
				// 获取页面设置配置
				const _this = this;
				const token = uni.getStorageSync('accessToken');
				// #ifdef APP-PLUS
				// 5+ push 消息推送 ps:使用:H5+的方式监听，实现推送
				plus.push.addEventListener(
					'click',
					function(msg) {
						_this.navTo(JSON.parse(msg.content));
					},
					false
				);
				// 监听在线消息事件
				plus.push.addEventListener(
					'receive',
					function(msg) {
						_this.navTo(JSON.parse(msg.content));
					},
					false
				);
				// #endif
				// 获取系统title高度
				this.initSystemInfo();
				if (token) {
					this.handleVerifyAccessToken(token);
				}
				if (this.$mStore.getters.hasLogin) {
					// 初始化Websocket
					// await this.$mWebsocket.initWebsocket();
					// 初始化数量
					//this.setNotifyNum(uni.getStorageSync('notifyNum') || 0);
					// #ifdef APP-PLUS
					const info = plus.push.getClientInfo();
					//await this.handleBindingEquipment(info.clientid, token);
					// #endif
					this.getTabBarBadge();
				}

			},
			// 初始化系统信息
			initSystemInfo() {
				uni.getSystemInfo({
					success(e) {
						// #ifndef MP
						Vue.prototype.StatusBar = e.statusBarHeight;
						if (e.platform === 'android') {
							Vue.prototype.CustomBar = e.statusBarHeight + 50;
						} else {
							Vue.prototype.CustomBar = e.statusBarHeight + 43;
						}
						// #endif
						// #ifdef MP-WEIXIN
						Vue.prototype.StatusBar = e.statusBarHeight;
						const custom = wx.getMenuButtonBoundingClientRect();
						Vue.prototype.Custom = custom;
						Vue.prototype.CustomBar = custom.top - e.statusBarHeight;
						// #endif
						// #ifdef MP-ALIPAY
						Vue.prototype.StatusBar = e.statusBarHeight;
						Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
						// #endif
					}
				});
			},


			// 设备绑定(app推送)
			async handleBindingEquipment(id, token) {
				const oauth_client = uni.getSystemInfoSync().platform;
				await this.$http.post(bindingEquipment, {
					token,
					oauth_client,
					oauth_client_user_id: id
				});
			},
			async handleVerifyAccessToken(token) {
				var url = this.$mConfig.baseUrl + '/fw/Refresh';
				this.$http.request({
					url: url,
					method: "POST",
					header: {
						'content-type': 'application/json',
						'Authorization': token
					}
				}).then(r => {
					if (!r.loginUser.token) {
						this.$mStore.commit('logout');
					} else {
						this.$store.commit('login', r);
					}
				})
			},
			// 推送消息跳转
			async navTo(item) {
				let route;
				const id = item.target_id;
				const type = item.target_type;
				switch (type) {

					default:
						route = '/pages/index/index';
						break;
				}
				if (route) this.$mRouter.push({
					route
				});
			},
			//检查更新
			checkApk() {
				let url = this.$mConfig.baseUrl + '/appinterface/ip/version';
				this.$http.request({
					url: url,
					header: {
						'content-type': 'application/json'
					},
				}).then(res => {
					//获取到的app最新版本号
					//获取url
					let url = res.data.dataUrl;
					let app_last_version = res.data.lastVersion;
					// let nativeVersion = plus.runtime.version;
					console.log("服务器版本：" + app_last_version)
					// console.log("客户端版本：" + nativeVersion)
					//修改版本判断
					let that = this
					var result = null
					var ss = null
					// #ifdef APP-PLUS
					plus.runtime.getProperty( plus.runtime.appid, async function ( wgtinfo ) {
						console.log("当前app版本"+wgtinfo.version)
						result = that.compareVersion(wgtinfo.version, app_last_version);
						that.checkAndInstall(res,result)
					} );
					// #endif
				})
			},
			//版本号对比:当且仅当本地版本号小于请求的版本号则返回 true
			compareVersion(nativeVersion, lastVersion) {
				nativeVersion = nativeVersion.split('.');
				lastVersion = lastVersion.split('.');
				let n = Math.max(nativeVersion.length, lastVersion.length)
				for (let i = 0; i < n; i++) {
					let code1 = (nativeVersion[i] === undefined) ? 0 : parseInt(nativeVersion[i]);
					let code2 = (lastVersion[i] === undefined) ? 0 : parseInt(lastVersion[i]);
					if (code1 > code2) {
						this.$needUpdate = false;
						return false
					} else if (code1 < code2) {
						return true
					}
				}
				this.$needUpdate = false;
				return false;
				
			},
			//下载和安装apk
			downloadApk(url) {
				let that = this;
				let watiting = plus.nativeUI.showWaiting("下载文件...");
				let dtask = plus.downloader.createDownload(url, {
					method: "GET",
					retry: 0,
				});

				dtask.addEventListener(
					"statechanged",
					function(task, status) {
						if (!dtask) {
							return;
						}
						switch (task.state) {
							case 1:
								break;
							case 2:
								break;
							case 3:
								var nowData = Math.floor(
									(task.downloadedSize * 100) / task.totalSize
								);
								watiting.setTitle("已下载：" + nowData + "%");
								if (nowData === 100) {
									watiting.toast("正在准备环境，请稍后！");
									watiting.close();
								}
								break;
							case 4:
								// 安装apk资源包
								plus.runtime.install(
									dtask.filename, {},
									function() {
										plus.nativeUI.closeWaiting();
										this.$needUpdate = false;
										plus.runtime.restart();
										//  plus.nativeUI.alert("更新完成！", function () {
										// //  更新完成后重启应用
										// plus.runtime.restart();
										//  });
									},
									function(e) {
										plus.nativeUI.closeWaiting();
										plus.nativeUI.toast("安装更新失败！");
										this.$needUpdate = true;
									}
								);
								break;
							default:
								break;
						}
					},
					false
				);
				dtask.setRequestHeader("Access-Control-Allow-Origin", "*");
				dtask.start();
			},
			//安装wgt
			downloadWgt(url){
				
				uni.downloadFile({  
					url: url,  
					success: (downloadResult) => {  
						plus.nativeUI.showWaiting("下载wgt文件...");
						// console.log(plus.runtime.version)
						// console.log(url)
						// console.log(downloadResult.tempFilePath+'==========='+downloadResult.statusCode)
						if (downloadResult.statusCode === 200) {  
							
							plus.nativeUI.toast("正在准备环境");
							plus.runtime.install(downloadResult.tempFilePath, {  
								force: true  
							}, function() {  
								plus.nativeUI.closeWaiting();
								plus.nativeUI.toast("更新成功，正在重启应用！");
								this.$needUpdate = false;
								plus.runtime.restart();  
							}, function(e) {  
								plus.nativeUI.closeWaiting();
								plus.nativeUI.toast("安装更新失败！");
								this.$needUpdate = true;
							});  
						}  
					}  
				});  
			},
		
			checkAndInstall(res,result){
				if (result) {
					uni.showModal({
						title: "有新的版本",
						content: "请确认是否更新?",
						success: (info) => {
							if (info.confirm) {
								// 因为App.vue中不能直接使用组件，这里用到了vuex来调用下载进度的组件
								// 显示下载进度弹窗
								// this.$store.commit('setHide',true)
								if (plus.os.name.toLowerCase() == 'ios') {
									// ios直接跳转到下载页面
									let downloadUrl = this.$mConfig.baseUrl + res.data.dataUrl
									plus.runtime.openURL(downloadUrl)
								} else {
										let downloadUrl = this.$mConfig.baseUrl + res.data.dataUrl
										if(downloadUrl.substring(downloadUrl.lastIndexOf(".")+1) == "apk"){
											return this.downloadApk(downloadUrl)
										}else if(downloadUrl.substring(downloadUrl.lastIndexOf(".")+1) == "wgt"){
											return this.downloadWgt(downloadUrl)
										}
									}
							}
						}
					})
				} else {
					this.$needUpdate = false;
					return;
				}
			}
		}
	};
</script>
<style lang="scss">
	// 导入colorUI
	@import '/static/css/colorui/main.css';
	@import '/static/css/colorui/icon.css';
	@import '/static/css/colorui/animation.css';
	// 导入阿里巴巴矢量图标库
	/*#ifdef MP*/
	@import './static/css/iconfont/iconfont.css';
	/*#endif*/
	/*#ifndef MP*/
	@import url('https://at.alicdn.com/t/font_1823374_98c45zxwb3c.css');
	/*#endif*/
	@import './static/css/reset.scss';
	@import './static/css/uni.scss';
</style>
