<template>
    <el-form ref="loginFormRef" :model="model" :rules="rules" label-width="0px" size="large" class="full-width q-mt-lg"> 
        <el-form-item label="" prop="account">
            <el-input v-model="model.account" placeholder="手机号">
                <template #suffix>
                    <el-button link :disabled="!phoneRegex.test(model.account)" :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="验证码" class="q-mt-lg"/>
        </el-form-item>
        <el-form-item label="">
            <div class="row q-mt-lg full-width">
                <div class="col">
                    <vue-hcaptcha ref="invisibleHcaptcha" sitekey="46e00e53-ddb2-4e7b-9c51-621534c2f1f5" @verify="verifyHandler" v-if="needVerify"></vue-hcaptcha>
                </div>
                <el-button link type="primary" > &nbsp; </el-button>
            </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" class="full-width q-mb-lg" @click="submitForm(loginFormRef)" :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="passwordLogin">立即登录</el-button>
        </div> -->
    </el-form>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import VueHcaptcha from "@hcaptcha/vue3-hcaptcha";
import { ApiResult } from '@/configs/axios';
import UserServices from '@/services/UserService';
import { useUserStore } from '@/store/user';

interface RuleForm {
  account: string
  code: string
}
const model = ref<{account:string,code:string,tid:string}>({
    account:'',
    code:'',
    tid:''
})
const rules = reactive<FormRules<RuleForm>>({
    account: [
        { required: true, message: '请输入你的手机号', trigger: 'blur' },
        { min: 11, message: '请输入正确的手机号', trigger: 'blur' },
    ],
    code: [
        { required: true, message: '请输入你的验证码', trigger: 'blur' },
        { min: 6,max:20, message: '请输入正确的验证码', trigger: 'blur' },
    ]
})

const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const user = useUserStore()
const multipleUsers = ref<any[]>([])
const inviteInfo = ref<any>()
const needVerify = ref(false)
const validateToken = ref('')
const invisibleHcaptcha = ref()
if(localStorage.getItem("invite")){
    inviteInfo.value = JSON.parse(localStorage.getItem("invite")??'{}')
}

const sending = ref(false)
const isCountdown = ref(false)
const countValue = ref<number>(0)
const phoneRegex = /^[1]([3-9])[0-9]{9}$/

const emit = defineEmits<{
    (event: 'passwordLogin'): void,
}>()

const passwordLogin = () =>{
    emit('passwordLogin')
}

const redicetToForgot = ()=>{
    location.href='/forgot'
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl || loading.value || (needVerify.value && validateToken.value=='')) return
  loading.value=true
  await formEl.validate(async (valid) => {
    if (valid) {
      await userLoginHandler()
    }
    loading.value=false
  })
  
}
const userLoginHandler = async ()=>{
    const result = await user.setUserVerifyLoginAsync(model.value.account,model.value.code,validateToken.value,model.value.tid)
    if(result.status=='SUCCESS'){
        ElMessage.success({message:'登录成功'})
        if(inviteInfo.value){
            localStorage.removeItem('invite')
            localStorage.setItem('sure_invite',JSON.stringify(inviteInfo.value))
        }
        location.href='/space';
    }else if(result.status=='CHOSEN' && Array.isArray(result.data)){
        multipleUsers.value = result.data
    }else{
        if(!needVerify.value) needVerify.value = result.verify
        if(invisibleHcaptcha.value && needVerify.value) invisibleHcaptcha.value.reset()
        ElMessage.error({message:'手机号或验证码错误'})
    }
}

const sendVerifyCode = async () => {
    if(!phoneRegex.test(model.value.mail) || sending.value) return
    sending.value= true
    
    const response = await UserServices.SendRegistCodeAsync(model.value.mail)
    if(response.data.resultCode == ApiResult.SUCCESS){
        ElMessage.success({message:'验证码已发送，请前往邮箱查看'})
        isCountdown.value = true
        countValue.value = Date.now() + 1000 * 60
        isSend.value = true
    } else {
        ElMessage.error({message:response.data.message})
    }
    sending.value= false
   
}

const verifyHandler = (token:string,ekey:string)=>{
    validateToken.value = token
}
</script>