<template>
	<view class="binding-phone-view">
		<view class="title-view">绑定手机</view>
		<view class="text-view">首次登录的用户需绑定手机</view>
		<view class="phone-view">
			<view class="left-view">+86</view>
			<view class="middle-view"></view>
			<view class="right-view"><input v-model="phone" type="number" width="100%" maxlength="20" clearable />
			</view>
		</view>
		<view class="code-view">
			<view class="left-view"><input v-model="code" type="number" maxlength="6" clearable /></view>
			<view class="right-view">
				<u-toast ref="uToast"></u-toast>
				<u-verification-code keep-running unique-key="binding-phone" :seconds="seconds" @end="end"
					@start="start" ref="uCode" @change="codeChange"></u-verification-code>
				<text :class="{ active: canGetCode }" @tap="$u.throttle(handleClick, 500)">{{ tips }}</text>
			</view>
		</view>
		<view class="bottom-vew" >
			<u-button type="primary" :disabled="disabled" :customStyle="buttonStyle"  :loading="loading" @click="handleClickSave">
				<view class="button-text">立即绑定</view>
			</u-button>
		</view>
		<view class="quick-title" @click="handleClickAgree">
			<view class="icon-view" :class="{ 'icon-agree': agree }"><u-icon name="checkmark-circle-fill" v-if="agree" size="44" color="#2979ff"></u-icon></view>
			<view class="agree-text-view">
				我已阅读并同意
				<text class="name-text" @tap.stop.prevent="toProtocol('protocol')">《用户服务协议》</text>
				和
				<text class="name-text" @tap.stop.prevent="toProtocol('policy')">《隐私政策》</text>
			</view>
		</view>
	</view>
</template>

<script>
	import login from '@/utils/login.js';
	const app = getApp()
	export default {
		data() {
			return {
				agree:false,
				phone: '',
				code: '',
				timer: null,
				canGetCode: true,
				seconds: 60,
				encryptedData: '',
				iv: '',
				loading: false,
				weixinAuthService: null,
				params: {},
				tips: '',
				buttonStyle: {
					height: '104rpx',
					backgroundColor: '#2979ff',
					color: 'transparent'
				}
			};
		},
		computed: {
			disabled() {
				return this.code && this.phone ? false : true;
			}
		},
		onReady() {
			this.canGetCode = this.$refs.uCode.canGetCode ? true : false;
		},
		onLoad(options) {
			console.log('-----options----', options);

			if (options) {
				let {
					unionId
				} = options;
				if (unionId) {
					this.params = options;
				}
			}
		},
		methods: {
			toProtocol(type) {
				if(type==='protocol'){
					uni.navigateTo({
						url: '/pages/mine/about/user-agreement/user-agreement'
					});
				}else{
					uni.navigateTo({
						url: '/pages/mine/about/privacy-agreement/privacy-agreement'
					});
				}
				
			},
			handleClickAgree() {
				this.agree = !this.agree;
			},
			checkAgree() {
				if (!this.agree) {
					uni.showToast({
						title: '请阅读并同意《用户服务协议》和《隐私政策》',
						icon: 'none',
						duration: 2000
					});
					return false;
				}
				return true;
			},
			handleClick() {
				if (!this.checkAgree()) {
					return;
				}
				if (this.phone == '') {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				var reg = /^[1][3456789][0-9]{9}$/;
				if (!reg.test(this.phone)) {
					uni.showToast({
						icon: 'none',
						title: '请输入正确的手机号'
					});
					return false;
				}
				this.startCode();
			},
			startCode() {
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码

					this.$u.toast('正在获取验证码');
					this.getCode();
				}
			},
			async getCode() {
				try {
					let res = await uni.$u.api.sendCode({
						mobile: this.phone
					});
					uni.hideLoading();
					if (res.data) {
						this.$u.toast('验证码已发送');
						this.$refs.uCode.start();
						console.log('--------发送成功----------');
					} else {
						uni.showToast({
							title: '获取验证码失败',
							icon: 'none'
						});
					}
				} catch (e) {
					console.log(e);
					if (e.msg) {
						uni.showToast({
							title: e.msg,
							icon: 'none'
						});
					}
					//TODO handle the exception
					uni.hideLoading();
				}
			},
			handleClickSave() {
				if (!this.checkAgree()) {
					return;
				}
				this.signup();
			},
			signup() {
				this.loading = true;
				var reg = /^[1][3456789][0-9]{9}$/;
				if (!reg.test(this.phone)) {
					uni.showToast({
						icon: 'none',
						title: '请输入正确的手机号'
					});
					this.loading = false;
					return false;
				}
				if (uni.$u.platform === '4') {
					this.onAppLogin();
				} else {
					this.onWxLogin();
				}
			},
			async onWxLogin() {
				try {
					let res = await login.appLogin();
					let params = {
						code: res.code,
						// nickname: userInfo.nickName,
						// avatar: userInfo.avatarUrl,
						// encryptedData: this.encryptedData,
						// iv: this.iv,
						// verify: this.code,
					};
					this.onAppLogin(params)
				} catch (e) {
					console.log('onWxLogin:fail', e);
					this.loading = false;
					//TODO handle the exception
				}
				this.loading = false;
			},
			async onAppLogin(paramsData={}) {
				let params = {
					...paramsData,
					mobileCode: this.code,
					mobile: this.phone,
					wxAppNo:1
				};
				try {
					let res = await uni.$u.api.newLoginWechatAuth(params);
					if (res&&res.code === 200) {
						login.setUserData(res.data, this)
						app.track('signup_login', {mobile: res.data.mobile});
						app.profileSet(this)
						app.profileAppend(this)
						app.getBaseInfo(this)
						uni.showToast({
							title: '登录成功',
							icon: 'none',
							mask:true
						});
						setTimeout(() => {
							this.goBackPage()
						}, 1000);
					} else {
						this.loading = false;
					    uni.hideLoading()
						uni.showToast({
							title: '登录失败，请重新登录',
							icon: 'none'
						});
						this.setLoginStatus(false)
					}
				} catch (e) {
					console.log('onAppLogin', e);
					//TODO handle the exception
				}
				this.loading = false;
			},
			toPage(){
				if (this.returnUrl) {
					// 需要跳转到特定页面
					var isSwitchTab = this.returnUrl.indexOf('pages/index/') != -1;
					this.$u.route({
						url: this.returnUrl,
						type: isSwitchTab ? 'switchTab' : 'redirectTo'
					});
				} else {
					uni.switchTab({
						url: '/pages/index/index'
					});
				}
			},
			goBackPage() {
				let pages = getCurrentPages();
				if(pages.length) {
					let index = pages.length - 1;
					if(index) {
						let prevPage = pages[index]; //上一个页面
						if (prevPage && prevPage.$vm) {
							prevPage.$vm.isRefresh = true;
						}
						uni.navigateBack({
							delta: 1
						})
					} else {
						uni.redirectTo({
							url:'pages/index/index'
						})
					}
				} else {
					uni.reLaunch({
						url: "pages/index/mine"
					})
				}
				
			},
			setLoginStatus(authed = true) {
				getApp().globalData.logout = false
				this.code = ''
			},
			codeChange(text) {
				this.tips = text;
			},

			end() {
				console.log('end');
				this.canGetCode = true;
			},
			start() {
				console.log('start');
				this.canGetCode = false;
			},
		}
	};
</script>

<style scoped lang="scss">
	.binding-phone-view {
		padding: 60rpx;
		background-color: #ffffff;
		height: 100vh;

		.title-view {
			font-size: 52rpx;
			color: #333333;
			font-weight: bold;
			margin-bottom: 24rpx;
		}

		.text-view {
			font-size: 28rpx;
			color: #8d8d8d;
			margin-bottom: 88rpx;
		}

		.phone-view {
			display: flex;
			align-items: center;
			font-weight: bold;
			font-size: 28rpx;
			color: #333333;
			background-color: #fafafa;
			border-radius: 16rpx;
			height: 104rpx;
			padding: 0 32rpx;
			margin-bottom: 48rpx;

			.left-view {
				width: 66rpx;
				text-align: left;
				flex-shrink: 0;
			}

			.middle-view {
				background-color: #8d8d8d;
				width: 4rpx;
				height: 28rpx;
				margin: 0 12rpx;
				flex-shrink: 0;
			}

			.right-view {
				flex: 1;
				padding-left: 8rpx;
			}
		}

		.code-view {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-weight: bold;
			font-size: 28rpx;
			color: #333333;
			background-color: #fafafa;
			border-radius: 16rpx;
			height: 104rpx;
			padding: 0 32rpx;
			margin-bottom: 96rpx;

			.left-view {
				width: 330rpx;
			}

			.right-view {
				font-weight: 400;

				.active {
					color: #3383fe;
				}
			}
		}

		.bottom-vew {
			.button-text {
				color: #ffffff;
				height: 104rpx;
				line-height: 104rpx;
				font-weight: bold;
				font-size: 32rpx;
			}
		}
		.quick-title {
			z-index: 10;
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			position: fixed;
			left: 0;
			bottom: 5%;
			text-align: center;
			line-height: 28upx;
			font-size: 24upx;
			color: #8d8d8d;
			font-weight: 500;
			&-weight {
				font-weight: bold;
				color: #333333;
			}
			&-icon {
				width: 28upx;
				height: 28upx;
				border-radius: 50%;
				margin-right: 16upx;
				border: 2upx solid #333333;
				display: inline-block;
			}
			.icon-view {
				width: 36rpx;
				height: 36rpx;
				font-size: 18rpx;
				border-radius: 50%;
				border: 2rpx solid #333333;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #ffffff;
				margin-right: 12rpx;
			}
		
			.icon-agree {
				// background-color: #3383fe;
				// color: #ffffff;
				border: 0rpx;
			}
			.name-text {
				color: #3383fe;
			}
		}
	}
</style>