<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='phone'>
      <view class='logo'>
        <image src='{{about.logo}}'></image>
      </view>
    </view>
    <view class="bgfff form r10">
      <view class="borbom dflex"><image src="/pages/images/telephone.png"></image><input type="text" placeholder="请输入手机号" /></view>
      <view class="dflex paw"><image src="/pages/images/paw.png"></image><input type="text" placeholder="请输入验证码" /><text class="huoqu">获取验证码</text></view>
    </view>
    <view class="btn">
      <button class="goloing">立即登录</button>
      <view class="gophone1 r10">微信手机号快捷绑定</view>
      <navigator url="/mine/page/page?title=用户协议&isXieyi=true" hover-class="none" class="xieyi">《用户协议》</navigator>
      <view class='copy'>{{about.name}}版权所有© {{about.recordNumber}}</view>
    </view>
  </block> -->
		</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>
	</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,
			configRes: {},
			logo: '',
			name: '',
			isPromote: false, //是否从分销进入
			isXyShow: true ,//默认显示协议指引
			XyBottom: '-100%',
		};
	},

	components: {},
	props: {},
	onLoad: function(options) {
		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
			});
		} 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
				});
			});
		}

		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) {
				uni.switchTab({
					url: req.header.appId == 'ZQ1VK5oc17I387E' ? '/pages/timelyDelivery/index' : '/pages/index/index'
				});
			} else {
				uni.navigateBack();
			}
		},

		getAbout() {
			var _this = this;
			req.getRequest(
				'/api/user/aboutUs',
				{},
				function(res) {
					_this.setData({
						about: res
					});
				},
				true
			);
		},
		getWXUserProfile() {
			let that = this;
			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);
					}
				});
			}
		},
		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');
				if (json.token) req.setStorage('AUTH_TOKEN', json.token);
				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: this.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>
