<script>
	import auth from 'common/js/auth.js';
	import { Weixin } from 'common/js/wx-jssdk.js';
	// #ifdef APP-PLUS
	import appUpdate from "@/config/appUpdate"
	var jpushModule = uni.requireNativePlugin('JG-JPush');
	// #endif

	function getQueryParams(url) {
		const paramArr = url.slice(url.indexOf("?") + 1).split("&");
		const params = {};
		paramArr.forEach((param) => {
			const [key, val] = param.split("=");
			params[key] = decodeURIComponent(val);
		});
		return params;
	}

	export default {
		mixins: [auth],
		// onLoad() {
		// 	// 判断登录
		// 	if (!uni.getStorageSync('token')) {
		// 		this.$util.redirectTo('/pages_tool/login/login');
		// 	}
		// },
		onLaunch: function(e) {
		
			// #ifdef MP-ALIPAY
			console.log(e, 'onLaunchonLaunchonLaunch');
			uni.removeStorageSync('schemeData')
			if (e.path == "pages_tool/pay/index") {
				uni.setStorageSync('schemeData', e.query);
			}
			// #endif

			// #ifdef APP-PLUS
			if (!this.$isIOS)
				setTimeout(() => {
					if (jpushModule) {
						jpushModule.initJPushService();
						jpushModule.setLoggerEnable(true);
						var registerID;
						jpushModule.getRegistrationID(result => {
							registerID = result.registerID;
							console.log(registerID, `registerID`);
							if (registerID) {
								this.$api.sendRequest({
									url: '/api/jpush/setRegistrationId',
									data: {
										registration_id: registerID
									},
									success: res => {
										console.log(res, `registerID_res`);
									}
								});
							}
						});
					}
				}, 30000);

			// #endif
			uni.hideTabBar();
			uni.setStorageSync('DIY_VIEW_INDEX_popwindow_count', 1);

			// #ifdef MP
			const updateManager = uni.getUpdateManager();
			updateManager.onCheckForUpdate(function(res) {
				// 请求完新版本信息的回调
			});

			updateManager.onUpdateReady(function(res) {
				uni.showModal({
					title: '更新提示',
					content: '新版本已经准备好，是否重启应用？',
					success(res) {
						if (res.confirm) {
							// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
							updateManager.applyUpdate();
						}
					}
				});
			});

			updateManager.onUpdateFailed(function(res) {
				// 新的版本下载失败
			});
			// #endif

			// #ifdef H5
			if (uni.getSystemInfoSync().platform == 'ios') {
				uni.setStorageSync('initUrl', location.href);
			}
			// #endif

			uni.onNetworkStatusChange(function(res) {
				if (!res.isConnected) {
					uni.showModal({
						title: '网络失去链接',
						content: '请检查网络链接',
						showCancel: false
					});
				}
			});

			this.$store.dispatch('init');


			// #ifdef APP-PLUS || H5 || MP-WEIXIN
			const userType = uni.getStorageSync('user_type');
			if (userType && Number(userType) === 2) {
				// 自动授权登录
				if (!uni.getStorageSync('token')) {
					this.getAuthInfo();
				} else {
					// 启动小程序/app 更新用户登录信息
					this.$api.sendRequest({
						url: '/api/login/loginLog',
						success(res) {}
					})

					this.$api.sendRequest({
						url: '/api/member/info',
						complete: () => {
							if (!uni.getStorageSync('token')) this.getAuthInfo();
						}
					});

				}
			}
			// #endif


			// #ifdef APP-PLUS
			// ios 通知打开
			setTimeout(() => {
				if (jpushModule) {
					jpushModule.addNotificationListener(result => {
						let notificationEventType = result.notificationEventType
						let extras = result.extras
						if (notificationEventType === 'notificationOpened' && extras.schemes) {
							this.checkArgs(extras.schemes);
						}
					})
				}
			}, 30000);

			// #endif
		},
		onLoad() {
			console.log('onLoad');
		},
		onShow(e) {
			uni.removeStorageSync('schemeData')
			if (e.path == "pages_tool/pay/index") {
				uni.setStorageSync('schemeData', e.query);
			}
			console.log('onShow', e);
			// #ifdef APP-PLUS
			setTimeout(() => {
				// 清除角标
				if (jpushModule)
					jpushModule.setBadge(0)
				// 同步服务器角标数据
				plus.runtime.setBadgeNumber(0);
				this.checkArgs(this.getArgs());
			}, 0);
			// #endif
		},
		onHide: function() {},
		methods: {
			getArgs() {
				// console.log(plus.runtime.launcher, plus.runtime.arguments, 'plus.runtime.launcher')
				// const urlSchemeArgs = uni.getStorageSync('urlSchemeArgs')
				// if (urlSchemeArgs === plus.runtime.arguments) return
				if (plus.runtime.launcher === 'default') return
				// uni.setStorageSync('urlSchemeArgs', plus.runtime.arguments)
				plus.runtime.launcher = 'default'
				return plus.runtime.arguments
			},
			checkArgs(args) {
				if (!args) return
				const runtimeArguments = args.split('://')
				if (runtimeArguments.length < 1) return
				// const scheme = runtimeArguments[0]
				const url = runtimeArguments[1]
				let path = url.split('?')
				if (path.length < 0) return
				path = path[0]
				const params = getQueryParams(decodeURIComponent(url))

				if (path === 'target') {
					// 判断登录 TODO
					if (!uni.getStorageSync('token')) {
						this.$util.showToast({
							title: '您尚未登录，请先进行登录',
							icon: 'none',
						});
						setTimeout(() => {
							this.$util.redirectTo('/pages_tool/login/login');
						}, 1000)
						return
					}
					console.log(params, 'params')
					// 进行跳转
					this.$util.redirectTo(params.path, params);
				}
			},
			/**
			 * 获取授权信息
			 */
			getAuthInfo() {
				// #ifdef H5
				if (this.$util.isWeiXin()) {
					this.$util.getUrlCode(urlParams => {
						if (urlParams.source_member)
							uni.setStorageSync('source_member', urlParams.source_member);

						if (urlParams.code == undefined) {
							this.$api.sendRequest({
								url: '/wechat/api/wechat/authcode',
								data: {
									redirect_url: location.href,
									scopes: 'snsapi_userinfo'
								},
								success: res => {
									if (res.code >= 0) {
										location.href = res.data;
									}
								}
							});
						} else {
							this.$api.sendRequest({
								url: '/wechat/api/wechat/authcodetoopenid',
								data: {
									code: urlParams.code
								},
								success: res => {
									if (res.code >= 0) {
										let data = {};
										if (res.data.openid) data.wx_openid = res.data.openid;
										if (res.data.unionid) data.wx_unionid = res.data.unionid;
										if (res.data.userinfo) Object.assign(data, res.data.userinfo);
										this.authLogin(data);
									}
								}
							});
						}
					});
				}
				// #endif

				// #ifdef MP
				this.getCode(data => {
					this.authLogin(data, 'authOnlyLogin');
				});
				// #endif
			},
			/**
			 * 授权登录
			 */
			authLogin(data, type = 'authLogin') {
				if (uni.getStorageSync('source_member'))
					data.source_member = uni.getStorageSync('source_member');

				uni.setStorage({
					key: 'authInfo',
					data: data
				});

				this.$api.sendRequest({
					url: type == 'authLogin' ? '/api/login/auth' : '/api/login/authonlylogin',
					data,
					success: res => {
						if (res.code >= 0) {
							uni.setStorage({
								key: 'token',
								data: res.data.token,
								success: () => {
									this.$store.dispatch('getCartNumber');
									this.$store.commit('setToken', res.data.token);
								}
							});
						}
					}
				});
			},
			/**
			 * 公众号分享设置
			 */
			shareConfig() {
				this.$api.sendRequest({
					url: '/wechat/api/wechat/share',
					data: {
						url: window.location.href
					},
					success: res => {
						if (res.code == 0) {
							var wxJS = new Weixin();
							wxJS.init(res.data.jssdk_config);

							let share_data = JSON.parse(JSON.stringify(res.data.share_config.data));
							if (share_data) {
								wxJS.setShareData({
										title: share_data.title,
										desc: share_data.desc,
										link: share_data.link,
										imgUrl: this.$util.img(share_data.imgUrl)
									},
									res => {
										console.log(res);
									}
								);
							}

							let hideOptionMenu = res.data.share_config.permission.hideOptionMenu;
							let hideMenuItems = res.data.share_config.permission.hideMenuItems;

							if (hideOptionMenu) {
								wxJS.weixin.hideOptionMenu(); //屏蔽分享好友等按钮
							} else {
								wxJS.weixin.showOptionMenu(); //放开分享好友等按钮
							}
						}
					},
					fail: err => {}
				});
			}
		},
		watch: {
			$route: {
				handler(newName, oldName) {
					if (this.$util.isWeiXin()) {
						this.shareConfig();
					}
				},
				// 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
				immediate: true
			}
		}
	};
</script>
<style lang="scss">
	// @import 'uview-ui/index.scss';
	@import "@/uni_modules/uview-ui/index.scss";
	@import './common/css/iconfont.css';
	@import './common/css/icondiy.css'; // 自定义图标库
	@import './common/css/main.scss';

	// ********** 这里要引用扩展图标库文件 **********
	@import './common/css/icon_extend/diy_default1.css';

	.df {
		display: flex;
	}

	.aic {
		align-items: center;
	}

	.jcsb {
		justify-content: space-between;
	}

	.jcsa {
		justify-content: space-around;
	}

	.jcc {
		justify-content: center;
	}

	.f1 {
		flex: 1;
	}

	.fn {
		flex: none;
	}

	.fdc {
		flex-direction: column;
	}

	.fw {
		flex-wrap: wrap;
	}

	.jcf {
		justify-content: flex-end;
	}
</style>