<template>
	<view>
		<status-nav :titleVal="'登录'" :tabcolor="'rgba(244, 244, 244,1)'" :whereCome="1*1" :statusTitle="true" :backgroudColor="'rgba(244, 244, 244,1)'"></status-nav>
		<!-- <view class='login-header'>
			<image class="infoImg" :style="{boxShadow: '0px 0px 20px '+ publicColor}" mode="aspectFit" :src="userInfo.avatarUrl || imgSrc"></image>
			<view class="logo-name">恒美植发</view>
		</view>
		<view class="login-box">
			<button class='login-btn' :style="{background:publicColor}" type='primary' @click="bindGetUserInfo">微信授权</button>
			<view class="xie-box">登录代表您已同意<text @tap="goXie" class="xieCon">《用户服务协议》</text></view>
		</view>
		<view v-if="isShowP" class="disjcac posAll">
			<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-sx10 radius10 tank-btn" style="background-color: rgba(230, 230, 230,1);color: #000000;">暂不绑定</view>
					<view :style="{background:publicColor}" class="pad-sx10 radius10 tank-btn posir">
						立即绑定
						<button open-type="getPhoneNumber" @getphonenumber="getphonenumber" class="posia syxzo">立即绑定</button>
					</view>
				</view>
			</view>
		</view> -->
		<view class='login-header'>
			<image class="infoImg" :style="{boxShadow: '0px 0px 20px '+ publicColor}" mode="aspectFit" :src="userInfo.avatarUrl || imgSrc"></image>
			<view class="logo-name">{{appletName}}</view>
		</view>
		<view class="login-box">
			<view @tap="setMiniColor">
				<button class='login-btn' open-type="getPhoneNumber" @getphonenumber="getphonenumber" :style="{background:publicColor}" type='primary'>手机号授权登录</button>
			</view>
			<view class="xie-box">登录代表您已同意<text @tap="goXie" class="xieCon">《用户服务协议》</text></view>
		</view>
		<!-- <view v-if="isShowP" class="disjcac posAll">
			<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 :style="{background:publicColor}" class="pad-sx20 radius10 tank-btn posir">
						立即授权
						<button @click="bindGetUserInfo" class="posia syxzo">立即授权</button>
					</view>
				</view>
			</view>
		</view> -->
		<!-- 获取头像&昵称 -->
		<view class="pop-up-bg" v-if="isShowP"> <!-- v-if="isShowP" -->
			<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="bindGetUserInfo">授权</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				userInfo: {
					nickName:'',
					avatarUrl:''
				}, //用户信息
				canIGetUserProfile: false,
				imgSrc: '/static/public/logo.png',//默认logo头像
				logoAvatar:'/static/public/logo-avatar.png', //默认用户头像
				appletName:'恒美植发',//小程序名称
				appletImg:'',//小程序logo
				isShowP:false,
			};
		},
		computed: {
			// 主题颜色
			publicColor() {
				return this.$store.state.publicColor
			}
		},
		onLoad(options) {
			this.appletImg = uni.getStorageSync('appletImg');
			// 检测当前运行环境并缓存域名
			this.$toolAll.tools.currentContext();
			this.setLogo();
			this.$toolAll.tools.isVedio();
			// let ya = this;
			// // 微信扫码后会自动编码,所以需要解码
			// if (options && options.q) {
			// 	let arr = decodeURIComponent(options.q).split('?')[1].split('&')
			// 	let obj = {}
			// 	arr.forEach(item => {
			// 		let brr = item.split('=')
			// 		obj[brr[0]] = brr[1]
			// 	})
			// 	// console.log(obj) //得到参数组成的对象
			// 	ya.invite_code = obj.invite_code
			// }
			if (uni.getUserProfile) {
				this.canIGetUserProfile = true;
			}
		},
		methods: {
			// 设置logo图
			setLogo(){
				this.$requst.get('index/base-config').then(res=>{
					this.imgSrc = this.$http + res.data.logo;
					this.appletName = res.data.appletName;
				})
			},
			refuse(){//暂不绑定事件
				this.isShowP=false;
				this.$toolAll.tools.showToast('登录成功','success')
				uni.reLaunch({url:'/pages/tabbar/pagehome/pagehome'})
			},
			// 设置主题色
			setMiniColor(){
				this.$requst.get(`index/mini-program-setting`).then(res=>{
					this.publicColor = res.data.mainColor;
					uni.setStorageSync('publicColor', res.data.mainColor) //#3875F6 #2E8B57
				})
			},
			getphonenumber(e){//授权绑定手机号
				let ya = this;
				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=>{
									console.log('手机号信息：',res);
									if(res.code==0){
										this.$toolAll.tools.showToast('手机号绑定成功','success');
										this.isShowP = true;
										// uni.reLaunch({url:'/pages/tabbar/pagehome/pagehome'})
									} else this.$toolAll.tools.showToast(res.msg);
								},error=>{})
							} else {
								// console.log('取消授权手机号')
							}
						}).catch(err=>{
							console.log(err);
						})
					}
				})
			},
			goXie(){
				uni.navigateTo({
					url:'/pages/login/xiey'
				})
			},
			//调起登录授权
			bindGetUserInfo(e) {
				let ya = this;
				//新版登录方式
				uni.login({
					provider: 'weixin',
					success: (res)=> {
						if (res.code) {
							ya.updateUserInfo(res.code);
						} else {
							uni.showToast({
								title: '登录失败！',
								duration: 2000
							});
						}
					},
				});
			},
			
			// 头像上传
			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.isShowP = 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;
				}
			},
			//调用登录接口
			updateUserInfo(code) {
				let ya = this;
				uni.showToast({
					title: '登录中...',
					icon:'loading',
					duration:10000
				})
				var params = {
					code:code,
					nickname: ya.userInfo.nickName,//用户昵称
					headimgurl: ya.userInfo.avatarUrl,//用户头像
					country: ya.userInfo.country,//用户所在国家
					province: ya.userInfo.province,//用户所在省份
					city: ya.userInfo.city,//用户所在城市
					gender: ya.userInfo.gender,//用户性别
					language:ya.userInfo.language,//语言
					is_active:1
				}
				this.$requst.post('user/login',params).then(res => {
					if(res.data.token!=''){
						uni.setStorageSync('params',params)
						uni.setStorageSync('userId',res.data.account_id)
						uni.setStorageSync('token',res.data.token)//缓存token
						uni.setStorageSync('openid',res.data.openid)//缓存openid
						uni.setStorageSync('expire',res.data.expire)//缓存失效时间（时间戳格式）
						uni.setStorageSync('phone_active',res.data.phone_active)//是否第一次授权
						uni.setStorageSync('is_active',res.data.is_active)//是否第一次授权
						uni.setStorageSync('invite_code',res.data.invite_code)
						uni.hideToast()
						// if(res.data.phone_active!=1){
						// 	this.isShowP = true;
						// } else {
							if(uni.getStorageSync('urlparams')) {
								uni.reLaunch({ // 重新进入当前页面
									url:uni.getStorageSync('urlparams')
								})
							} else {
								uni.reLaunch({
									url:'/pages/tabbar/pagehome/pagehome'
								})
							}
						// }
					}
				},error => {})
			}
		}
	}
</script>
<style lang="less">
	@tcolor:#333333;
	@tcolorp:#3875F6;
	.login-header {display: flex;justify-content: center;align-items: center;flex-direction: column;margin-top: 40%;}
	.infoImg {width: 192rpx;height: 192rpx;border-radius: 100%;}
	.logo-name {font-size: 30rpx;font-weight: bold;margin-top: 20rpx;color: @tcolor;}
	.login-box {margin-top: 60rpx;text-align: center;}
	.login-btn {width: 80%;margin-top: 50%;}
	.xie-box{display: flex;justify-content: center;align-items: center;color: @tcolor;margin-top: 30rpx;}
	.xieCon{color: @tcolorp;}
	
</style>
