<script>
	import Vue from 'vue'
	import api from 'utils/api'
	import util from 'utils/util'
	import __config from 'config/env';
	//import JMessage from 'public/jmessage-wxapplet-sdk/jmessage-wxapplet-sdk-1.4.0.min.js'

	// #ifdef APP-PLUS
	import APPUpdate from "@/public/APPUpdate/index.js"; //App版本更新
	// #endif

	export default {
		globalData: {
			urlTitle:'',
			showPrivacy: false,
			isIPad: false,
			isIos: false,
			isAndroid: false,
			systemInfo: {},
			shoppingCartCount: 0, //购物车数量
			tenantId: null, //租户Id
			appId: null, //公众号appId
			componentAppId: null, //第三方平台appid
			isEnableSwitchToken: false, //是否开启SwitchToken
			theme: { //主题定义
				backgroundColor: null, //背景颜色,支持渐变色
				themeColor: null, //主题颜色
				tabbarBackgroundColor: null, //tabbar背景颜色
				tabbarColor: null, //tabBar上的文字默认颜色
				tabbarSelectedColor: null, //tabBar上的文字选中时的颜色
				tabbarBorderStyle: null, //tabBar上边框的颜色
				tabbarItem: [] //tabBar明细设置
			},
			logining: false, //登录loading
		},
		onLaunch: async function() {
			
			// 微信授权验证
			// if (uni.getPrivacySetting) {
			// 	uni.getPrivacySetting({
			// 		success: res => {
			// 			console.log("是否需要授权：", res.needAuthorization, "隐私协议的名称为：", res.privacyContractName)
			// 			if (res.needAuthorization) {
			// 				getApp().globalData.urlTitle = res.privacyContractName
			// 				getApp().globalData.showPrivacy = true;
			// 			} else {
			// 				getApp().globalData.showPrivacy = false;
			// 			}
			// 		},
			// 		fail: () => {
			// 		},
			// 		complete: () => {},
			// 	})
			// };
			const Decimal = require('decimal.js');
			// #ifdef MP
			//小程序平台检测新版本
			this.updateManager();
			//this.doLogin();
			// #endif
			// 原生app版本更新检测
			// #ifdef APP-PLUS
			APPUpdate();
			// const ToastPlusModule = uni.requireNativePlugin("unitest")
			// ToastPlusModule.init();

			// #endif

			//隐藏原生tabbar
			uni.hideTabBar()

			// #ifdef H5
			// H5平台获取参数中的租户ID、公众号appID,并存入globalData
			let local = location.href
			let tenantId = util.getUrlParam(local, "tenant_id");
			let appId = util.getUrlParam(local, "app_id");
			let componentAppId = util.getUrlParam(local, "component_appid");
			this.globalData.tenantId = tenantId;
			this.globalData.appId = appId;
			this.globalData.componentAppId = componentAppId;
			// #endif

			// #ifdef APP-PLUS
			// APP平台需要从配置文件中获取租户ID
			let tenantId = __config.tenantId;
			this.globalData.tenantId = tenantId;
			// #endif

			//设置全局样式
			this.setGlobalStyle();
			if (uni.getStorageSync('wx_token_value')) {}
			// 上报设备信息
			await this.deviceReport();
		},


		methods: {
			// 同步上报设备信息
			async deviceReport() {
				let info = uni.$u.sys()
				this.globalData.systemInfo = info
				this.globalData.deviceId = info.deviceId
				this.globalData.isIPad = (info.devicePixelRatio != 3 && info.windowWidth > 420)
				if (info.system.toLowerCase().indexOf("ios") > -1) {
					this.globalData.isIos = true
				}
				if (info.system.toLowerCase().indexOf("android") > -1) {
					this.globalData.isAndroid = true
				}

				this.$log('device-id: ' + info.deviceId)
				console.log('system: ', info.system)
				console.log('model: ', info.model)
				console.log('设备像素比: ', info.devicePixelRatio)

				/* for (let k in info) {
					console.log(k + ': ', info[k])
				} */

				console.log('globalSystemInfo: ', info)
				// APP上报设备信息
				let res = await api.deviceReport(info)
				//TODO 待处理店铺信息
				if (res.data.length > 0) {
					//店铺ID放入缓存
					uni.setStorageSync(__config.shopIdSessionKey, res.data.shopInfos.id)
					uni.setStorageSync(__config.shopInfoSessionKey, res.data.shopInfos ? res.data.shopInfos : [])
					uni.setStorageSync("tableList", res.data.sendTableDTOS ? res.data.sendTableDTOS : [])
				} else {
					uni.removeStorageSync(__config.shopIdSessionKey)
					uni.removeStorageSync(__config.shopInfoSessionKey)
					uni.removeStorageSync("tableList")
				}
				console.log('^^^^^^^^^^^^^^^^****************^^^^^^^^^^^^^^^^^')
				console.log('isIPad: ', this.globalData.isIPad)
				console.log('isIos: ', this.globalData.isIos)
				console.log('isAndroid: ', this.globalData.isAndroid)
			},
			//设置全局样式
			setGlobalStyle() {
				uni.getSystemInfo({
					success: function(e) {
						// [2020-08-01]更新ColorUI 修复ios 状态栏错位
						// #ifndef MP
						Vue.prototype.StatusBar = e.statusBarHeight;
						if (e.platform == 'android') {
							Vue.prototype.CustomBar = e.statusBarHeight + 50;
						} else {
							Vue.prototype.CustomBar = e.statusBarHeight + 45;
						};
						// #endif
						// #ifdef MP-WEIXIN || MP-QQ
						Vue.prototype.StatusBar = e.statusBarHeight;
						let capsule = wx.getMenuButtonBoundingClientRect();
						if (capsule) {
							Vue.prototype.Custom = capsule;
							// Vue.prototype.capsuleSafe = uni.upx2px(750) - capsule.left + uni.upx2px(750) - capsule.right;
							Vue.prototype.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
						} else {
							Vue.prototype.CustomBar = e.statusBarHeight + 50;
						}
						// #endif
						// #ifdef MP-ALIPAY
						Vue.prototype.StatusBar = e.statusBarHeight;
						Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
						// #endif

						// 处理IPAD头部高度问题
						if (e.devicePixelRatio != 3 && e.windowWidth > 420) {
							if (e.system.toLowerCase().indexOf("ios") > -1) {
								Vue.prototype.CustomBar = Vue.prototype.CustomBar + 20
							}
							if (e.system.toLowerCase().indexOf("android") > -1) {
								Vue.prototype.CustomBar = Vue.prototype.CustomBar
							}
						}
					}
				})
				//let themeMobile = res.data;
				//定义默认配置
				let backgroundColor = 'blue';
				let themeColor = 'purple';
				let tabbarBackgroundColor = '#ffffff';
				let tabbarColor = '#666666';
				let tabbarSelectedColor = '#f43f3b';
				let tabbarBorderStyle = '#black';
				let tabbarItem = [{
						index: 0,
						text: '首页',
						iconPath: '/static/public/img/icon-1/1-001.png',
						selectedIconPath: '/static/public/img/icon-1/1-002.png'
					},
					{
						index: 1,
						text: '分类',
						iconPath: '/static/public/img/icon-1/2-001.png',
						selectedIconPath: '/static/public/img/icon-1/2-002.png'
					},
					{
						index: 2,
						text: '消息',
						iconPath: '/static/public/img/icon-1/3-001.png',
						selectedIconPath: '/static/public/img/icon-1/3-002.png'
					},
					{
						index: 3,
						text: '购物车',
						iconPath: '/static/public/img/icon-1/4-001.png',
						selectedIconPath: '/static/public/img/icon-1/4-002.png'
					},
					{
						index: 4,
						text: '我的',
						iconPath: '/static/public/img/icon-1/5-001.png',
						selectedIconPath: '/static/public/img/icon-1/5-002.png'
					}
				]
				//将默认配置换成后台数据
				this.globalData.theme.backgroundColor = backgroundColor
				this.globalData.theme.themeColor = themeColor
				this.globalData.theme.tabbarBackgroundColor = tabbarBackgroundColor
				this.globalData.theme.tabbarColor = tabbarColor
				this.globalData.theme.tabbarSelectedColor = tabbarSelectedColor
				this.globalData.theme.tabbarBorderStyle = tabbarBorderStyle
				//this.globalData.theme.tabbarItem = tabbarItem
			},



			// #ifdef MP
			//小程序平台检测新版本
			updateManager() {
				const updateManager = uni.getUpdateManager();
				updateManager.onUpdateReady(function() {
					uni.showModal({
						title: '更新提示',
						content: '新版本已经准备好，是否重启应用？',
						success(res) {
							if (res.confirm) {
								updateManager.applyUpdate();
							}
						}
					});
				});
			},
			// #endif

			/**
			 * 获取用户信息(接口方式)
			 */
			getAccountInfoSync() {
				let params = {}
				if (this.getAccountId()) {
					params['accountId'] = this.getAccountId()
				}
				return api.getCurrentUserSync(params)
			},

			/**
			 * 获取缓存中用户信息(不存在返回undefined)
			 */
			getAccountInfo() {
				let userInfo = uni.getStorageSync(__config.loginWxUserInfoKey)
				if (userInfo)
					return userInfo;
				return undefined
			},

			/**
			 * 获取缓存中用户Id(无值返回undefined)
			 */
			getAccountId() {
				let account = this.getAccountInfo()
				return account ? account.accountId : undefined
			},

			/**
			 * 获取缓存中用户手机号(无值返回undefined)
			 */
			getAccountMobile() {
				let account = this.getAccountInfo()
				return account ? account.mobile : undefined
			},
			

			/**
			 * 获取缓存中用户是否授权过微信自身的用户信息(无值返回false)
			 */
			getAccountIsAuth() {
				let retFlag = false
				let account = this.getAccountInfo()
				if (!account)
					return retFlag
				if (account.headerImg) {
					retFlag = true
				}
				return retFlag
			},

			//页面初始化方法，供每个页面调用
			initPage() {
				let that = this;
				return new Promise((resolve, reject) => {
					//小程序或公众号H5，每个页面都进行登录校验
					if (util.isMiniPg() || (that.globalData.appId && util.isWeiXinBrowser())) {
						console.info('initPage : ' + __config.tokenValueKey, uni.getStorageSync(__config
							.tokenValueKey))
						if (!uni.getStorageSync(__config.tokenValueKey)) {
							//resolve("success");
							//无thirdSession，进行登录
							that.doLogin().then(res => {
								resolve("success");
							});
						} else {
							if (util.isMiniPg()) { //小程序需要检查登录态是否过期
								uni.checkSession({
									success() {
										//session_key 未过期，并且在本生命周期一直有效
										console.log('session_key 未过期')
										resolve("success");
									},
									fail() {
										// session_key 已经失效，需要重新执行登录流程
										console.log('session_key 已经失效')
										debugger
										that.doLogin().then(res => {
											resolve("success");
										});
									}
								})
							} else {
								resolve("success");
							}
						}
					} else {
						resolve("success");
					}
				});
			},

			//登录操作
			doLogin() {
				uni.showLoading({
					title: '登录中'
				});
				return new Promise((resolve, reject) => {
					// #ifdef MP-WEIXIN
					//微信小程序登录
					this.loginWxMa().then(res => {
						resolve("success");
					});
					// #endif
					// #ifdef H5
					//微信公众号H5
					if (util.isWeiXinBrowser()) {
						let local = location.href
						let code = util.getUrlParam(local, "code");
						let state = util.getUrlParam(local, "state");
						//授权code登录
						if (code) { //有code
							if (state == 'snsapi_base' || state == 'snsapi_userinfo') { //登录授权
								this.loginWxMp(code, state).then(res => {
									resolve("success");
								});
							}
						} else { //无code则发起网页授权
							//微信公众号H5，页面授权登录
							let appId = this.globalData.appId;
							let pages = getCurrentPages();
							let currentPage = pages[pages.length - 1];
							let route = currentPage.route;
							let redirectUri = location.href;
							let componentAppId_str = this.globalData.componentAppId ? '&component_appid=' + this
								.globalData.componentAppId : '';
							redirectUri = encodeURIComponent(redirectUri);
							let wx_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId +
								'&redirect_uri=' + redirectUri + componentAppId_str +
								'&response_type=code&scope=snsapi_base&state=snsapi_base#wechat_redirect';
							location.href = wx_url;
						}
					}
					// #endif
				});
			},
			//微信小程序登录
			// #ifdef MP-WEIXIN
			loginWxMa() {
				this.globalData.logining = true
				let that = this;
				return new Promise((allResolve, allReject) => {
					Promise.resolve().then(res => {
						return new Promise((resolve, reject) => {
							uni.login({
								success: function(wxRes) {
									resolve(wxRes)
								}
							});
						});
						// 只有当第一个then返回了promise对象才会接着调用下一个的then方法
					}).then((wxRes) => {
						return new Promise((resolve, reject) => {
							if (wxRes.code) {
								let params = {
									jsCode: wxRes.code
								}
								api.doGet(__config.authConfig.apiLoginUrl, params).then(res => {
									resolve(res);
								})
							}
						});
					}).then((allRes) => {
							console.log('用户登录成功返回结果: ', allRes)
							uni.hideLoading();
							this.globalData.logining = false
							let session = allRes.data;
							if (session.isLogin) {
								uni.setStorageSync(__config.tokenNameKey, session
									.tokenName);
								uni.setStorageSync(__config.tokenValueKey, session
									.tokenValue);
							
								/**
								 * 缓存用户信息
								 */
								let wxMemberInfo = util.parseUser(session.userInfo)
								uni.setStorageSync(__config.loginWxUserInfoKey,
									wxMemberInfo)
							}
							uni.$emit('loginSuccess', that.getAccountInfo())
							allResolve("success");
					})
				});
				
				
				// return new Promise((resolve, reject) => {
				// 	let that = this;
				// 	this.uniWxLogin().then(wxRes => {
				// 		if (wxRes.code) {
				// 			let params = {
				// 				jsCode: wxRes.code
				// 			}
				// 			debugger
				// 			api.doGet(__config.authConfig.apiLoginUrl, params).then(res => {
								
				// 			});
				// 		}
				// 	})
				// });
			},


			/**
			 * 获取微信 login code
			 */
			uniWxLogin() {
				return new Promise((resolve, reject) => {
					let that = this;
					uni.login({
						success: function(res) {
							resolve(res)
						}
					});
				});
			},


			// #endif
			//公众号登录
			// #ifdef H5
			loginWxMp(code, state) {
				let that = this;
				return new Promise((resolve, reject) => {
					let that = this
					api.loginWxMp({
						jsCode: code,
						scope: state
					}).then(res => {
						//公众号h5网页授权时url会产生code、state参数，防止code、state被复制，需自动剔除
						let query = that.$Route.query;
						delete query.code;
						delete query.state;
						util.resetPageUrl(query);
						let userInfo = res.data;
						uni.setStorageSync('third_session', userInfo.thirdSession);
						uni.setStorageSync('user_info', userInfo);
						//获取购物车数量
						that.shoppingCartCount();
						resolve("success");
					}).catch(res => {

					});
				});
			},
			// #endif
		}
	};
</script>
<style lang="scss">
	/* #ifndef APP-PLUS-NVUE */
	@import "./app.css";
	/* #endif */

	@import './public/animate/animate.css';

	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import "@/uni_modules/uview-ui/index.scss";
</style>
