<template>
	<view class="" :style="vuex_skin">
		<!-- #ifdef MP-WEIXIN -->
		<!-- 获取手机号 -->
		<u-popup v-model="phoneShow" mode="center" border-radius="14" width="70%">
			<view class="" style="padding: 30rpx 50rpx 0;">
				<view class="center">
					<text class="text-bold">授权手机号</text>
				</view>

				<view style="padding: 80rpx 0;">
					<view class=" margin-bottom-20 text-sm text-center" style="line-height: 42rpx;">
						<text style="color: #949494;">为了保证用户评选公平，大赛采用实名制投票，需要授权获取您的手机号</text>
					</view>
				</view>

				<view class="flex justify-around">
					<button @click="phoneShow=false" class="cu-btn  radius bg-gray "
						style="height: 60rpx;margin-bottom: 20rpx;font-size: 24rpx;">
						暂不授权
					</button>
					<button class="cu-btn bg-base radius" style="height: 60rpx;margin-bottom: 20rpx;font-size: 24rpx;"
						open-type="getPhoneNumber" @getphonenumber="getphonenumber">
						确定授权
					</button>
				</view>
			</view>
		</u-popup>
		<!-- 获取头像昵称 -->
		<view @touchmove.stop.prevent="clear" v-show="dialogShow">
			<view class="popup_mask" @touchmove.stop.prevent="clear"></view>
			<view class="">
				<view class="dt-login-wrap" >
					<view class="title">请先登录</view>
					<view class="content">
						<view class="userinfo-avatar">
							<open-data type="userAvatarUrl"></open-data>
						</view>
						<open-data type="userNickName"></open-data>
						<text class="subtitle">申请获取您的公开信息（昵称,头像）</text>
					</view>
					<view class="btn-content setBtnCss">
						<button @click="hide" style="padding: 10rpx 0;">暂不登录</button>
						<button @click="getUserProfile" style="padding: 10rpx 0;">立即登录</button>
						<!-- <button v-else open-type="getUserInfo" @getuserinfo="getuserinfo">立即登录</button> -->
					</view>
				</view>
			</view>
		</view>
		<!-- #endif -->


		<!-- #ifndef MP-WEIXIN -->
		<view @touchmove.stop.prevent="clear" v-show="dialogShow">
			<view class="popup_mask" @touchmove.stop.prevent="clear"></view>
			<view class="">
				<view class="dt-login-wrap" style="width: 580rpx;margin-left: -290rpx;">
					<view class="title">请先登录</view>
					<view class="content" style="padding: 120rpx 40rpx ;">
						<u-form :model="form" ref="uForm" label-width="140" :border-bottom="borderBottom">
							<u-form-item label="手机号">
								<u-input v-model="form.phone" :clearable="false" />
							</u-form-item>
							<u-form-item label="验证码">
								<u-input :clearable="false" placeholder="请输入验证码" v-model="form.code"
									type="text"></u-input>
								<button slot="right" class="u-reset-button cu-btn radius sm bg-base" style="padding: 0 15rpx;height: 42rpx;line-height: 42rpx;" @click="getCode">
									{{codeTips}}
								</button>
							</u-form-item>
						</u-form>
						<view class="text-sm text-gray margin-top-20 text-left">
							<text style="color: #EF9944;">* 未注册过的手机号，点击登录时我们会给您创建一个新的账号</text>
						</view>
					</view>
					<view class="btn-content setBtnCss "
						style="background-color: #FFFFFF;border-radius: 20rpx;border-top: 1rpx solid #f4f4f4;">
						<button @click="hide" style="padding: 5rpx 0;border-right: 1rpx solid #f4f4f4;">暂不登录</button>
						<button @click="h5Login" style="padding: 5rpx 0;">立即登录</button>
					</view>
				</view>
			</view>
		</view>
		<!-- #endif -->
		<u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
		<toast ref="toast"></toast>
	</view>
</template>
<script>
	import pointAuth from "./alert/pointAuth.vue"
	export default {
		name: "login",
		components: {
			pointAuth
		},
		data() {
			return {
				customStyle: {
					'backgroundColor': '#EF9944',
					'color': '#ffffff'
				},
				codeTips: '',
				
				borderBottom: false,

				notToast: false,

				canIUseGetUserProfile: false,
				//保存时间七天
				cacheTime: 1 * 24 * 60 * 60 * 7,
				dialogShow: false,
				jscode: '',
				//邀请码
				inviteCode: '',
				userInfo: '',
				sessionKey: '',

				//获取手机号
				phoneShow: false,


				//h5登录
				form: {
					phone: '',
					code: '',
					smsId:""
				}
			};
		},
		beforeDestroy() {
			if (this.timer) {
				clearTimeout(this.timer)
				this.timer = null
			}
		},
		created() {
			if (uni.getUserProfile) {
				this.canIUseGetUserProfile = false
			}
		},
		methods: {
			codeChange(text) {
				this.codeTips = text;
			},
			// 获取验证码
			getCode() {
				if (this.$isEmpty(this.form.phone)) {
					this.$refs.toast.info('请输入手机号')
					return
				}
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					let params = {
						phone: this.form.phone
					}
					let p = this.$u.queryParams(params)
					this.$api.sms.send(p).then(res => {
						if (res.data.data.success) {
							this.form.smsId =res.data.data.id
							this.$refs.toast.info('验证码已发送')
							// 通知验证码组件内部开始倒计时
						} else {
							this.$u.toast(res.data);
						}
						this.$refs.uCode.start();
					})
				} else {
					this.$refs.toast.info('倒计时结束后再发送')
				}
			},
			async h5Login() {
				if (this.$isEmpty(this.form.phone)) {
					this.$u.toast("请输入手机号")
					return
				}
				if (this.$isEmpty(this.form.code)) {
					this.$u.toast("请输入验证码")
					return
				}
				if (this.$isEmpty(this.form.smsId)) {
					this.$u.toast("验证码已过期，请重新获取")
					return
				}
				let res = await this.$api.loginUser.h5Login(this.form)
				if (this.$isEmpty(res.data.data) && !res.success) {	
					this.$u.toast(res.msg)
					return
				}
				let userInfo = res.data.data
				console.log(userInfo);
				this.$u.toast("登录成功")
				this.$cache.put("userInfo", userInfo)
				this.$u.vuex('vuex_userId', userInfo.id)
				this.$u.vuex('vuex_phone', userInfo.phone)
				console.log(this.vuex_phone, "this.vuex_phone");
				this.$emit('signIn', userInfo)
				this.hide()
			},
			//获取手机号
			showPhoneModal() {
				this.phoneShow = true
			},
			//隐藏授权弹框
			hidePhoneModal() {
				this.phoneShow = false
			},
			show(notToast) {
				this.notToast = notToast || false
				//获取邀请码
				this.inviteCode = this.$cache.get('inviteCode')
				this.dialogShow = true
				// #ifdef MP-WEIXIN
				this.$mpi.wxLogin().then(res => {
					this.jscode = res.code
				})
				this.setTimer()
				// #endif
			},
			hide() {
				if (this.timer) {
					clearTimeout(this.timer)
					this.timer = null
				}
				this.dialogShow = false;
				this.$emit('hide')
			},
			async setTimer() {
				let respWx = await this.$mpi.wxLogin()
				this.jscode = respWx.code
				// 每隔4分钟重新请求 jscode
				this.timer = setTimeout(() => {
					this.setTimer()
				}, 240000)
			},
			getUserProfile(e) {
				uni.getUserProfile({
					desc: '用于获取头像和昵称',
					success: (res) => {
						this.userInfo = res.userInfo
						console.log("getUserProfile获取用户信息", this.userInfo);
						this.doLogin()
					}
				})
			},
			getuserinfo(e) {
				console.log("getuserinfo获取用户信息", e);
				if (e.detail.errMsg != 'getUserInfo:ok') {
					return
				}
				this.userInfo = e.detail.userInfo
				this.doLogin()
			},
			getSex(gender) {
				if (gender == 1) {
					return "男"
				} else if (gender == 2) {
					return "女"
				} else {
					return "保密"
				}
			},
			async doLogin() {
				this.dialogShow = false
				try {
					this.respLogin = (await this.$api.wxApp.getOpenId({
						code: this.jscode
					})).data

					let openId = this.respLogin.data.openid

					if (this.$isEmpty(openId)) {
						this.$refs.toast.error('登录失败')
						return
					}
					let unionid = this.respLogin.data.unionid || ''
					this.sessionKey = this.respLogin.data.session_key
					//通过openid查询数据库中该用户是否存在
					let params = {
						nickName: this.userInfo.nickName,
						avatar: this.userInfo.avatarUrl,
						sex: this.getSex(this.userInfo.gender),
						unionid,
						openid: openId,
						province: this.userInfo.province,
						city: this.userInfo.city
					}
					//将openid
					let resp = await this.$api.loginUser.login(params)
					let userData = resp.data.data
					if (this.$isNotEmpty(userData.id)) {
						//登录成功
						let obj = {
							...userData,
							sessionKey: this.sessionKey,
						}
						//将openid和sessionkey存进缓存中,有效时间为七天
						this.$cache.put("userInfo", obj)
						this.$u.vuex('vuex_userId', userData.id)
						if (userData.phone) {
							this.$u.vuex('vuex_phone', userData.phone)
						}
						//移除邀请码
						this.$cache.remove('inviteCode')
						this.dialogShow = false

						//获取手机号
						if (this.$isEmpty(this.vuex_phone) && this.$config.isAuthPhone) {
							this.showPhoneModal()
						} else {
							if (!this.notToast) {
								this.$u.toast('登录成功')
							}
						}
						//登录成功
						this.$emit('signIn', resp)

					} else {
						this.$refs.toast.error('登录失败')
					}

				} catch (e) {
					console.error(e);
					this.$refs.toast.error('登录失败')
				} finally {
					if (this.timer) {
						clearTimeout(this.timer)
						this.setTimer()
					}
				}
			},
			clear() {
				return
			},
			async getphonenumber(e) {
				this.hidePhoneModal()
				if (e.detail.errMsg != 'getPhoneNumber:ok') {
					console.log("获取手机号失败");
					return
				}
				if (this.$isEmpty(this.sessionKey)) {
					this.sessionKey = this.$cache.get('userInfo').sessionKey
				}
				let params = {
					sessionKey: this.sessionKey,
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv
				}
				this.$api.wxApp.getOpenData(params).then(res => {
					if (res.data.success) {
						let obj = JSON.parse(res.data.data)
						let phone = obj.phoneNumber
						this.cachePhone(phone)
					}
				})
			},
			cachePhone(phone) {
				let userInfo = this.$cache.get('userInfo')
				let params = {
					userId: userInfo.id,
					phone
				}
				this.$api.loginUser.savePhone(params).then(res => {
					console.log(res);
					if (res.data.success) {
						userInfo.phone = phone
						this.$cache.put('userInfo', userInfo)
						this.$u.vuex('vuex_phone', phone)
						this.$emit('phoneSuccess')
					} else {
						this.$refs.toast.error(res.msg)
					}
				})
			}

		}
	};
</script>

<style lang="scss">
	.popup_mask {
		position: fixed;
		bottom: 0;
		top: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.4);
		opacity: 1;
		z-index: 98;

	}

	.dt-login-wrap {
		position: fixed;
		border-radius: 16rpx;
		background: #ffffff;
		width: 560rpx;
		z-index: 99;
		bottom: 30%;
		left: 50%;
		margin-left: -280rpx;
		right: 0;
		text-align: center;

		.title {
			padding-top: 40upx;
			font-size: 34upx;
			font-weight: bold;
		}

		.content {
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			padding-top: 30rpx;
			padding-bottom: 150rpx;

			.userinfo-avatar {
				overflow: hidden;
				display: block;
				width: 140rpx;
				height: 140rpx;
				margin: 20rpx 20rpx 40rpx;
				border-radius: 50%;
				border: 2px solid #fff;
			}
		}

		.subtitle {
			color: #7e7e7e;
			font-size: 26upx;
			margin-top: 30rpx;
		}

		.btn-content {
			display: flex;
			width: 100%;
			border-radius: 0;
			border-top: 1upx solid #ebebeb;

			button {
				border: none;
				width: 50%;
				font-size: 30rpx;
				background-color: #FFFFFF;
				color: #66656a;
			}

			button:first-child {
				border-right: 1rpx solid #ebebeb;
				border-radius: 0 0 0 18rpx;
			}

			button:last-child {
				color: var(--bgColor);
				border-radius: 0 0 18rpx 0;
			}

		}

		.btn-content button::after {
			border: none;
		}
	}
</style>
