<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="账号/邮箱" />
        </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="" v-if="needVerify">
            <div class="row full-width">
                <div class="col">
                    <vue-hcaptcha ref="invisibleHcaptcha" sitekey="46e00e53-ddb2-4e7b-9c51-621534c2f1f5" @verify="verifyHandler" 
                    ></vue-hcaptcha>
                </div>
            </div>
        </el-form-item>
        <el-form-item style="margin-bottom: 8px;">
            <el-button type="primary" class="full-width" @click="submitForm(loginFormRef)" :loading="loading">登录</el-button>
        </el-form-item>
        <div class="text-info text-small row flex-between">
            <div class="row items-center">
                <!-- <span>还没有账号？</span>
                <el-button link type="primary" @click="redicetToRegist">立即注册</el-button> -->
            </div>
            <el-button link type="primary" @click="redicetToForgot">忘记密码？</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
  password: string
}
const model = ref<{account:string,password:string,tid:string}>({
    account:'',
    password:'',
    tid:''
})
const rules = reactive<FormRules<RuleForm>>({
    account: [
        { required: true, message: '请输入你的账号/邮箱', trigger: 'blur' },
        { min: 6, message: '请输入正确的账号', trigger: 'blur' },
    ],
    password: [
        { 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 emit = defineEmits<{
  (event: 'submitForm'): void,
}>()

const redicetToRegist = ()=>{
    location.href='/regist'
}

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.setUserPasswordLoginAsync(model.value.account,model.value.password,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
        emit('submitForm', multipleUsers.value)
    }else{
        if(!needVerify.value) needVerify.value = result.verify
        if(invisibleHcaptcha.value && needVerify.value) invisibleHcaptcha.value.reset()
        ElMessage.error({message:'账号或密码错误'})
    }
}

const verifyHandler = (token:string,ekey:string)=>{
    validateToken.value = token
}
const verifyCheckHandler = async ()=>{
    const response = await UserServices.NeedVerifyStatusAsync()
    if(response.data.resultCode == ApiResult.SUCCESS){
        needVerify.value = response.data.data==1
    } else needVerify.value = true
}
verifyCheckHandler()
</script>