<template>
	<!--验证验证码-->
	<view class="retrieve-pwd">
		<u--form
			labelPosition="left"
			:model="formData"
			:rules="rules"
			ref="uForm"
			labelWidth="70"
		>
			<u-form-item borderBottom label="手机号">
				<view class="phone-num">
					<text>
						{{ formData.phoneNum }}
					</text>
				</view>
			</u-form-item>

			<u-form-item label="验证码">
				<c-input
					class="login-input"
					v-model="formData.code"
					placeholder="请输入验证码"
					type="number"
					border="none"
				>
					<view slot="suffix">
						<u-code
							keepRunning
							uniqueKey="retrieve-pwd-code"
							ref="uCode"
							@change="codeChange"
						></u-code>
						<u--text
							size="14"
							@click="getCode"
							type="primary"
							:text="tips"
						>
						</u--text>
					</view>
				</c-input>
			</u-form-item>
		</u--form>

		<view class="footer" style="margin-top: 130rpx">
			<c-button
				@click="nextStep"
				:key="isPassed"
				type="primary"
				:disabled="!isPassed"
			>
				下一步
			</c-button>
		</view>
	</view>
</template>

<script>
import { getAuthCode } from '@/api/com';
import { byPassword } from '@/api/user/login/retrievePwd'; // 找回密码手机验证码验证

export default {
	name: 'retrievePwd',
	data() {
		return {
			tips: '',
			formData: {
				phoneNum: '',
				code: '',
			},
			rules: {
				code: [
					{
						type: 'string',
						required: true,
						message: '请输入验证码',
						trigger: ['change'],
					},
				],
			},
		};
	},
	computed: {
		isPassed() {
			const code = this.formData.code;
			return code;
		},
	},
	onLoad(params) {
		this.formData.phoneNum = params.phoneNum;
	},
	methods: {
		async nextStep() {
			try {
				const params = {
					userName: this.formData.phoneNum,
					code: this.formData.code,
				};
				this.$c.loading();
				const { data } = await byPassword(params);
				uni.hideLoading();
				uni.$u.route({
					type: 'redirectTo',
					url: '/pages/user/retrievePwd/setNewPwd',
					params: {
						uuid: data,
						phone: this.formData.phoneNum,
					},
				});
			} catch (e) {
				uni.hideLoading();
				console.error(e);
			}
		},
		async getCode() {
			//注意：用户可能在倒计时的过程中点击获取验证码的按钮，组件内部提供了通过ref获取的canGetCode变量，在倒计时 过程中，该值为false
			if (!this.$refs.uCode.canGetCode) return;
			if (!this.formData.phoneNum) {
				// 手机号为空
				this.$c.toast('手机号不能为空');
				return;
			}
			uni.$c.loading('正在获取验证码');
			await getAuthCode({
				phone: this.formData.phoneNum,
				code: 'putPassword',
			});
			uni.hideLoading();
			uni.$c.toast('验证码已发送');
			// 通知验证码组件内部开始倒计时
			this.$refs.uCode.start();
		},
		codeChange(text) {
			this.tips = text;
		},
	},
};
</script>

<style scoped lang="scss">
.retrieve-pwd {
	padding: 28rpx;
	background-color: #f8f8f8;
	height: 100%;

	.u-form {
		padding: 8rpx 20rpx;
		background-color: #fff;
		border-radius: 6px;
	}

	.phone-num {
		display: flex;
		justify-content: flex-end;
		width: 100%;
		font-size: 13px;
		color: $u-tips-color;
	}
}
</style>
