<template>
	<view class="body" :style="{height:screenHeight}">
		<u-toast ref="uToast"></u-toast>
		<view style="height: 40%;">
			<view class="logo">
				<u--image :src="logoSrc" width="120px" height="120px"></u--image>
			</view>
			<view class="title">登录 旭烁</view>
			<!-- <u-button text="getUserProfile" type="success" :hairline="false" throttleTime="2000" shape="circle" open-type="getUserProfile"
				@click="getUserProfile"></u-button> -->
			<u-button v-if="loginBtn" text="微信一键登录" type="success" :hairline="false" throttleTime="2000" shape="circle" 
				@click="openAuth"></u-button>
		</view>
		
		<!-- 微信获取手机号弹窗 -->
	   <u-modal :show="showAuthorizePhone" :show-title="false"
				 :show-confirm-button="false">
			<view class="slot-content">
				<div class="auth-card">
					<div class="img">
						<img class="avatar-img" :src="logoSrc" mode="widthFix">
					</div>
					<div class="title">{{bname}}</div>
					<div class="content">申请获得您的手机号</div>
				</div>
				<div class="auth-btncard u-flex u-row-between">
					<div class="btn-unok"><u-button :hair-line='false' :custom-style="customStyleUnOk" @click="showAuthorizePhone=false">拒绝</u-button></div>
					<div class="btn-ok"><u-button :hair-line='false' :custom-style="customStyleOk" open-type="getPhoneNumber" @getphonenumber="authPhone"> 允许</u-button></div>
				</div>
			</view>
		</u-modal>
		<!-- 微信获取用户头像昵称弹窗 -->
		<u-modal :show="showAuthorizeUser" :show-title="false"
		                 :show-confirm-button="false">
		    <view class="slot-content">
		        <div class="auth-card">
		            <div class="img">
		                <img class="avatar-img"
		                     :src="logoSrc"
		                     mode="widthFix">
		            </div>
		            <div class="title">{{bname}}</div>
		            <div class="content">邀请您补全个人信息<br></br>（昵称、头像）</div>
		        <div style="margin-left: 100rpx;margin-right: 100rpx">
		            <u-form :model="user" ref="uForm">
		                <u-form-item label="头像">
		                    <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" slot="right">
		                        <image class="avatar" :src="user.avatar"></image>
		                    </button>
		                </u-form-item>
		                <u-form-item label="昵称">
		                    <input type="nickname" class="weui-input u-border-bottom" @blur="nickNameInput" placeholder="请输入昵称"/>
		                </u-form-item>
		            </u-form>
		        </div>
		        </div>
		    <div class="auth-btncard">
		        <div class="btn-unok"><u-button :hair-line='false' :custom-style="customStyleUnOk" @click="showAuthorizeUser=false"> 拒绝</u-button></div>
		        <div class="btn-ok"><u-button :hair-line='false' :custom-style="customStyleOk" @click="authUser"> 允许</u-button></div>
		    </div>
		    </view>
		</u-modal>


	</view>
</template>

<script>
	export default {
		data() {
			return {
				loginBtn:true,
				bname:'旭烁集团',
				//屏幕高度
				screenHeight: "",
				logoSrc: "/static/logo.png",
				miniappLoginInfo:null,
				hasUserInfo:false,
				userInfo: null,
				user:{   
					avatar:'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
					name:'',
					mobile:'',
				},
				code: '',
				showAuthorizeUser: false,
				showAuthorizePhone: false,
				customStyleUnOk:{},
				customStyleOk:{'margin-left': '30px',color:'#00A447'},
				backUrl:null,
			};
		},
		onLoad() {
			let that = this;
			//获取屏幕高度，我的项目再store里已经取到了
			uni.getSystemInfo({
				success: (res) => {
					this.screenHeight = res.windowHeight + "px"
				}
			});
			uni.getStorage({
				key: 'backUrl',
				success: function (res) {
					that.backUrl = '/'+res.data;
				}
			});
		},
		onShow() {
			// uni.showLoading({
			// 	mask:true
			// });
			this.getChatCode();
			setTimeout(() => {
				this.openAuth();
				// this.showAuthorizeUser = true //弹出头像用户名
			}, 100);
			let userInfo = uni.getStorageSync('userInfo');
			this.user.name = userInfo.name;
		},
		methods: {
			openAuth(){
				this.showAuthorizePhone = true;
				// let userInfo = uni.getStorageSync('userInfo')
				// console.log('userInfo>>>>>>>>>>>>>>>>>>>>>',userInfo)
				// if(userInfo){
				// 	this.showAuthorizeUser = true;
				// }else{
				// 	this.showAuthorizePhone = true;
				// }
				// uni.hideLoading()
			},
			getChatCode() {
				//因为作用域先提前赋值
				var that = this
				//使用uni封装的一键登录方法
				uni.login({
					provider: 'weixin',
					success(res) {
						//成功后带着微信登录返回的code去请求我们的后端
						that.code = res.code;
						console.log('code',that.code);
					}
				})
			},
			getUserProfile() {
				var that = this
				uni.getUserProfile({
					desc: "获取你的昵称、头像",
					success(res) {
						console.log('getUserProfile success',res);
						if (res.errMsg == "getUserProfile:ok" && res.userInfo != undefined) {
							//我用store来存储一些数据，你可以放到你要放的地方
							console.log(' res.userInfo', res.userInfo);
							// that.$u.vuex('wx_user_info.nickName', res.userInfo.nickName);
							// that.$u.vuex('wx_user_info.avatarUrl', res.userInfo.avatarUrl);
							// that.getChatCode()
						}
					},
					complete(res) {
						// console.log('complete',res);
					}
				})
			},
			//获取昵称输入内容
			// userNameInput(e){
			//     this.user.nickName = e.detail.value
			// },
			onChooseAvatar(e) {
				console.log('头像信息》')
				console.log(e)
				this.user.avatar = e.detail.avatarUrl;
			},
			async authPhone(e){
				let errMsg = e.detail?.errMsg;
				if(errMsg!='getPhoneNumber:ok'){
					uni.showToast({
						title:'您已拒绝使用！',
						icon:'error'
					})
					return					
				}
				this.showAuthorizePhone=false;
				this.loginBtn = false;
				let _this = this;
				// this.getMobile()
				let mobileData = await this.$u.api.getMobile({code:e.detail.code});
				console.log('mobileData',mobileData);
				let mobile = mobileData.data?.mobile;
				if(mobile){
					this.mobile = mobile
					this.login(e);
				}else{
					uni.showToast({
						title: '没有获取手机号',
						icon:'error',
						duration: 2000
					});
					this.loginBtn = true;
				}
			},
			async login(e){
				// console.log('e',e);
				let _this = this;
				let wxinfo = await this.$u.api.wxinfo({code:this.code});
				let {openid,sessionKey,unionid} = wxinfo.data;
				
				_this.$u.vuex('vuex_wechatOpenid', openid);
				const { errMsg, iv, encryptedData } = e.detail;
				if (errMsg !== 'getPhoneNumber:ok') return;
				let data = {
					code: this.code,
					encryptedData: encryptedData,
					ivStr: iv,
					wechatOpenid:openid,
					sessionKey,
					sourceType:1,
					mobile:this.mobile
				}
				// console.log('----------登陆中',data)
				this.$u.api.login(data).then(res=>{
					console.log('微信登录返回结果========',res.data)
					_this.$u.vuex('vuex_user_info', res.data);
					// _this.$u.vuex('vuex_member_info',res.data);
					// uni.setStorageSync('userInfo', res.data)
					this.showAuthorizePhone = false
					this.getMemberInfo(res.data.userid);
				}).catch(err=>{
					console.log('err',err);
					this.showAuthorizePhone = false
				})
			},
			getMemberInfo(userid){
				let _this = this;
				this.$u.api.memberInfo({id:userid}).then(res=> {
					if(res.code ===200) {
						_this.userInfo = res.data;
						this.$u.vuex('vuex_member_info', res.data);
						// this.$u.vuex('vuex_member_info.avatar', 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0');
						if(!res.data.name){
							this.$u.vuex('vuex_member_info.name', '微信用户');
							this.updateMemberInfo();
						}else{
							let url = this.backUrl&&this.backUrl.length>0?this.backUrl:'/pages/index/index';
							uni.navigateTo({
								url: url
							})
						}
						// 下面需要获取微信头像和昵称
						// if(res.data.name){
						// 	_this.hasUserInfo = true;
						// 	_this.userInfo = res.data;
						// 	uni.navigateTo({
						// 		url: '/pages/index/index'
						// 	})
						// }else{
						// 	_this.showAuthorizeUser = true
						// 	// uni.hideLoading()
						// }
						// console.log('---------登陆成功')
						
					}
				})
			},
			updateMemberInfo(){
				let params ={
					id:this.userInfo.id,
					// avatar:'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
					name:'微信用户'
				};
				this.$u.api.updateMemberInfo(params).then(res=>{
					let url = this.backUrl&&this.backUrl.length>0?this.backUrl:'/pages/index/index';
					uni.navigateTo({
						url: url
					})
				}).catch(err=>{
					console.log('err',err);
				})
			},
			authUser(){
				let userInfo = this.vuex_user_info || {};
				// console.log('this===',this);
				// console.log('vuex_user_info===',this.vuex_user_info);
				// console.log('userInfo',userInfo);
				// console.log('this.user',this.user);
				if(!this.user.name){
					uni.showToast({
						title: '请输入您的昵称！',
						icon:'error',
						duration: 2000
					});
					return;
				}
				userInfo.avatar = this.user.avatar;
				userInfo.name =  this.user.name;
				this.userInfo = userInfo;
				uni.setStorageSync('userInfo', userInfo)
				this.user.id = userInfo.userid;
				let param = {
					id:this.user.id,
					name:this.user.name,
					avatar:this.user.avatar
				}
				this.$u.api.updateMemberInfo(param).then(res=>{
					this.hasUserInfo = true;
					this.showAuthorizeUser = false;
					uni.navigateTo({
						url: '/pages/index/index'
					})
				}).catch(err=>{
					console.log('err',err);
				})
			},
			nickNameInput(e){
				this.user.name = e.detail.value
			}
		}
	}
</script>

<style lang="scss" scoped>
.body {
	// width: 100%;
	background-color: #f3f3f3;
	padding: 24px;
	box-sizing: border-box;
	.logo {
		padding-top: 200rpx;
		margin: auto;
		width: 120px;
		height: 120px;
	}

	.title {
		width: 90%;
		margin: 0 auto 30rpx;
		text-align: center;
		font-size: 18px;
		color: #111;
	}
}

// 

.auth-btncard{
	margin-top: 20px;
    .btn-unok{
        width: 45%;
        float: left;
    }
    .btn-ok{
        width: 45%;
        float: left;
        margin: 0;
        padding: 0;
        border: 0px solid transparent;  //自定义边框
        outline: none;    //消除默认点击蓝色边框效果
        u-button{
			font-size: 16px;
            margin: 0;
            padding: 0;
            // border: 0px solid transparent;  //自定义边框
            outline: none;    //消除默认点击蓝色边框效果
        }
    }
}
.auth-card{
    text-align: center;
    .avatar-img{
        width: 150rpx;
        height: 150rpx;
        overflow: hidden;
        border-radius: 100%;
        margin-top: 30rpx;
    }
    .title{
        font-size: 30rpx;
    }
    .content{
        margin-top: 10rpx;
		margin-bottom: 20rpx;
    }
}
.avatar-wrapper{
	width: 150rpx;
	height: 100rpx;
	color: #333 !important;
	text-align: center !important;
	border: none !important;
	border-radius:0 !important;
	background-color:transparent !important;
}
.avatar-wrapper::after {
	border: none !important;
}
.avatar{
	width: 100rpx;
	height: 100rpx;
	overflow: hidden;
	border-radius: 100%;
}


</style>

