<template>
	<view class="wrap">
		<view class="content">
			<view class="title">手机号登录</view>
			<input class="u-border-bottom" type="number" maxlength="11" v-model="tel" placeholder="请输入手机号" />
			<view class="u-text-center u-type-error u-m-t-20" v-if="telError">手机号输入错误</view>
			<button @tap="submit" :style="[inputStyle]" class="getCaptcha">获取短信验证码</button>
			<u-message-input v-if="show" :focus="true" :value="messageCode" @change="change" @finish="finish"
				mode="bottomLine" :maxlength="codelength"></u-message-input>
		</view>
		<!-- <view class="u-text-center u-type-error" v-if="phoneError">手机号输入错误</view> -->
		<view class="captcha">
			<!-- <text v-if="show&&this.messageDisable==false" @tap="noCaptcha">收不到验证码点这里</text> -->
			<text v-if="messageShow">{{ second }}秒后可重新获取验证码</text>
		</view>
		<view class="buttom">
			<view class="hint u-text-center">
				登录代表同意
				<text class="link" @tap="jumpToPage(1)">《用户服务条款》</text>和
				<text class="link" @tap="jumpToPage(2)">《隐私政策》</text>
				并授权使用您的账号信息（如昵称、头像、收货地址）以便您统一管理
			</view>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import getUrlParams from "./../../../utils/getUrlParams.js";
	export default {
		data() {
			return {
				tel: '',
				messageCode: '',
				messageShow: false,
				messageDisable: false,
				codelength: 4,
				show: false,
				second: 60,
				toastMsg: '',
				toastUrl: '',
				toastType: '',
				accessToken: '',
				userId: '',
				telError: false,
				// messageError:false
			}
		},
		onLoad(page) {
			//  如果存在code 则认为是微信登录完成后跳转过来的,直接获取信息跳转首页或者指定页面
			let locationLocaturl = window.location.search;
			this.code = getUrlParams(locationLocaturl, "code"); // 截取code
			if (this.code) {
				this.handleGetWXInfo(this.code) //把code传给后台获取用户信息
			}
		},
		computed: {
			inputStyle() {
				let style = {};
				if (this.tel.length == 11 && this.messageDisable == false && this.$u.test.mobile(this.tel)) {
					style.color = "#fff";
					style.backgroundColor = '#5295F5';
					this.telError = false;
					// style.backgroundColor = this.$u.color['warning'];
				} else if (this.tel.length == 11 && !this.$u.test.mobile(this.tel)) {
					this.telError = true;
				}
				return style;
			}
		},
		methods: {
			showToast() {
				this.$refs.uToast.show({
					title: this.toastMsg,
					type: this.toastType,
					url: this.toastUrl
				})
			},
			submit() {
				if (this.$u.test.mobile(this.tel) && this.messageDisable == false) {
					let that = this;
					this.$u.api.getPhoneLoginCode({
							mobile: this.tel
						})
						.then(res => {
							this.messageDisable = true;
							this.messageShow = true;
							this.show = true;
							let interval = setInterval(() => {
								that.second--;
								if (that.second <= 0) {
									that.messageDisable = false
									that.messageShow = false;
									if (that.messageCode.lenth != 4) {
										// this.messageError = true;
									}
									clearInterval(interval);
									that.second = 60;
								}
							}, 1000);
							this.accessToken = res.data.accessToken;
							this.userId = res.data.userId;
						}).catch(err => {
							this.toastMsg = err.code + ":" + err.msg;
							this.showToast();
						});
				}
			},
			// 收不到验证码选择时的选择
			// noCaptcha() {
			// 	uni.showActionSheet({
			// 		itemList: ['重新获取验证码', '接听语音验证码'],
			// 		success: function(res) {

			// 		},
			// 		fail: function(res) {

			// 		}
			// 	});
			// },
			// change事件侦听
			change(value) {
				// console.log('change', value);
			},
			// 输入完验证码最后一位执行
			finish(value) {
				let params = {
					accessToken: this.accessToken,
					userId: this.userId,
					code: value
				};
				this.$u.api.phoneLoginAuth(params)
					.then(res => {
						if (res.code == '200') {
							this.$u.vuex('vuex_token', this.accessToken);
							this.$u.vuex('vuex_user', res.data);
							this.$u.vuex('vuex_hasLogin', true);
							this.wechatLogin()

						} else {
							this.toastMsg = res.msg;
							this.showToast();
						}
					}).catch(err => {
						this.toastMsg = err.msg;
						this.showToast();
					});
			},
			// 微信登录
			wechatLogin() {
				this.jumpIndex()
				// const openId = this.$store.state.vuex_wxinfo?.openId
				// if (openId) {
				// 	this.jumpIndex()
				// } else {
				// 	this.getCode()
				// }
			},
			// 微信已登录则跳转到首页
			jumpIndex() {
				let ret = localStorage.getItem('backUrl')
				if (ret && ret.indexOf('phoneLogin') < 0) {
					// 截取url
					const pagesIndex = ret.indexOf('pages')
					if (pagesIndex > (-1)) {
						const pageUrl = ret.slice(pagesIndex)
						const tabbarUrl = ['pages/center/index', 'pages/parkingLists/parkingLists']
						if (tabbarUrl.indexOf(pageUrl) > (-1)) {
							setTimeout(() => {
								uni.switchTab({
									url: '../../index/index'
								})
							}, 100)
						} else {
							setTimeout(() => {
								uni.navigateTo({
									url: '/' + pageUrl
								})
							}, 100)
						}
					} else {
						uni.switchTab({
							url: '../../index/index'
						})
					}
				} else {
					uni.switchTab({
						url: '../../index/index'
					})
				}
			},
			// 获取code
			getCode() {
				const local = window.location.href // 获取页面url
				let locationLocaturl = window.location.search;
				this.code = getUrlParams(locationLocaturl, "code"); // 截取code
				if (this.code) { // 如果没有code，则去请求
					this.handleGetWXInfo(this.code) //把code传给后台获取用户信息
				} else {
					window.location.href =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.config.wxAppid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&#wechat_redirect`
				}
			},
			// 通过code获取 openId等用户信息，/api/user/wechat/login 为后台接口
			handleGetWXInfo(code) {
				uni.showLoading({
			  title: '加载中'
				})
				this.$u.api.getWXInfo(code).then((res) => {
					if (res.code === 200) {
						this.$u.vuex('vuex_wxinfo', res.data);
						this.jumpIndex()
					} else {
						this.$refs.uToast.show({
							title: '获取用户信息失败!',
							type: 'error',
						});
					}
					uni.hideLoading()
				}).catch((err) => {
					this.$refs.uToast.show({
						title: '获取用户信息失败!',
						type: 'error',
					});
				})
			},
			/**
			 * 跳转页面
			 * */
			jumpToPage(flag) {
				uni.navigateTo({
					url: "/pages/privacyPolicy/privacyPolicy?termsType=" + flag,
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.hide {
		display: none !important;
	}

	.wrap {
		font-size: 28rpx;

		.content {
			width: 600rpx;
			margin: 80rpx auto 0;

			.title {
				text-align: left;
				font-size: 60rpx;
				font-weight: 500;
				margin-bottom: 100rpx;
			}

			input {
				text-align: left;
				margin-bottom: 10rpx;
				padding-bottom: 20rpx;
				border-bottom: 1px solid #ddd;
			}

			.getCaptcha {
				margin: 45rpx auto 130rpx;
				background-color: #a8c6f1;
				color: $u-tips-color;
				border: none;
				font-size: 30rpx;
				padding: 12rpx 0;

				&::after {
					border: none;
				}
			}
		}

		.buttom {
			.hint {
				padding: 20rpx 40rpx;
				font-size: 20rpx;
				color: $u-tips-color;

				.link {
					color: $u-type-warning;
				}
			}
		}

		.captcha {
			color: $u-type-warning;
			font-size: 30rpx;
			margin-top: 40rpx;
			text-align: center;
		}
	}
</style>
