<template>
	<view class="verify-container">
		<view class="title-wrapper">
			<view class="title">输入验证码</view>
			<view class="sub-title">验证码已发送到{{ countryCode }} {{ phoneNum }}</view>
		</view>
		
		<view class="verify-wrapper">
			<u-message-input
				:maxlength="6"
				active-color="#f2f2f2"
				inactive-color="#f2f2f2"
				:breathe="false"
				@finish="handleFinish"
			></u-message-input>
		</view>
		
		<view class="count-down" :class="{ disabled: disabled }" @click="getVerifyCode">重新获取 <template v-if="disabled">{{ countdown }}s</template></view>
	</view>
</template>

<script>
	import { phoneLogin } from '@/utils/login'
	
	export default {
		data() {
			return {
				phoneNum: '',
				countryCode: '+86',
				disabled: true,
				countdown: 60,
				timer: null,
				loading: false
			};
		},
		onLoad(options) {
			if (options.phoneNum) {
				this.phoneNum = options.phoneNum
			}
			if (options.countryCode) {
				this.countryCode = decodeURIComponent(options.countryCode)
			}
			this.startCountdown()
		},
		onUnload() {
			this.clearCountdownTimer()
		},
		methods: {
			getVerifyCode() {
				if (this.disabled || this.loading) return
				uni.showLoading({
					title: '正在发送验证码'
				})
				this.loading = true
				this.$Request
					.getT('/app/Login/sendMsg/' + this.phoneNum + '/bind')
					.then((res) => {
						if (res.code === 0) {
							this.startCountdown()
						} else {
							uni.showModal({
								showCancel: false,
								title: '短信发送失败',
								content: res.msg ? res.msg : '请一分钟后再获取验证码',
							});
						}
					})
					.finally(() => {
						this.loading = false
						uni.hideLoading();
					})
			},
			startCountdown() {
				this.disabled = true
				this.timer = setInterval(() => {
					this.countdown--
					if (this.countdown <= 0) {
					    this.clearCountdownTimer()
					    this.countdown = 60
					    this.disabled = false
					}
				}, 1000)
			},
			clearCountdownTimer() {
			    if (this.timer) {
					clearInterval(this.timer)
					this.timer = null // 重置定时器实例
				}
			},
			handleFinish(value) {
				phoneLogin({
					phone: this.phoneNum,
					msg: value
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.verify-container {
		padding: 0 40rpx;
		.title-wrapper {
			padding-top: 132rpx;
			.title {
				font-size: 40rpx;
				font-weight: 700;
				line-height: 52rpx;
				color: rgba(51, 51, 51, 1);
				margin-bottom: 12rpx;
			}
			.sub-title {
				font-size: 28rpx;
				line-height: 36rpx;
				color: rgba(153, 153, 153, 1);
			}
		}
		.verify-wrapper {
			margin: 120rpx auto 40rpx;
			::v-deep.u-char-flex {
				justify-content: space-between;
				.u-box {
					width: 40rpx;
					height: 40rpx;
					box-sizing: border-box;
					border-radius: 12rpx;
					background: rgba(250, 250, 250, 1);
					color: rgba(51, 51, 51, 1) !important;
				}
			}
		}
		.count-down {
			color: rgba(1, 107, 246, 1);
			font-size: 24rpx;
			line-height: 32rpx;
			&.disabled {
				color: rgba(1, 107, 246, 0.6);
			}
		}
	}
</style>