<template>
	<div
		class="flex h-screen w-screen items-center justify-center"
		v-if="$resources.signupSettings.loading"
	>
		<Spinner class="mr-2 w-4" />
		<p class="text-gray-800">加载中</p>
	</div>
	<div class="flex h-screen overflow-hidden sm:bg-gray-50" v-else>
		<div class="w-full overflow-auto">
			<SaaSLoginBox
				title="验证您的邮箱"
				:subtitle="[
					`我们已向 ${email} 发送了一封邮件`,
					'请检查您的收件箱以获取后续步骤'
				]"
				:logo="saasProduct?.logo"
			>
				<template v-slot:default>
					<form
						class="flex flex-col"
						@submit.prevent="$resources.verifyCode.submit"
					>
						<FormControl
							label="验证码"
							type="text"
							variant="outline"
							placeholder="5位验证码"
							maxlength="5"
							v-model="code"
							required
						/>
						<ErrorMessage class="mt-2" :message="$resources.verifyCode.error" />
						<Button
							class="mt-8"
							variant="solid"
							:loading="
								$resources.verifyCode?.loading ||
								$resources.setupAccount?.loading
							"
							loading-text="验证中..."
							type="submit"
						>
							验证
						</Button>
						<Button
							class="mt-2"
							variant="outline"
							type="button"
							loading-text="重新发送邮件中..."
							:loading="$resources.resendOTP?.loading"
							@click="$resources.resendOTP.submit()"
						>
							未收到邮件？重新发送
						</Button>
					</form>
				</template>
			</SaaSLoginBox>
		</div>
	</div>
</template>
<script>
import { toast } from 'vue-sonner';
import SaaSLoginBox from '../../components/auth/SaaSLoginBox.vue';

export default {
	name: 'SaaSSignupVerifyEmail',
	props: ['productId'],
	components: {
		SaaSLoginBox
	},
	data() {
		return {
			account_request: this.$route.query.account_request,
			email: this.$route.query.email,
			code: '',
			requestKey: ''
		};
	},
	resources: {
		signupSettings() {
			return {
				url: 'jcloud.api.account.signup_settings',
				params: {
					product: this.productId,
					fetch_countries: false
				},
				auto: true
			};
		},
		verifyCode() {
			return {
				url: 'jcloud.api.account.verify_otp',
				params: {
					account_request: this.account_request,
					otp: this.code
				},
				onSuccess: key => {
					this.requestKey = key;
					this.$resources.setupAccount.submit();
				}
			};
		},
		resendOTP() {
			return {
				url: 'jcloud.api.account.resend_otp',
				params: {
					account_request: this.account_request
				},
				onSuccess() {
					this.otp = '';
					toast.success('已重新发送验证码到您的邮箱');
				},
				onerror() {
					toast.error('重新发送验证码失败');
				}
			};
		},
		setupAccount() {
			return {
				url: 'jcloud.api.product_trial.setup_account',
				makeParams() {
					return {
						key: this.requestKey
					};
				},
				onSuccess: data => {
					window.location.href = data?.location;
				}
			};
		}
	},
	computed: {
		saasProduct() {
			return this.$resources.signupSettings.data?.product_trial;
		}
	}
};
</script>