<script>
	/* eslint-disable */
	import Vue from 'vue';
	import request from '@/utils/request'
	import {
		verifyAccessToken
	} from '@/api/login'
	import {
		mapMutations
	} from 'vuex';
	// import startPage from './pages/index/startPage'
	export default {
		async onLaunch() {
			//app设置当前语言
			var lan = 'zh'
			try {
				const res = uni.getSystemInfoSync();
				lan = res.language
			} catch (e) {
				console.log('error=' + e)
			}
			console.log('lan=' + lan);
			if (lan !== 'zh' || lan == 'en' || lan !== 'zh-Hans-CN') {
				this.$i18n.locale = 'en'
			}
			if (lan == 'zh-CN' || lan == 'zh' || lan == 'zh-Hans-CN') {
				this.$i18n.locale = 'zh'
			}
			//#ifdef APP-PLUS
			let client_info = plus.push.getClientInfo(); //获取客户端clientId（这个id每次重新安装包就会刷新
			console.log("xxxxxxxxxxx" + JSON.stringify(client_info));
			// #endif
			//获取手机属于iOS或者安卓
			var platform = uni.getSystemInfoSync().platform;
			console.log(platform);
			//收到透传消息
			//只有APP在线时，才会触发receive事件，透传消息不会触发系统消息,需要创建本地消息
			//#ifdef APP-PLUS
			plus.push.addEventListener("receive", function(msg) {
				console.log("(receive):" + JSON.stringify(msg));
				console.log("(receive):" + JSON.stringify(msg.payload));
				if (platform == "ios") { //如果是IOS
					//plus.push.createMessage(msg.title,msg.content);
					var payload = msg.payload;
					//【APP离线】收到消息，但没有提醒（发生在一次收到多个离线消息时，只有一个有提醒，但其他的没有提醒）
					//【APP在线】收到消息，不会触发系统消息,需要创建本地消息，但不能重复创建。必须加msg.type验证去除死循环
					if (msg.aps == null && msg.type == "receive") {
						console.log(typeof(payload));
						var messageTitle = payload.title;
						var messageContent = payload.content;
						//创建本地消息,发送的本地消息也会被receive方法接收到，但没有type属性，且aps是null
						plus.push.createMessage(messageContent, JSON.stringify(payload), {
							title: messageTitle
						});
					}
				} else if (platform == "android") {
					var payload = msg.payload;
					var messageTitle = payload.title;
					var messageContent = payload.content;
					console.log("(receive。。。。。):" + payload.url);
					//plus.push.createMessage(messageContent, msg, {title: messageTitle});
					setTimeout(function() {
						uni.navigateTo({
							url: payload.url
						})
					}, 1000)
				}
			}, false);

			//消息点击事件
			//【APP在线】，收到透传消息通过，不会提醒至通知栏目，需要发送本地消息，再进行点击触发的点击事件。
			//【APP离线】，收到离线透传消息，必须通过Java后台的Intent字符串携带payload，且符合格式才能触发click事件，格式不符合不会触发。
			plus.push.addEventListener("click", function(msg) {
				console.log('click');
				console.log("(click):" + JSON.stringify(msg));
				console.log("(click):" + JSON.stringify(msg.payload));
				if (platform == "ios") { //如果是IOS
					var payload;
					if (msg.type == "click") { //APP离线点击包含click属性，这时payload是JSON对象
						payload = msg.payload;
					} else { //APP在线，收到消息不会包含type属性,这时的payload是JSON字符串，需要转为JSON对象
						payload = JSON.parse(msg.payload);
					}
					if (payload != null || payload != undefined) {
						setTimeout(function() {
							uni.navigateTo({
								url: payload.url
							})
						}, 1000)
					}
				}
				if (platform == "android") {
					setTimeout(function() {
						uni.navigateTo({
							url: msg.payload.url
						})
					}, 1000)
				}
			}, false);

			plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
				let BASE_URL = 'https://www.geidcp.com/api'
				uni.request({
					url: BASE_URL + '/project/appSoftwares/searchIsNew',
					method: 'get',
					data: {
						//当前版本
						currentVersion: widgetInfo.version,
						//当前软件名称
						softwareName: widgetInfo.name,
						//系统类型
						softwarePlatformTypeDict: plus.os.name
					},
					success: (result) => {
						var data = result.data.data;
						if (data.flag == false) {
							uni.showModal({
								title: '版本更新',
								content: '发现新版本请问是否进行更新',
								success: function(e) {
									if (e.confirm) {
										var dtask = plus.downloader.createDownload(
											'https://www.geidcp.com/' + data
											.wgt, {},
											function(d, status) {
												uni.showToast({
													title: '下载完成',
													mask: false,
													duration: 6000
												});
												// 下载完成
												if (status == 200) {
													plus.runtime.install(d
														.filename, {
															force: false
														},
														function() {
															plus.nativeUI
																.alert(
																	"APP更新完成！",
																	function() {
																		plus.nativeUI
																			.closeWaiting();
																		plus.runtime
																			.restart();
																		uni
																			.hideLoading();
																	});
															console.log(
																'install success...'
															);
															//plus.runtime.restart();
														},
														function(e) {
															plus.nativeUI
																.closeWaiting();
															plus.nativeUI
																.alert(
																	"安装更新文件失败[" +
																	e.code +
																	"]：" + e
																	.message);
															uni.hideLoading();
															console.error(
																'install fail...'
															);
														});

													// console.log('下载成功');
													// plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename)
													// )
													// plus.nativeUI.alert("APP更新完成！",function(){
													// 	plus.runtime.restart();
													// });
												} else {
													uni.showToast({
														title: '更新失败-02',
														mask: false,
														duration: 3500
													});
												}

											});
										try {
											dtask.start(); // 开启下载的任务
											var prg = 0;
											var showLoading = plus.nativeUI
												.showWaiting(
													"正在下载"); //创建一个showWaiting对象
											dtask.addEventListener('statechanged',
												function(
													task,
													status
												) {
													// 给下载任务设置一个监听 并根据状态  做操作
													switch (task.state) {
														case 1:
															showLoading.setTitle(
																"正在下载");
															break;
														case 2:
															showLoading.setTitle(
																"已连接到服务器");
															break;
														case 3:
															prg = parseInt(
																(parseFloat(
																		task
																		.downloadedSize
																	) /
																	(parseFloat(
																			data
																			.wgtSize
																		) *
																		1048576
																	)) *
																100
															);
															showLoading.setTitle(
																"  正在下载" +
																prg + "%  ");
															break;
														case 4:
															plus.nativeUI
																.closeWaiting();

															//下载完成
															console.log(
																'task.downloadedSize    ' +
																task
																.downloadedSize
															);
															console.log(
																'data.wgtSize    ' +
																data.wgtSize);
															break;
													}
												});
										} catch (err) {
											plus.nativeUI.closeWaiting();
											uni.showToast({
												title: '更新失败-03',
												mask: false,
												duration: 1500
											});
										}
									} else {
										//取消
									}
								}
							});
						}
					},
				})
			})
			// #endif
			/* 	plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
					  console.log('进入热更新访问路径');
				 	let BASE_URL = 'https://www.geidcp.com/api'
				     uni.request({
				         url: BASE_URL+'/project/appSoftwares/searchIsNew',
				 		method: 'get',
				 		data:{
				 			//当前版本
				             currentVersion: widgetInfo.version,
				 			//当前软件名称
				             softwareName: widgetInfo.name,
				 			//系统类型
				 			softwarePlatformTypeDict:plus.os.name
				         },

				 		success: (result) => {
							console.log('提示一下当前版本'+widgetInfo.version);
				 		var data = result.data.data;
				 		if (data.flag === false) {
							 console.log('进入热更新');
				 			uni.showModal({
				 				title: '版本更新' ,
				 				content: '发现新版本请问是否进行更新',
				 				success: function(e) {
				 					if (e.confirm) {
				 						if (plus.os.name.toLowerCase() == 'ios'||plus.os.name.toLowerCase() == 'IOS') {
				 							// 跳转到下载页面
				 							plus.runtime.openURL('https://www.geidcp.com/'+data.wgt)
				 						} else {
				 							var dtask = plus.downloader.createDownload(
				 								'https://www.geidcp.com/'+data.wgt, {},
				 								function(d, status) {
				 									uni.showToast({
				 										title: '下载完成',
				 										mask: false,
				 										duration: 6000
				 									});
				 									// 下载完成
				 									if (status == 200) {
														console.log('下载成功');
														plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, e => e, function(error) {
				 											uni.showToast({
				 												title: '安装失败-01',
				 												mask: false,
				 												duration: 3500
				 											});
				 										})
														plus.nativeUI.alert("APP更新完成！",function(){
															plus.runtime.restart();
														});
				 									} else {
				 										uni.showToast({
				 											title: '更新失败-02',
				 											mask: false,
				 											duration: 3500
				 										});
				 									}
				 								});
				 							 try {
				 								dtask.start(); // 开启下载的任务
				 								var prg = 0;
				 								var showLoading = plus.nativeUI.showWaiting("正在下载");  //创建一个showWaiting对象
				 								dtask.addEventListener('statechanged', function(
				 								  task,
				 								  status
				 								) {
				 								  // 给下载任务设置一个监听 并根据状态  做操作
				 								  switch (task.state) {
				 									case 1:
				 									  showLoading.setTitle("正在下载");
				 									  break;
				 									case 2:
				 									  showLoading.setTitle("已连接到服务器");
				 									  break;
				 									case 3:
				 									  prg = parseInt(
				 										(parseFloat(task.downloadedSize) /
				 										  (parseFloat(data.wgtSize) * 1048576)) *
				 										  100
				 									  );
				 									  showLoading.setTitle("  正在下载" + prg + "%  ");
				 									  break;
				 									case 4:
				 									   plus.nativeUI.closeWaiting();

				 										//下载完成
														console.log('task.downloadedSize    '+task.downloadedSize);
														console.log('data.wgtSize    '+data.wgtSize);
				 									  break;
				 								  }
				 								});
				 							  } catch (err) {
				 								  plus.nativeUI.closeWaiting();
				 								  uni.showToast({
				 								  	title: '更新失败-03',
				 								  	mask: false,
				 								  	duration: 1500
				 								  });
				 							  }
				 						}

				 					} else {
				 						//取消
				 					}
				 				}
				 			});
				 		}
				 	},
				 })
				}) */

			/* plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
				let BASE_URL = 'https://www.geidcp.com/api'
			    uni.request({
			        url: BASE_URL+'/project/appSoftwares/searchIsNew',
					method: 'get',
					data:{
						//当前版本
			            currentVersion: widgetInfo.version,
						//当前软件名称
			            softwareName: widgetInfo.name,
						//系统类型
						softwarePlatformTypeDict:plus.os.name
			        },
					success: (result) => {
					var data = result.data.data;
					if (data.flag === false) {
						uni.showModal({
							title: '发现新版本',
							content: '是否进行更新',
							success: function (res) {
								if (res.confirm) {
									 uni.showLoading({
									 title: '更新中...'
													})
									uni.downloadFile({
										url: 'https://www.geidcp.com/'+data.wgt,
										success: (downloadResult) => {
											if (downloadResult.statusCode === 200) {
												plus.runtime.install(downloadResult.tempFilePath, {
													force: false
												}, function() {
												 plus.nativeUI.alert("APP更新完成！",function(){
															plus.nativeUI.closeWaiting();
														plus.runtime.restart();
														uni.hideLoading();
													});
												   console.log('install success...');
													//plus.runtime.restart();
												}, function(e) {
													plus.nativeUI.closeWaiting();
													plus.nativeUI.alert("安装更新文件失败["+e.code+"]："+e.message);
													uni.hideLoading();
													console.error('install fail...');
												});

											}
										}
									});
								console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
				}
			    });
			}); */
			// #ifdef APP-PLUS
			//设置2.4秒后主动关闭，最多设置6秒
			// setTimeout(() => {
			// 	plus.navigator.closeSplashscreen();
			// }, 3000);

			// #endif
		},

		methods: {
			...mapMutations(['setCartNum', 'setNotifyNum']),

			// 数据初始化
			async initData() {
				uni.setTabBarStyle({
					selectedColor: this.themeColor.color,
					borderStyle: 'white'
				});
				this.themeColor.tabList && this.themeColor.tabList.forEach((selectedIconPath, index) => {
					uni.setTabBarItem({
						index,
						selectedIconPath
					});
				});
				if (this.$i18n.locale == 'zh') {
					document.title = _self.AgentSystemSet.WebSiteName;
					debugger
				} else {

				}
				// 获取页面设置配置
				const token = uni.getStorageSync('accessToken');
				// 获取系统title高度
				await this.initSystemInfo();
				if (token) {
					await this.handleVerifyAccessToken(token);
				}
				if (this.$mStore.getters.hasLogin) {
					this.setCartNum(uni.getStorageSync('cartNum') || 0);
					this.setNotifyNum(uni.getStorageSync('notifyNum') || 0);
					// #ifdef APP-PLUS
					const info = plus.push.getClientInfo();
					// #endif
				}
				// #ifdef H5
				if (this.$mPayment.isWechat()) {
					await this.$mPayment.wxConfigH5(window.location.href);
				}
				// #endif
			},
			// 初始化系统信息
			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;
						// eslint-disable-next-line
						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
					}
				});
			},
			// 检验token是否有效
			async handleVerifyAccessToken(token) {
				await this.$http.post(verifyAccessToken, {
					token
				}).then(r => {
					if (!r.data.token) {
						this.$mStore.commit('logout');
					}
				});
			}
		}
	};
</script>
<style lang="scss">
	/* #ifndef APP-PLUS-NVUE
@import "uview-ui/index.scss";
// 导入colorUI
@import '/static/css/colorui/main.css';
@import '/static/css/colorui/icon.css';
@import '/static/css/colorui/animation.css';

@import './static/css/iconfont/iconfont.css';
@import './static/css/reset.scss';
@import './static/css/uni.scss';

@import './static/css/font-awesome/css/font-awesome.css';

/* #endif */
	uni-page-head {
		display: none;
	}

	// 导入阿里巴巴矢量图标库
	/*#ifdef MP*/
	@import './static/css/iconfont/iconfont.css';
	/*#endif*/
	/*#ifndef MP || APP-PLUS-NVUE*/
	@import url('https://at.alicdn.com/t/font_1681579_dwilkcq6mvg.css');
	/*#endif*/
</style>
