<template>
	<view class="login">
		<!-- 小程序状态下登录 -->
		<!-- #ifdef MP-WEIXIN -->
		<view class="mp_wxBox">
			<view>
				<view class="headers">
					<image src="../../static/logo.png" style="border-radius: 50%;"></image>
				</view>
				<view class="content">
					<view>申请获取以下权限</view>
					<text style="margin-top: 20rpx;">获得你的公开信息(昵称，头像、地区等)</text>
				</view>
				<button v-show="weixinPhone" style="background: #FF7F00;background-color: #FF7F00;color: #FFFFFF;"
					class="bottom" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
					授权手机号
				</button>
				<!-- <button v-show="!weixinPhone" style="background: #FF3530; color: #FFF;" class="bottom"
					open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="wxGetUserInfo">
					立即登录
				</button> -->
				<button v-show="!weixinPhone" style="background: #FF7F00;color: #FFFFFF;" class='bottom'
					bindtap="getUserProfile" @tap="wxGetUserInfo">
					授权登录
				</button>

				<!-- 底部信息 -->
				<view class="footer">
					<text @tap="isShowAgree" class="cuIcon" :class="showAgree?'cuIcon-radiobox':'cuIcon-round'">同意
					</text>
					<!-- 协议地址 -->
					<navigator url="/pages/riderMy/set/mimi" open-type="navigate">《隐私政策》</navigator>和
					<navigator url="/pages/riderMy/set/xieyi" open-type="navigate">《用户服务协议》</navigator>
				</view>
			</view>
		</view>
		<!-- #endif -->


		<!-- #ifndef MP-WEIXIN -->
		<view class="register">
			<!-- <view class="back-btn yticon icon-zuojiantou-up" @click="navBack"></view> -->
			<view style="padding-top: 172upx;margin-left: 36upx;">
				<view style="color: #333333;font-size: 44upx;">手机快捷登录</view>
				<view style="color: #999999;font-size: 24upx;margin-top: 20upx;">未注册的手机号将自动创建账号</view>
			</view>
			<view style="margin-left: 26upx;margin-top: 104upx;">
				<wInput v-model="phoneData" type="number" maxlength="11" placeholder="请输入手机号"></wInput>
				<!-- <wInput v-model="passData" type="number" maxlength="6" placeholder="请输入密码"></wInput> -->
				<wInput v-model="verCode" type="number" maxlength="6" placeholder="请输入验证码" isShowCode ref="runCode"
					@setCode="sendMsg()"></wInput>
				<wInput v-show="show" v-model="invitation" isShowGet ref="setNumberCode" @setNumberCode="isShowGet()"
					placeholder="请填写邀请码"></wInput>
			</view>

			<view class="footer" style=" margin-right: 72px;">
				<image v-if="showAgree" @tap="isShowAgree"
					src="https://api.shengqianxiong.com.cn/img/20201112/669aa8946cfb4ebdb459d57193c0ebca.png"
					style="width: 36upx;height: 36upx;"></image>
				<image v-else @tap="isShowAgree"
					src="https://api.shengqianxiong.com.cn/img/20201112/1e9102fc891f4d86a13c7b2ba6921cba.png"
					style="width: 36upx;height: 36upx;"></image>
				<text style="margin-left: 10upx;margin-right: 0;">同意</text>
				<navigator url="/pages/riderMy/set/mimi" open-type="navigate">《隐私政策》</navigator>和
				<navigator url="/pages/riderMy/set/xieyi" open-type="navigate">《用户服务协议》</navigator>
			</view>
			<wButton text="登 录" :rotate="isRotate" @click.native="startReg()"></wButton>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import wInput from '@/components/watch-login/watch-input.vue' //input
	import wButton from '@/components/watch-login/watch-button.vue' //button

	export default {
		components: {
			wInput,
			wButton,
		},
		data() {
			return {
				phoneData: '',
				verCode: '',
				show: '',
				invitation: '',
				isRotate: false, //是否加载旋转
				platform: "app",
				userType: 2,
				passData: '', //密码

				numbers: '',
				password: '',
				type: 'number',
				pass: 'number',
				clearable: false,
				mobile: '',
				code: '',
				sessionkey: '',
				flag: '1',
				showAgree: false, //协议是否选择
				weixinPhone: false,
				sending: false,
				sendDataList: {},
				phone: '',
				sendTime: '获取验证码',
				count: 60
			}
		},
		methods: {
			navBack(){
				uni.navigateBack()
			},
			isShowAgree() {
				this.showAgree = !this.showAgree
			},
			startReg() {
				var that = this
				uni.getSystemInfo({
					success: function(res) {
						console.log(res.model);
						if (res.model == 'iPhone') {
							that.sysphone = 2
						} else if (res.model != 'iPhone') {
							that.sysphone = 1
						}
					}
				});
				//注册
				if (that.isRotate) {
					//判断是否加载中，避免重复点击请求
					return false;
				}
				if (that.showAgree == false) {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '请先同意《协议》'
					});
					return false;
				}
				if (that.phoneData.length != 11) {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '手机号不正确'
					});
					return false;
				}
				// if (that.passData.length < 5) {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		position: 'bottom',
				// 		title: '密码不能低于六位'
				// 	});
				// 	return false;
				// }
				if (that.verCode == 6) {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '验证码不正确'
					});
					return false;
				}
				that.isRotate = true;
				console.log('验证码', that.verCode, )
				// {
				// 	password: that.passData,
				// 	phone: that.phoneData,
				// 	msg: that.verCode,
				// 	platform: that.platform,
				// 	userType: that.userType,
				// 	sysphone: that.sysphone
				// 	// openid: this.$queue.getData("openid")
				// }

				var openid = this.$queue.getData("openid") ? this.$queue.getData("openid") : '';
				that.$Request.postJson("/app/Login/registerCode?password=" + that.passData + '&phone=' + that.phoneData +
					'&msg=' + that.verCode + '&platform=' + that.platform +
					'&userType=' + that.userType + '&sysphone=' + that.sysphone + '&openId=' + openid).then(res => {
					console.log(res)
					if (res.code == 0) {
						console.log(res.token)
						this.$queue.setData("token", res.token);
						this.$queue.setData("userId", res.user.userId);
						this.$queue.setData("mobile", res.user.phone);
						// this.getUserInfo(res.user.userId, res.token);
						uni.navigateTo({
							url: '/pages/index/index'
						})
						return false;
					} else {
						that.isRotate = false;
						uni.hideLoading();
						uni.showModal({
							showCancel: false,
							title: '登录失败',
							content: res.msg,
						});
					}
				});
			},
			sendMsg() {
				const {
					phoneData
				} = this;
				if (!phoneData) {
					this.$queue.showToast("请输入手机号");
				} else if (phoneData.length !== 11) {
					this.$queue.showToast("请输入正确的手机号");
				} else {
					this.$queue.showLoading("正在发送验证码...");
					this.$Request.getT("/app/Login/sendMsg/" + phoneData + '/register').then(res => {
						console.log(res)
						if (res.code == 0) {
							if (res.data === 'register') {
								this.show = true;
							}
							this.sending = true;
							this.$queue.showToast('验证码发送成功请注意查收');
							this.$refs.runCode.$emit('runCode');
							uni.hideLoading();
						} else {
							uni.hideLoading();
							uni.showModal({
								showCancel: false,
								title: '短信发送失败',
								content: res.msg ? res.msg : '请一分钟后再获取验证码',
							});
						}
					});
				}
			},
			// bindriderlogin() {
			// 	uni.navigateTo({
			// 		url: '/pages/login/running_rider/running_rider'
			// 	})
			// },
			forgetPwd() {
				uni.navigateTo({
					url: '/pages/login/forgetPwd'
				})
			},
			//第一授权获取用户信息===》按钮触发
			wxGetUserInfo(e) {
				if (!this.showAgree) {
					uni.showToast({
						title: '请选择用户和隐私协议',
						icon: 'none'
					})
					return
				}
				let that = this;
				wx.getUserProfile({
					desc: '业务需要',
					success: infoRes => {
						console.log("infoRes.encryptedData__________:",infoRes.userInfo)
						let userName = infoRes.userInfo.nickName; //昵称
						let avatarUrl = infoRes.userInfo.avatarUrl; //头像
						let sex = infoRes.userInfo.gender; //头像
						try {
							that.login(userName, avatarUrl, sex);
						} catch (e) {}
					}
				})
			},
			//小程序微信登录后获取手机号
			getPhoneNumber: function(e) {
				console.log(e);
				if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
					console.log('用户拒绝提供手机号');
				} else {
					console.log('用户同意提供手机号');
					this.setPhoneByInsert(e.detail.encryptedData, e.detail.iv);
				}
			},
			//小程序微信登录后获取手机号
			setPhoneByInsert(decryptData, iv) {
				this.$queue.showLoading('登录中...');

				let data = {
					decryptData: decryptData,
					key: this.sessionkey,
					iv: iv
				};
				this.$Request.postJson('/app/Login/selectPhone', data).then(res => {
					if (res.code === 0) {
						uni.hideLoading();
						this.phone = res.data.phoneNumber;
						this.getWeixinInfo(this.sendDataList);
					} else {
						uni.hideLoading();
						this.$queue.showToast(res.msg);
					}
				});
			},
			//获取个人信息
			getWeixinInfo(sendData) {
				let that = this;
				// let url = '/user/mp/update';
				uni.showLoading({
					title: '登录中...',
					mask: true, // 是否显示透明蒙层，防止触摸穿透
				});
				var postData = {
					riderOpenId: sendData.openid, //小程序openid
					platform: '小程序', //unionId
					userName: sendData.userName, //微信名称
					avatar: sendData.imageUrl, //头像
					userId: '', //性别
					phone: that.phone,
					inviterCode: sendData.invitation,
					sex: sendData.gender
				};
				that.$Request.postJson('/app/Login/insertWxRiderUser', postData).then(res => {
					console.log(res);
					if (res.code === 0) {
						uni.hideLoading();
						that.$queue.setData('token', res.token);
						that.$queue.setData('userId', res.user.userId);
						that.$queue.setData("avatar", res.user.avatar ? res.user.avatar : '/static/img/logo.png');
						that.$queue.setData("userName", res.user.userName);
						that.$queue.setData("invitationCode", res.user.invitationCode);
						that.$queue.setData("inviterCode", res.user.inviterCode);
						that.$queue.setData("sex", res.user.sex);
						that.$queue.setData("phone", res.user.phone);
						that.$queue.setData("platform", res.user.platform);

						that.$queue.setData("zhiFuBao", res.user.zhiFuBao);
						that.$queue.setData("zhiFuBaoName", res.user.zhiFuBaoName);

						that.$queue.setData("checkCertification", res.user.checkCertification);
						uni.navigateBack();
						// that.initUserInfo(res.user.userId, res.token);
					} else {
						uni.hideLoading();
						uni.showModal({
							showCancel: false,
							title: '登录失败',
							content: res.msg
						});
					}
				});
			},

			login(userName, avatarUrl, sex) {
				console.log(userName, avatarUrl, sex, '*********')
				let that = this;
				uni.showLoading({
					title: '登录中...',
					mask: true, // 是否显示透明蒙层，防止触摸穿透
				});
				// 1.wx获取登录用户code
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						var getParams = {
							code: loginRes.code,
							userType: 2
						};
						that.$Request.getT('/app/Login/wxRiderLogin', getParams).then(res => {
							console.log(res, '登录');
							if (res.code == 0) {
								
									that.$queue.setData('openid', res.data.open_id);
									that.$queue.setData('unionid', res.data.unionid);
									that.sessionkey = res.data.session_key;
									that.flag = res.data.flag;
									console.log(res.data.unionid, res.data.session_key);
									uni.hideLoading();
									//非第一次授权获取用户信息
									//获取用户信息后向调用信息更新方法
									that.$queue.setData("sessionkey", res.data.session_key);

									var userByinvitationId = that.$queue.getData('userByinvitationId');
									if (userByinvitationId) {
										that.userByinvitationId = userByinvitationId;
									} else {
										that.userByinvitationId = that.$queue.getInvitation();
									}
									var sendData = {
										openid: that.$queue.getData('openid'),
										unionid: that.$queue.getData('unionid'),
										userName: userName,
										imageUrl: avatarUrl,
										gender: sex, //性别
										invitation: that.userByinvitationId //别人登录进来携带你的邀请码
									};
									that.sendDataList = sendData;

									
									if (res.data.isPhone == 2) {
										that.weixinPhone = true
									} else {
										that.getWeixinInfo(sendData);
									}
							}
						});
					}
				});
			},
		}
	}
</script>

<style lang='scss'>
	.headers {
		text-align: center;
	}

	.headers>image {
		width: 400upx;
		height: 400upx;
	}

	.footer {
		/* // padding-left: 140upx; */
		justify-content: center;
		margin-top: 32upx;
		font-size: 24upx;
		color: #666666;
		display: flex;
		text-align: center;
		align-items: center;
	}

	page {
		background: #fff;
	}

	.send-msg {
		border-radius: 30px;
		color: black;
		background: white;
		height: 30px;
		font-size: 14px;
		line-height: 30px;
	}

	.container {
		top: 0;
		padding-top: 32upx;
		position: relative;
		width: 100%;
		height: 100%;
		overflow: hidden;
		background: #fff;


	}

	.mp_wxBox {}

	.headers {
		margin: 35% auto 50rpx;
		text-align: center;
		border-radius: 60rpx;
		width: 650rpx;
		height: 300rpx;
		line-height: 450rpx;


	}

	.headers image {
		width: 300rpx;
		height: 300rpx;
	}

	.content {
		text-align: center;
	}

	.headers text {
		display: block;
		color: #9d9d9d;
		/* // margin-top: 40rpx; */
	}

	.bottom {
		line-height: 80upx;
		border-radius: 80upx;
		margin: 50rpx;
		height: 80upx;
		font-size: 35rpx;
	}



	.welcome {
		position: relative;
		left: 30px;
		top: -55px;
		font-size: 28px;
		color: #555;
		text-shadow: 1px 0px 1px rgba(0, 0, 0, 0.3);
	}

	.input-content {
		padding: 0 20px;
	}

	.left-top-sign {
		font-size: 80px;
		/* color: $page-color-base; */
		position: relative;
	}

	.right-top-sign {
		position: absolute;
		top: 40px;
		right: -15px;
		z-index: 95;


	}

	.right-top-sign:before,
	.right-top-sign:after {
		display: block;
		content: '';
		width: 20px;
		height: 40px;
		background: #FF7F00;
	}

	.right-top-sign:before {
		transform: rotate(50deg);
		border-radius: 0 50px 0 0;
	}

	.right-top-sign:after {
		position: absolute;
		right: -198px;
		top: 0;
		transform: rotate(-50deg);
		border-radius: 50px 0 0 0;
		/* background: pink; */
	}

	/* ````` */
	.login {
		width: 100%;
	}

	.login_type {
		width: 90%;
		margin: 0 auto;
		margin-top: 50rpx;
		margin-bottom: 135rpx;
	}

	.type_name {
		font-size: 38rpx;
		font-weight: bold;
		letter-spacing: 2rpx;
	}

	.type_tit {
		color: #999999;
		font-size: 21rpx;
		margin-top: 10rpx;
	}

	/* 登录 */
	.login_input {
		width: 80%;
		margin: 0 auto;
	}

	.numbers {
		height: 120rpx;
	}

	.u-input__input {
		border-bottom: 1rpx solid #E6E6E6 !important;
	}

	.submit {
		width: 100%;
		height: 90rpx;
		background: #FF7F00;
		color: white;
		text-align: center;
		line-height: 90rpx;
		border-radius: 20rpx;
		margin-top: 75rpx;
	}

	.submit_bottom {
		display: flex;
		height: 70rpx;
	}

	.bottom_left {
		flex: 1;
		color: #999999;
		font-size: 26rpx;
		display: flex;
		justify-content: left;
		align-items: center;
	}

	.bottom_right {
		flex: 1;
		color: #FF7F00;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.wrapper {
		position: relative;
		z-index: 90;
		background: #fff;
		padding-bottom: 20px;
	}
</style>
