<script setup>
import {ref,computed,watch} from 'vue'
import { showToast } from 'vant';
import {_apiLogin} from '@/api/user'
import {useLogin} from './hooks/useLogin'
const props = defineProps({
    activeModel:{//当前选择的登陆模式
        type:String,
        default:'ordinaryModel'
    }
})
const { picSrc,picId,getPicCode,
        timer,codeStr,codeCountDown,countDown,getCode
      } = useLogin()
watch(()=>props.activeModel,()=>{
    if(props.activeModel==='emailModel'){
        if(!timer){
            getPicCode()
            codeStr.value = '获取验证码'
        }
    }
})

//邮箱
let email = ref('')
//邮箱的图形验证码
let emailPicCode = ref('')
//邮件验证码
let emailCode = ref('')
const isEmailCountDown = computed(()=>{
    return codeCountDown.value<60&&codeCountDown.value>0
})
let isGetNewCode = ref(false)

const emailPattern = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
function checkForm(){
    if(isEmailCountDown.value) return 
    //是否是重新获取验证码
    if(codeStr.value==='重新获取'&&!isGetNewCode.value){
        //清空图形验证码输入框，引导用户重新输入
        showToast("重新获取需再次输入图形验证码")
        getPicCode()
        emailPicCode.value = ''
        isGetNewCode.value = true
        return
    }
    //检查邮箱和图形验证码是否正确
    if(!emailPicCode.value.length){
        showToast('请输入图形验证码')
        return
    }
    if(!email.value.length){
        showToast('请输入邮箱')
        return 
    }
    if(!emailPattern.test(email.value)){
        showToast('请输入正确的邮箱')
        return 
    }

    getCode({
        email:email.value,
        picCode:emailPicCode.value
    },'email',1)
    isGetNewCode.value = false
}
</script>

<template>
    <van-field
        class="form-input-box form-mobile-box"
        v-model="email"
        name="email"
        placeholder="请输入邮箱"
        :rules="[
            { required: true, message: '请输入邮箱' },
            {validator:(val)=>emailPattern.test(val),message:'请输入正确的邮箱'}
        ]"
    />
    <van-field
        class="form-input-box form-mobile-box"
        v-model="emailPicCode"
        name="emailPicCode"
        placeholder="请输入图形验证码"
        :rules="[{ required: true, message: '请输入图形验证码' }]"
    >
        <template #button>
            <div class="pic-filed" @click="getPicCode">
                <img :src="picSrc" />
            </div>
        </template>
    </van-field>
    <van-field
        class="form-input-box form-mobile-box"
        v-model="emailCode"
        name="emailCode"
        placeholder="请输入邮件验证码"
        :rules="[{ required: true, message: '请输入邮件验证码' }]"
    >
        <template #button>
            <span class="btn-text" :class="{'disabled':isEmailCountDown}"
                @click="checkForm"
            >{{codeStr}}</span>
        </template>
    </van-field>
</template>

<style scoped lang="scss">
@import "./style/common.scss";
</style>
