<template>
    <div class="window-height regist-box column flex-center items-center">
        <div class="column flex-center items-center rounded light-shadow q-pa-xl bg-white" style="margin: 60px 0;">
            <div style="width:400px;padding:0 50px;">
                <div class="text-center">
                    <div style="font-size: 1.88vw; line-height: 1;" class="text-dark text-weight-bolder row items-end flex-center">
                        <span>Welcome to </span>
                        <img src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1715138194000_864.png" style="width:3.18vw;margin-left: 1.67vw;" alt="">
                    </div>
                    <div class="text-small" style="color:#404B5B;margin-top:0.99vw">创建账户，开启行程设计第一步</div>
                </div>
                <el-form ref="registFormRef" :model="model" :rules="rules" label-width="0px" size="large" class="full-width q-mt-lg" :disabled="loading"> 
                    <!-- <el-form-item label="" prop="nickname">
                        <el-input v-model="model.nickname" placeholder="昵称" class="q-mt-lg" />
                    </el-form-item> -->
                    <!-- <el-form-item label="" prop="account">
                        <el-input v-model="model.account" placeholder="账号" />
                    </el-form-item> -->
                    <el-form-item label="" prop="mail">
                        <el-input v-model="model.mail" placeholder="邮箱">
                            <template #suffix>
                                <el-button link :disabled="!mailRegex.test(model.mail)" :loading="sending" v-if="!isCountdown" @click="sendVerifyCode">{{ isSend?'重新发送':'发送验证码' }}</el-button>
                                <template  v-else>
                                    <el-countdown title="" format="ss" :value="countValue" value-style="font-size:14px;color:#f89c53;" class="inline q-mx-sm" @finish="()=>isCountdown=false" />s
                                </template>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="" prop="code">
                        <el-input v-model="model.code" placeholder="验证码" />
                    </el-form-item>
                    <el-form-item label="" prop="password">
                        <el-input v-model="model.password" type="password" placeholder="设置密码" autocomplete="new-password" show-password/>
                    </el-form-item>
                    <el-form-item label="" prop="confirmPwd">
                        <el-input v-model="model.confirmPwd" type="password" placeholder="确认密码" autocomplete="new-password" show-password/>
                    </el-form-item>
                    <el-form-item label="">
                        <vue-hcaptcha ref="invisibleHcaptcha" sitekey="46e00e53-ddb2-4e7b-9c51-621534c2f1f5" @verify="verifyHandler"></vue-hcaptcha>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" class="full-width q-mb-lg" @click="submitForm(registFormRef)" :loading="loading">立即注册</el-button>
                    </el-form-item>
                    
                    <div class="text-info text-small row flex-center">
                        <span>已有账号？</span>
                        <el-button link type="primary" class="q-mb-lg"  @click="redicetToLogin">立即登录</el-button>
                    </div>
                </el-form>
            </div>
        </div>
        <div class="text-small text-info q-mb-lg">@2012-2024 成都微途科技有限公司 版权所有 蜀ICP备13024891号-9</div>
    </div>
</template>
<script lang="ts" setup>
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { reactive, ref } from 'vue';
import UserServices from '@/services/UserService'
import { ApiResult } from '@/configs/axios';
import VueHcaptcha from "@hcaptcha/vue3-hcaptcha";

interface RuleForm {
  //account: string
  password: string
  //nickname: string
  confirmPwd:string
  mail:string,
  code:string
}
const model = ref<{password:string,confirmPwd:string,mail:string,code:string}>({
    //account:'',
    password:'',
    //nickname:'',
    confirmPwd:'',
    mail:'',
    code:''
})
const validateToken = ref('')
const registFormRef = ref<FormInstance>()
const invisibleHcaptcha = ref<VueHcaptcha|null>(null)
const loading = ref(false)
const sending = ref(false)
const isSend = ref(false)
const isCountdown = ref(false)
const countValue = ref<number>(0)
const mailRegex = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
   
  if (value === '') {
    callback(new Error('请再次确认密码'))
  } else if (value != model.value.password) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}
const validateMail = (rule:any,value:any,callback:any)=>{
    if (value === '') {
        callback(new Error('请输入你的邮箱账户'))
    }  else if (!mailRegex.test(value)) {
        callback(new Error("请输入正确的邮箱账户"))
    } else {
        callback()
    }
}
const rules = reactive<FormRules<RuleForm>>({
    // account: [
    //     { required: true, message: '请输入你的账号', trigger: 'blur' },
    //     { min: 6, message: '账号至少是6位', trigger: 'blur' },
    //     { max: 16, message: '账号最长只能是16位', trigger: 'blur' },
    // ],
    // nickname: [
    //     { required: true, message: '请输入你的昵称', trigger: 'blur' },
    //     { max: 8, message: '昵称最长只能是8位', trigger: 'blur' },
    // ],
    password: [
        { required: true, message: '请输入你的密码', trigger: 'blur' },
        { min: 6,max:20, message: '密码的长度应为6-20位', trigger: 'blur' },
    ],
    confirmPwd:[
        { validator: validateConfirmPassword, trigger: 'blur' }
    ],
    mail:[
        { validator: validateMail, trigger: 'blur' }
    ],
    code:[
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 6,max:6, message: '验证码应为6位', trigger: 'blur' },
    ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate(async (valid) => {
        loading.value=true
        if (valid) {
            if (invisibleHcaptcha.value && validateToken.value == '') {
                invisibleHcaptcha.value.execute()
                loading.value=false
                return
            }
            await registHandler()
        }
        loading.value=false
    })
}

const registHandler = async () =>{
    const response = await UserServices.RegistUserAsync(model.value.mail,model.value.password,model.value.code,validateToken.value)
    if(response.data.resultCode == ApiResult.SUCCESS){
        ElMessage.success({message:'注册成功，正在跳转'})
        setTimeout(() => {
            redicetToLogin()
        }, 1000);
        return
    }
    ElMessage.error({message:response.data.message})
    invisibleHcaptcha.value?.reset()
    validateToken.value=''
}
const verifyHandler = (token:string,ekey:string)=>{
    validateToken.value = token
}
const redicetToLogin = ()=>{
    location.href='/login'
}
const sendVerifyCode = async () => {
    if(!mailRegex.test(model.value.mail) || sending.value) return
    sending.value= true
    
    const response = await UserServices.SendRegistCodeAsync(model.value.mail)
    if(response.data.resultCode == ApiResult.SUCCESS){
        isCountdown.value = true
        countValue.value = Date.now() + 1000 * 60
        isSend.value = true
    }
    sending.value= false
   
}
</script>
<style>
.regist-box{
    background-image: url('../../assets/img/regist.png'),linear-gradient(0deg, #E3ECFF, #FFFFFF);
    background-size: 100% auto;
    background-repeat: no-repeat;
}
</style>