<template>
	<view class="content">
		<!-- #ifdef MP -->
		<view class="flex-center">
			<view class="logo-img-box">
				<image class="logo-img" src="../../static/image/logo.png" mode="scaleToFill"></image>
				<button class="userInfo flex-center" type="warn" @tap="loding?'':userInfoData()">
					<image class="icon margin-r-10" src="../../static/icon/weichat.png" mode="scaleToFill"></image>
					<text>微信授权登录</text>
				</button>
				<agreement @checkedChange='changeChecked'></agreement>
			</view>
		</view>
		<!-- <view class="info flex">
			<view>
				登录代表你已同意
			</view>
			<view class="text" @click="agreement">用户协议，</view>
			<view class="text" @click="privacy">隐私协议</view>
		</view> -->
		<view class="Mask" v-show="MaskShow">
			<view class="Mask-box">
				<view class="title">申请获取您的手机号</view>
				<view class="text">为了方便您的取货和我们的送货，并获取更多优惠活动,需要您的手机授权</view>
				<view class="btn_box">
					<button class="weixin" @click="outUser">取消</button>
					<button class="weixin" open-type="getPhoneNumber" @getphonenumber="PhoneNumber">授权</button>
				</view>
			</view>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	// #ifdef H5
	import {
		loginWinxin
	} from '@/utils/wxAuthorized';
	// #endif
	// #ifdef MP-WEIXIN
	import {
		wechatMpAuth
	} from '@/api/wx';
	import {
		loginWinxinMp
	} from '@/utils/wxMinProgram';
	// #endif
	import {
		mapMutations
	} from 'vuex';
	import {
		getUserInfo,
	} from '@/api/login.js';
	import {
		binding
	} from '@/api/set.js';
	import agreement from "./agreement.vue"
	export default {
		components: {
			agreement
		},
		data() {
			return {
				checked: false,
				userInfo: {}, //授权用户信息
				code: '', //授权code
				loding: false, //判断是否在点击中
				MaskShow: false, // 手机号授权弹窗
				cache_key: ''
			};
		},
		onLoad(option) {
			console.log(option, '船只');
			this.loadData();
		},
		methods: {
			...mapMutations('user', ['login', 'setUserInfo', 'logout']),
			changeChecked(check) {
				this.checked = check;
			},
			loadData() {
				let obj = this;
				// #ifdef H5
				loginWinxin();
				// #endif
				// #ifdef MP-WEIXIN
				loginWinxinMp().then(() => {
					wx.login({
						success(e) {
							console.log(e, 'loginWinxinMp');
							obj.code = e.code;
						},
						fill: function(e) {
							console.log(e)
						}
					})
				});
				// #endif
			},
			// #ifndef H5
			// 用户确认授权
			userInfoData(e) {
				const that = this;
				if (!that.checked) {
					uni.showModal({
						title: '提示',
						content: '请先阅读同意《卡羚能服服务》《隐私条例》',
						showCancel: false,
					});
					return;
				}
				// #ifdef MP-WEIXIN
				if (!this.loding) {
					wx.getUserProfile({
						desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
						success: res => {
							that.userInfo = res;
							that.loadMp();
						},
						fail: err => {
							obj.loding = false;
							uni.showToast({
								title: '您拒绝了请求,不能正常使用小程序',
								icon: 'error',
								duration: 2000
							});
							return;
						}
					});
				}
				// #endif
			},
			// #endif
			// #ifdef MP-WEIXIN
			// 退出用户登录
			outUser() {
				this.logout();
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			// 小程序授权登录
			loadMp(option) {
				let obj = this;
				obj.loding = true;
				// 获取登录授权页数据
				let user = obj.userInfo;
				// 获取推广人id
				// #ifndef MP
				let spread_spid = uni.getStorageSync('spread') || '';
				// #endif
				// #ifdef MP
				let spread_code = uni.getStorageSync('spread_code') || '';
				// #endif
				uni.showLoading({
					title: '授权中',
					mask: true
				});

				wechatMpAuth({
						code: obj.code,
						iv: user.iv,
						encryptedData: user.encryptedData,
						// #ifndef MP
						spread_spid: spread_spid,
						// #endif
						// #ifdef MP
						spread_code: spread_code
						// #endif
					})
					.then(({
						data
					}) => {
						obj.loding = false;
						obj.wchatAuth(data);
						console.log(data, '授权数据');
					})
					.catch(e => {
						obj.loding = false;
						uni.hideLoading();
						// 重新获取token
						// #ifdef MP-WEIXIN
						loginWinxinMp().then(() => {
							wx.login({
								success(e) {
									console.log(e, 'loginWinxinMp');
									obj.code = e.code;
								},
								fill: function(e) {
									console.log(e)
								}
							})
						});
						// #endif
					});

			},
			wchatAuth(data) {
				let obj = this;
				obj.cache_key = data.cache_key;
				// 保存token
				uni.setStorageSync('token', data.token);
				obj.GetUser().then((data) => {
					console.log(data, '返回用户的数据');
					try {
						uni.hideLoading();
						obj.login();
						// 保存返回用户数据
						obj.setUserInfo(data);
						if (data.phone == null || !data.phone) {
							obj.MaskShow = true;
						} else {
							obj.ToIndex();
						}
					} catch (e) {
						console.log(e, '登录');
					}
				}).catch((e) => {
					uni.hideLoading();
				})
			},
			// #endif
			ToIndex() {
				// let ur = uni.getStorageSync('present') || '/pages/index/index';
				// // 用于处理缓存bug
				// if (ur == 'pages/product/product') {
				// 	ur = '/pages/index/index';
				// }
				// uni.switchTab({
				// 	url: ur,
				// 	fail(e) {
				// 		uni.navigateTo({
				// 			url: ur,
				// 			fail(e) {
				// 				uni.navigateTo({
				// 					url: '/pages/index/index'
				// 				});
				// 			}
				// 		});
				// 	}
				// });
				uni.switchTab({
					url: '/pages/index/index'
				});
			},
			// 获取用户数据
			GetUser() {
				// 获取用户基础信息
				return new Promise((ok, error) => {
					getUserInfo({})
						.then(({
							data
						}) => {
							ok(data)
						})
						.catch(e => {
							error(e)
						});
				})
			},
			// #ifdef MP
			// 绑定手机号
			PhoneNumber(e) {
				let obj = this;
				console.log(e, '授权返回数据');
				obj.MaskShow = false;
				(obj.iv = e.detail.iv), (obj.encryptedData = e.detail.encryptedData);
				uni.setStorageSync('code', obj.code);
				let requestData = {
					flag: 1,
					cache_key: obj.cache_key,
					code: obj.code,
					iv: obj.iv,
					encryptedData: obj.encryptedData
				}
				
				obj.bindPhone(requestData).then((ar) => {

					if (ar.data.is_bind == 1) {
						obj.$api.msg(e.msg);
					} else {
						obj.GetUser().then((data) => {
							obj.setUserInfo(data);
							obj.ToIndex();
						});
					}

				}).catch(err => {
					obj.GetUser().then((data) => {
						obj.setUserInfo(data);
						obj.ToIndex();
					});
				})
			},
			// 绑定手机号
			bindPhone(data) {
				// 获取用户基础信息
				return new Promise((ok, error) => {
					binding(data)
						.then(function(e) {
							ok(e)
						})
						.catch(e => {
							error(e)
						});
				})

			}
			// #endif
		}
	};
</script>

<style lang="scss">
	page,
	.content {
		height: 100%;

		/* #ifdef MP-WEIXIN */
		.flex-center {
			height: 100%;
			text-align: center;
			line-height: 1;
		}
		/* #endif */
	}
	/* #ifdef MP-WEIXIN */
	
	.Mask {
		position: fixed;
		top: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(51, 51, 51, 0.7);

		.Mask-box {
			margin: auto;
			margin-top: 320rpx;
			padding: 50rpx 30rpx;
			width: 90%;
			height: 450rpx;
			top: 500rpx;
			left: 10%;
			background-color: #ffffff;
			border-radius: 15rpx;

			.title {
				text-align: center;
				font-size: 35rpx;
				font-weight: 700;
			}

			.text {
				font-size: 30rpx;
				color: #848484;
				padding-top: 50rpx;
			}

			.btn_box {
				margin: 70rpx 0 0 0;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
		}
	}

	.weixin {
		background: $base-color;
		width: 40%;
		color: #ffffff;
		border-radius: 50rpx;
		border: none;
		margin: 0 20rpx;
	}

	.logo-img {
		width: 385rpx;
		height: 385rpx;
		margin: 0 auto;
		border-radius: 50rpx;
	}

	.userInfo {
		margin: 0 100rpx;
		margin-top: 50rpx;
		padding: 30rpx 50rpx;
		color: #ffffff;
		border-radius: 99rpx;
		background-color: $base-color !important;
		.icon{
			width: 55rpx;
			height: 55rpx;
		}
	}
	/* #endif */
</style>
