<template>
	<view v-if="showAuth">
		<!-- 用户信息授权 -->
		<!-- <view v-if="showUserInfo" @touchmove.stop.prevent="moveHandle" :class="isAnimation==2?'card-box-userinfo':''" class="auth-box">
			<view :class="isAnimation==1?'card-box-userinfo':''">
				<view class="auth-top">
					<image :src="appletImg" mode=""></image>
					<view class="auth-top-content">
						<view>恒美植发客服代表提醒您：</view>
						<view>您当前是游客身份</view>
						<view>是否选择授权登录</view>
					</view>
				</view>
				<view class="auth-center">为了给您提供更好的服务，向您申请微信头像及昵称授权。</view>
				<view class="auth-bottom">
					<view @tap="chooseBtn" :class="noAuthBtn?'isNyin':'noyin'" class="btn btn-no">暂不授权</view>
					<view :class="yesAuthBtn?'isOyin':'noyin'" class="btn btn-yes">
						<text>立即授权</text>
						<button @tap="authEv" class="auth-btn">立即授权</button>
					</view>
				</view>
			</view>
		</view> -->
		
		<!-- 获取头像&昵称 -->
		<view class="pop-up-bg" v-if="showUserInfo"> <!-- v-if="showUserInfo" -->
			<view class="user-info-box">
				<view class="info">
					<view class="cover">
						<image :src="appletImg" mode="aspectFit"></image>
					</view>
					<view class="name">{{appletName}}</view>
					<view class="tips">
						<view>您当前是游客身份</view>
						<view>请补全个人信息并授权登录</view>
						<view>(昵称、头像)</view>
					</view>
				</view>
				<view class="msg">
					<view class="item">
						<text>头像</text>
						<button class="avatar" open-type="chooseAvatar" @chooseavatar="chooseAvatar">
							<view class="img"><image :src="userInfo.avatarUrl || logoAvatar" mode="aspectFit"></image></view>
						</button>
					</view>
					<view class="item">
						<text>昵称</text>
						<input class="nick-name" type="nickname" @blur="nickNameInput" v-model="userInfo.nickName" placeholder="请输入昵称" placeholder-style="color:#999"/>
					</view>
				</view>
				<view class="empower-btns">
					<view class="btn" @tap="refuseEv">拒绝</view>
					<view class="btn" @tap="authEv">授权</view>
				</view>
			</view>
		</view>
		
		<!-- 手机号授权 -->
		<view v-if="showMobile" @touchmove.stop.prevent="moveHandle" class="disjcac posAll" style="z-index: 1001;">
			<view class="bacf radius20 width100 tank-box">
				<view class="tc tank-box-itemone">请授权绑定手机号</view>
				<view class="fon28 colf pad-x30 pad-zy30 tc disjb">
					<view class="pad-sx20 radius10 tank-btn" style="background-color: rgba(230, 230, 230,1);color: #000000;">暂不绑定</view>
					<view class="pad-sx20 radius10 tank-btn posir pbackc">
						立即绑定
						<button open-type="getPhoneNumber" @getphonenumber="getphonenumber" class="posia syxzo">立即绑定</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {reportBuriedPoint} from '@/jsFile/publicAPI.js';
	export default {
		name:"auth-userInfo-mobileInfo",
		props:{
			optionObj:{//参数
				type:Object,
				default:()=>{
					return {}
				}
			},
			// appletImg:{//小程序头像
			// 	type:String,
			// 	default:'/static/public/like.png'
			// },
			appletName:{//小程序名称
				type:String,
				default:'恒美植发'
			}
		},
		data() {
			return {
				yesAuthBtn:false, // 是否点击立即授权按钮
				noAuthBtn:false, // 是否点击暂不授权按钮
				isAnimation:0, // 动画
				showAuth:false, // 是否显示授权弹框
				currentPage:'', // 当前页面路径
				showMobile:true ,// 是否显示手机授权弹框
				showUserInfo:false,
				flag:true,
				appletImg:'',//小程序logo
				userInfo: {
					nickName:'',
					avatarUrl:''
				}, //用户信息
				canIGetUserProfile: false,
				logoAvatar:'/static/public/logo-avatar.png', //默认用户头像
			};
		},
		destroyed() {
			console.log('清除路径缓存');
			uni.removeStorageSync('urlparams');
		},
		mounted() {
			this.appletImg = uni.getStorageSync('appletImg');
			// 转发进入：获取页面路径
			let pages = getCurrentPages(); //获取加载的页面
			let currentPage = pages[pages.length - 1]; //获取当前页面的对象
			// console.log(currentPage.route,'获取当前页面路径');
			console.log(currentPage.$page.fullPath,'获取当前页面完整路径带参数');
			// console.log(currentPage.options,'获取当前页面参数');
			uni.setStorageSync('urlparams',currentPage.$page.fullPath);
			if(uni.getStorageSync('token')=='' || uni.getStorageSync('phone_active')==0 || uni.getStorageSync('is_active')==0){
				this.loginEv(currentPage.options);
			}
			let pagesArr = getCurrentPages();
			// console.log(pagesArr.length,'获取页面栈大小');
			if(pagesArr.length==1) {
				uni.setStorageSync('outside',6);
			}
		},
		methods:{
			loginEv(data){
				uni.login({ 
					provider: 'weixin',
					success: (res)=> {
						if (res.code) {
							var params = {
								code: res.code,
								invite_code: data.invite_code || '', // 用户邀请码
								source_code: data.source_code || '', // 渠道
								channel: data.channel || ''
							}
							uni.request({
								url: `${uni.getStorageSync('hostapi')}user/login`,
								method: 'GET',
								data: params,
								success: res => { 
									if(res.data.data.token!=''){
										uni.setStorageSync('token',res.data.data.token); // 缓存token
										uni.setStorageSync('openid',res.data.data.openid)//缓存openid
										uni.setStorageSync('userId',res.data.data.account_id)//缓存用户id
										uni.setStorageSync('expire',res.data.data.expire); // 缓存失效时间（时间戳格式）
										uni.setStorageSync('phone_active',res.data.data.phone_active); // 是否绑定手机号
										uni.setStorageSync('is_active',res.data.data.is_active)//是否第一次授权
										if(res.data.data.phone_active==0 || res.data.data.is_active==0) {
											if(uni.getStorageSync('authorization')==1){
												this.showAuth = true;
											}else{
												this.showAuth = false;
											}
											// this.$requst.post('user/first-enter',{openid:res.data.data.openid,path:uni.getStorageSync('urlparams')}).then(res=>{})
										}else {
											uni.reLaunch({ // 重新进入当前页面
												url:uni.getStorageSync('urlparams')
											})
										}
									}
								},
							})
							// 调用登录事件
							// this.$requst.post('user/login',params).then(res => {
							// 	if(res.code==0){console.log(params,101);} else this.$toolAll.tools.showToast(res.msg);
							// },error => {
							// 	// this.$toolAll.tools.showToast(error.msg);
							// 	// setTimeout(()=>{
							// 	// 	uni.navigateTo({url:'/pages/login/login'})
							// 	// },2000)
							// })
						}
					},
				});
			},
			// 当弹框出现时，禁止底层滑动
			moveHandle(){
				return false
			},
			chooseBtn(){//暂不授权点击事件
				this.noAuthBtn = true;
			},
			
			// 头像上传
			uploadImg(url){
				uni.showLoading({
					title: '上传中'
				});
				this.$requst.upload('file/upload/image',{file:url}).then(res=>{
					if(res.code==0) {
						this.userInfo.avatarUrl = uni.getStorageSync('hostHttps')+res.data.src;
					}
					uni.hideLoading();
				})
			},
			
			// 获取头像
			chooseAvatar(e){
				// 上传头像
				this.uploadImg(e.detail.avatarUrl)
			},
			
			// 获取昵称
			nickNameInput(e){
				this.userInfo.nickName = e.detail.value
			},
			
			// 拒绝登录
			refuseEv(){
				this.$toolAll.tools.showToast('您已拒绝授权');
				this.showUserInfo = false;
			},
			
			// 验证登录信息
			checkForm(){
				if(!this.isActive){
					if(this.userInfo.avatarUrl==''){
						this.$toolAll.tools.showToast('请选择头像！')
						return false;
					}else if(this.userInfo.nickName==''){
						this.$toolAll.tools.showToast('请输入昵称！')
						return false;
					}else{
						return true;
					}
				}else{
					return true;
				}
			},
			
			authEv(){//立即授权事件
				if(this.flag) {
					this.flag = false;
					this.$toolAll.tools.showToast('正在调起授权...');
					this.yesAuthBtn = true;
					uni.login({// 获取登录用户code
						provider: 'weixin',
						success: (result)=> {
							uni.hideToast()
							// 调用更新用户信息事件
							this.updateUserInfo(result.code,this.userInfo);
						},
					});
				} else {
					this.$toolAll.tools.showToast('请勿重复点击');
				}
			},
			
			
			// 更新用户信息事件
			updateUserInfo(code,userInfo) {
				uni.showToast({title: '授权中...',icon:'loading',})
				var params = {
					code:code,
					nickname: userInfo.nickName,//用户昵称
					headimgurl: userInfo.avatarUrl,//用户头像
					language:userInfo.language,//语言
					is_active:1,
				}
				this.$requst.post('user/login',params).then(res => {
					if(res.code==0){
						this.$toolAll.tools.showToast('授权成功...','success')
						uni.setStorageSync('params',params);
						uni.setStorageSync('userId',res.data.account_id); // 缓存用户id
						uni.setStorageSync('token',res.data.token); // 缓存token
						uni.setStorageSync('openid',res.data.openid)//缓存openid
						uni.setStorageSync('expire',res.data.expire); // 缓存失效时间（时间戳格式）
						uni.setStorageSync('invite_code',res.data.invite_code); // 缓存用户邀请码
						uni.setStorageSync('is_active',res.data.is_active);
						uni.setStorageSync('phone_active',res.data.phone_active); // 是否第一次授权
						this.isAnimation++;
						if(res.data.phone_active==1){
							// 如果手机号已经存在，取消手机授权弹框
							this.showAuth = false;
							uni.setStorageSync('outside',6);//表示外界进来授权的
							uni.reLaunch({ // 重新进入当前页面
								url:uni.getStorageSync('urlparams')
							})
						} else {
							// 如果手机号不存在，调起手机号授权弹框
							this.showMobile = true;
						}
					}
				})
			},
			getphonenumber(e){//授权绑定手机号
				wx.login({
					success:(res)=>{
						this.$requst.post('user/login',{code:res.code}).then(result => {
							if(e.detail.errMsg=="getPhoneNumber:ok"){
								this.$requst.post('user/bind-phone',{openid:result.data.openid, session_key:result.data.session_key, iv:e.detail.iv,encryptedData:e.detail.encryptedData}).then(res=>{
									if(res.code==0){
										this.$toolAll.tools.showToast('手机号绑定成功','success');
										this.showUserInfo = true;
										this.showMobile = false;
										uni.setStorageSync('phone_active',1);//是否第一次授权
										uni.setStorageSync('outside',6);//表示外界进来授权的
										// this.showAuth = false; // 关闭手机号授权弹框
										// uni.reLaunch({ // 重新进入当前页面
										// 	url:uni.getStorageSync('urlparams')
										// })
									}
								})
							}
						})
					}
				})
			},
		}
	}
</script>

<style>
	.auth-box {position: fixed;top: 0;right: 0;left: 0;bottom: 0;display: flex;justify-content: center;align-items: center;z-index: 1000;}
	.auth-box > view {background-color: #FFFFFF;border-radius: 10rpx;padding: 30rpx;box-shadow: 0rpx 0rpx 20rpx rgba(0,0,0,.5);margin: 0 100rpx;}
	.auth-top {display: flex;}
	.auth-top image {width: 96rpx;height: 96rpx;flex-shrink: 0;}
	.auth-top-content {margin-left: 20rpx;}
	.auth-top-content view {font-size: 28rpx;margin-top: 20rpx;color: #999999;}
	.auth-top-content view:nth-child(1) {font-size: 30rpx;font-weight: bold;margin-top: 0;}
	.auth-center {font-size: 28rpx;margin: 30rpx 0;border-bottom: 1rpx solid #F5F5F5;border-top: 1rpx solid #F5F5F5;padding: 20rpx 0;}
	.auth-bottom {display: flex;justify-content: center;align-items: center;font-size: 24rpx;}
	.btn {padding: 20rpx 60rpx;border-radius: 4rpx;}
	.btn-no {color: #07ad60;background-color: #FFFFFF;border: 1rpx solid #CCCCCC;}
	.btn-yes {color: #FFFFFF;background-color: #07ad60;border: 1rpx solid #07ad60;position: relative;margin-left: 20rpx;}
	.auth-btn {position: absolute;top: 0;left: 0;right: 0;bottom: 0;opacity: 0;}
	.isNyin{box-shadow: 0rpx 3rpx 6rpx rgba(0,0,0,.5);}
	.isOyin{box-shadow: 0rpx 3rpx 6rpx rgba(0,0,0,1);}
	.card-box-userinfo {transform: rotate(360deg) scale(0);transition: all 1s ease-in-out;}
</style>
