<template>
	<view>
		<!--pages/authorize/authorize.wxml-->
		<block v-if="isLong">
			<view class="about">
				<view class="logo">
					<image :src="logo"></image>
					<view>{{ name }}</view>
				</view>
			</view>
			<view class="btn">
				<button class="login" @click="getWXUserProfile()">授权登录</button>
				<!-- <button class="login" open-type="getUserInfo" @getuserinfo="bindGetUserInfo">授权登录</button> -->
				<view class="zanbu" @tap="back">暂不登录</view>
				<view hover-class="none" class="xieyi ddflex">
					<view @click="jump('/mine/page/page?title=用户协议&isXieyi=true')">《用户协议》</view>
					及
					<view @click="jump('/mine/page/page?title=隐私声明&isYinsi=true')">《隐私声明》</view>
				</view>
				<view class="copy" v-if="about.name && about.recordNumber">{{ about.name ? about.name : '' }}版权所有© {{ about.recordNumber ? about.recordNumber : '' }}</view>
			</view>
		</block>
		<block v-if="isphone">
			<view class="phone">
				<view class="logo">
					<image :src="logo"></image>
					<view>{{ name }}</view>
				</view>
			</view>
			<view class="btn">
				<button class="btnphone" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">微信手机号快捷绑定</button>
				<!-- <view class="btngophone r10">手机号验证绑定</view> -->
				<view class="zanbu" @tap="back">暂不绑定</view>
				<view hover-class="none" class="xieyi ddflex">
					<view @click="jump('/mine/page/page?title=用户协议&isXieyi=true')">《用户协议》</view>
					及
					<view @click="jump('/mine/page/page?title=隐私声明&isYinsi=true')">《隐私声明》</view>
				</view>
				<view class="copy" v-if="about.name && about.recordNumber">{{ about.name ? about.name : '' }}版权所有© {{ about.recordNumber ? about.recordNumber : '' }}</view>
			</view>

		</block>
		<view class="ceng" v-if="isXyShow"></view>
		<view class="pop-protocol" :style="'bottom:' + XyBottom">
			<view class="pop-tit">个人隐私保护指引</view>
			<view class="pop-con">
				为更好的保障你的个人信息安全及权利行使。我们将通过
				<text @click="jump('/mine/page/page?title=用户协议&isXieyi=true')">《用户协议》</text>
				和
				<text @click="jump('/mine/page/page?title=隐私声明&isYinsi=true')">《隐私声明》</text>
				帮助你了解我们收集、使用、存储、公开披露个人信息的情况。请仔细阅读并理解本政策的内容，若你同意，请点击下方按钮开始接受我们的服务。
			</view>
			<view class="pop-btn">
				<view class="pop-agree" @click="agn()">同意并继续</view>
				<view class="pop-no" @click="back()">不同意并退出</view>
			</view>
		</view>
		<!-- <privacy :is-bindMobile="false" :is-timeout="false"></privacy> -->
	</view>
</template>

<script>
// pages/authorize/authorize.js
const app = getApp();
const req = require('../../utils/request.js');

export default {
	data() {
		return {
			sessionKey: '',
			openid: '',
			about: {},
			isShow: true,
			isphone: false,
			isLong: true,
			istetphone: 0,
			config: '',
			logo: '',
			name: '',
			isPromote: false, //是否从分销进入
			isXyShow: true, //默认显示协议指引
			XyBottom: '-100%'
		};
	},

	components: {},
	props: {},
	onLoad: function(options) {
		req.removeStorage('authorize_jump')
		var agnXY = req.getStorage('agnXY');
		if (agnXY) {
			this.isXyShow = false;
			this.XyBottom = '-100%';
		} else {
			setTimeout(res => {
				this.XyBottom = 0;
			}, 200);
		}

		app.globalData.getCheckSessoin(json => {
			this.sessionKey = json.session_key;
			this.openid = json.openid;
		});
		console.log('登录页面===********************' + JSON.stringify(options));

		if (req.getStorage('configRes')) {
			let configRes = JSON.parse(req.getStorage('configRes'));
			this.setData({
				istetphone: configRes.user_bind_mobile,
				logo: configRes.CONFIG_PROJECT_LOGO,
				name: configRes.CONFIG_PROJECT_TITLE,
				config: configRes
			});
		} else {
			req.g('/api/config', res => {
				req.setStorage('configRes', JSON.stringify(res));
				this.setData({
					istetphone: res.user_bind_mobile,
					logo: res.CONFIG_PROJECT_LOGO,
					name: res.CONFIG_PROJECT_TITLE,
					config: res
				});
			});
		}

		if (options.bindmobile == 1) {
			this.isphoneFun();
		}

		if (options.scene) {
			this.scene = options.scene;
			this.loadCodeParams();
		}
		this.getAbout();
		// this.isphone()
	},
	onShow: function() {
		uni.setNavigationBarColor({
			frontColor: '#000000',
			backgroundColor: '#FFFFFF'
		});
		uni.setNavigationBarTitle({
			title: '授权登录'
		}); // this.isshop()
	},
	onUnload: function() {
		// 调用登录的时候会存一个REDIRECT_URL 根据REDIRECT_URL来判断用户是从哪里登录，identification用户点击暂不绑定的标识
		// console.log(this.identification,req.getStorage('REDIRECT_URL'),app)
		if (req.getStorage('REDIRECT_URL') == '/pages/user/user' && !this.identification) {
			// 判断是否开启了强制绑定手机号，并且判断缓存是否有userInfo，是否存在userInfo.mobile电话
			if (this.istetphone == '1' && req.getStorage('userInfo') && !req.getStorage('userInfo').mobile) {
				let pages = getCurrentPages();
				var prevPage = pages[pages.length - 2];
				prevPage.$vm.setData({
					noLogin: true
				});
				uni.navigateBack({
					delta: -1
				});
				// app.globalData.switchTab('pages/index/index')
			}
			// 判断用户是否登录,点击返回键,就跳转到首页,并传个值到user页面，阻止调用接口，防止登录
			if (!req.getStorage('userInfo')) {
				let pages = getCurrentPages();
				var prevPage = pages[pages.length - 2];
				prevPage.$vm.setData({
					noLogin: true
				});
				uni.navigateBack({
					delta: -1
				});
				// app.globalData.switchTab('pages/index/index')
			}
		}
	},
	methods: {
		jump(url) {
			uni.navigateTo({
				url: url
			});
		},

		loadCodeParams() {
			let _ts = this;
			return new Promise((resolve, reject) => {
				if (!_ts.scene) {
					resolve();
					return false;
				}

				req.getRequest(
					'/api/code/params',
					{
						scene: _ts.scene
					},
					data => {
						if (data.scene.split('_')[1] == 'isPromote') {
							this.isPromote = true;
						}
						// console.log("获取用户id====++++++++++++++" + JSON.stringify(data));
						req.setStorage('pidCode', data.userId);
						resolve();
					}
				);
			});
		},

		agn() {
			this.isXyShow = false;
			this.XyBottom = '-100%';
			req.setStorage('agnXY', true);
		},

		back() {
			this.XyBottom = '-100%';
			this.identification = true;
			// uni.switchTab({
			// 	url: req.header.appId=='ZQ1VK5oc17I387E'?'/pages/timelyDelivery/index':'/pages/index/index'

			// });
			if (this.isPromote) {
				app.globalData.reLaunchTo('pages/index/index')
			} else {
				uni.navigateBack();
			}
		},

		getAbout() {
			var _this = this;
			req.getRequest(
				'/api/aboutAs',
				{},
				function(res) {
					_this.setData({
						about: res
					});
				},
				true
			);
		},
		getWXUserProfile() {
			let that = this;
			// #ifdef MP-WEIXIN
			try {
				uni.getUserProfile({
					desc: '注册',
					success: res => {
						// console.log('数据====', JSON.stringify(res));
						that.toSubmitLogin(res.iv, res.encryptedData);
					},
					fail: res => {
						// console.log('数据====', res);
						req.msg(res);
					}
				});
			} catch (e) {
				//  老版
				wx.getUserInfo({
					success: function(ress) {
						// console.log('getUserInfo====', JSON.stringify(ress));
						that.toSubmitLogin(ress.iv, ress.encryptedData);
					}
				});
			}
			// #endif

			// #ifdef MP-TOUTIAO
			uni.login({
				success(res) {
					console.log('静默授权登录>>>', res);
					let params = {
						code: res.code,
						parentId: req.getStorage('pidCode')
					};
					return new Promise((resolve, reject) => {
						req.postRequest(
							'/api/v3/tiktok/login',
							params,
							data => {
								if (data.token) {
									req.setStorage('AUTH_TOKEN', data.token);
								}
								req.setStorage('userInfo', data);

								if (that.istetphone != '1') {
									uni.navigateBack();
								} else {
									if (data.mobile) {
										uni.navigateBack();
									} else {
										that.isphoneFun();
									}
								}
							},
							true
						);
					});
				}
			});
			// #endif
		},
		toSubmitLogin(iv, encryptedData) {
			let that = this;
			if (!encryptedData || !iv) return false;
			let _params = {
				sessionKey: this.sessionKey,
				openId: this.openid,
				iv: iv,
				encryptedData: encryptedData
			};
			if (req.getStorage('pidCode')) {
				_params.parentId = req.getStorage('pidCode');
			}
			req.postRequest('/api/login', _params, json => {
				let params = json;
				// console.log(json);
				that.setData(params);
				let url = req.getStorage('REDIRECT_URL');
				req.setStorage('userInfo', json);

				// req.removeStorage('MERCHANT')
				if (that.scene) {
					that.back();
				} else {
					// console.log(json.mobile);

					if (that.istetphone != '1') {
						uni.navigateBack();
					} else {
						if (json.mobile) {
							uni.navigateBack();
						} else {
							that.isphoneFun();
						}
					}
				}

				that.isshop();
			});
		},
		//原来的登录
		bindGetUserInfo(e) {
			var that = this;
			let data = e.detail;
			if (!data.encryptedData || !data.iv) return false;
			let _params = {
				sessionKey: this.sessionKey,
				iv: data.iv,
				encryptedData: data.encryptedData
			}; // console.log("!!!!!!!!!!!!!!!!!!!!!!"+_params)

			if (req.getStorage('pidCode')) {
				_params.parentId = req.getStorage('pidCode');
			}

			// console.log("登录页面===" + JSON.stringify(_params));
			req.postRequest('/api/login', _params, json => {
				let params = json;
				// console.log(json);
				that.setData(params);
				let url = req.getStorage('REDIRECT_URL');
				req.setStorage('userInfo', json);

				// req.removeStorage('MERCHANT')
				if (that.scene) {
					that.back();
				} else {
					// console.log(json.mobile);

					if (that.istetphone != '1') {
						uni.navigateBack();
					} else {
						if (json.mobile) {
							uni.navigateBack();
						} else {
							that.isphoneFun();
						}
					}
				}

				that.isshop();
			});
		},

		//判断是否开启手机绑定
		isphoneFun() {
			this.setData({
				isphone: true,
				isLong: false
			});
			uni.setNavigationBarTitle({
				title: '绑定手机号'
			});
		},

		getPhoneNumber(e) {
			let that = this;
			let _params = {
				sessionKey: that.sessionKey,
				iv: e.detail.iv,
				encryptedData: e.detail.encryptedData
			};
			// console.log(e.detail.errMsg);

			if (req.getStorage('pidCode')) {
				_params.parentId = req.getStorage('pidCode');
			}

			if (e.detail.errMsg == 'getPhoneNumber:ok') {
				req.postRequest('/api/weixin/mobile', _params, json => {
					// console.log(json);

					if (json.mobile) {
						var userInfo = req.getStorage('userInfo');
						userInfo.mobile = json.mobile;
						req.setStorage('userInfo', userInfo);

						if (that.scene) {
							that.back();
						} else {
							uni.navigateBack();
						}
					}
				});
			} else {
			}
		},

		// 分销的配置
		isshop() {
			req.p('/api/distribution/config', data => {
				// console.log(data);
				req.setStorage('distribution', data);
			});
		}
	}
};
</script>
<style>
@import './authorize.css';
</style>
