<template>
    <div class="login-box q-pa-xl row">
        <img src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1713237911000_1.png" class="logo"  />
        <div class="col column">
            <div class="col column flex-center items-center">
                <div class="wel">
                    <img src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1711705161000_818.png" />
                    <h1 style="font-size: 32px; text-dark" class="q-my-lg">快速，智能，美观</h1>
                    <div class="text-info text-small" style="font-size: 13px;">这里有上百种行程设计模板供你选择</div>
                    <div class="text-info text-small q-my-md" style="font-size: 13px;">我们为你提供了大量的插件，支持快速实现自己想要的行程</div>
                    <div class="text-info text-small" style="font-size: 13px;">AI助手的辅助让你报价与设计快人一步</div>
                </div>
            </div>
            <div class="text-center text-small text-info full-width">@2012-2024 成都微途科技有限公司 版权所有 <a class="q-pl-md" href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank"
        style="color: rgb(155, 153, 188);text-decoration: none;">蜀ICP备13024891号-9</a></div>
        </div>
        <div class="login-form q-pa-xl column flex-center items-center" style="padding: 30px 100px;" v-if="token==''">
            <div class="q-mb-xl  full-width" v-if="inviteInfo">
                <div class="q-mt-lg no-select row items-center q-pa-lg rounded" style="background-color:  rgb(240, 246, 255);">
                    <el-avatar :size="44" :src="inviteInfo.logo" shape="square"></el-avatar>
                    <div class="q-ml-md col flex-overflow">
                        <div class="text-dark text-weight-bold text-ellipsis"> {{ inviteInfo.nickname }}邀请你加入{{ inviteInfo.company }}{{ inviteInfo.nickname }}邀请你加入{{ inviteInfo.company }}</div>
                        <div class="text-grey-8 text-small q-mt-sm">{{ inviteInfo.expire }}后失效</div>
                    </div>
                    <el-button type="info" class="ppt-button q-ml-md" @click="cancelInviteHandler">取消</el-button>
                </div>
            </div>
            <div style="font-size: 36px; " class="text-dark">登录</div>
            <div class="text-info text-small">你的创作空间</div>
            <template v-if="!multipleUsers || multipleUsers.length==0">
                <!-- <div class="q-py-xl row items-center full-width">
                    <div class="login-type row items-center col">
                        <img src="../../assets/img/wechat.png" alt="">
                        <span class="q-ml-md">使用微信扫码登录</span>
                    </div>
                    <div class="login-type row items-center col q-ml-md">
                        <img src="../../assets/img/phone.png" alt="">
                        <span class="q-ml-md">使用短信验证登录</span>
                    </div>
                </div> -->
                <el-divider> <span class="text-info">使用邮箱或者账号登录</span> </el-divider>
                <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  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" @click="redicetToForgot">忘记密码？</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="redicetToRegist">立即注册</el-button>
                    </div>
                </el-form>
            </template>
            <template v-if="multipleUsers && multipleUsers.length>0">
                <el-divider> <span class="text-info">选择你需要登录的组织</span> </el-divider>
                <div v-for="x in multipleUsers" :key="x.tid" @click="()=>model.tid=x.tid" class="light-shadow q-pa-md row items-center full-width rounded q-mt-xl cursor-pointer q-mb-md transparent-borders" :class="{'primary-borders-thin':model.tid==x.tid}">
                    <el-avatar :size="30" :src="x.logo"></el-avatar>
                    <div class="q-ml-lg">
                        <div class="text-weight-bold" style="font-size: 20px;">{{ x.nickname }}</div>
                        <div class="text-info text-small">{{ x.tenantname }}</div>
                    </div>
                </div>
                <el-button type="primary" size="large" class="full-width q-mt-lg" @click="loginByCompany" :loading="loading" :disabled="model.tid==''">登录</el-button>
                <div class="text-center q-mt-lg">
                    <el-button link type="primary" class="q-mb-lg" @click="clearCompanyChoosenHandler">重新登录</el-button>
                </div>
            </template>
        </div>
        <div class="login-form q-pa-xl column flex-center items-center" style="padding: 30px 100px;" v-else>
            <div style="font-size: 36px; " class="text-dark">已登录</div>
            <div class="text-info text-small">你的创作空间</div>
            <div class="q-py-xl flex-center items-center column">
                <el-avatar :size="100" shape="square" class="bg-transparent"  :src="userInfo.photo"></el-avatar>
                <div class="row items-center flex-center q-mt-md ">
                    <div class="text-weight-bold" style="font-size: 18px;">{{ userInfo.nickname }}</div>
                    <el-tag type="primary" class="q-ml-md" v-if="userInfo.it">企业专业版</el-tag>
                    <el-tag type="warning" class="q-ml-md" v-else-if="userInfo.iv">个人专业版</el-tag>
                    <el-tag type="info" class="q-ml-md" v-else>个人免费版</el-tag>
                </div>
                <div class="q-mt-md text-small text-info">{{ userInfo.company }}</div>
                <div class="q-mt-lg row items-center">
                    <el-button @click="loginOutHandler">退出登录</el-button>
                    <el-button class="q-ml-md" type="primary" @click="forwardWorkspaceHandler">进入工作台</el-button>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ApiResult } from '@/configs/axios';
import UserServices from '@/services/UserService';
import { useUserStore } from '@/store/user';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { reactive, ref } from 'vue';
import VueHcaptcha from "@hcaptcha/vue3-hcaptcha";

interface RuleForm {
  account: string
  password: string
}
const model = ref<{account:string,password:string,tid:string}>({
    account:'',
    password:'',
    tid:''
})
const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const user = useUserStore()
const token = user.getUserToken??''
const userInfo = user.getUser
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 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 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 cancelInviteHandler = ()=>{
    inviteInfo.value = null
    localStorage.removeItem('invite')
}
const loginByCompany = async ()=>{
    if(model.value.tid=='') ElMessage.error({message:'请选择需要登录的组织'})
    else {
        loading.value=true
        validateToken.value=''
        await userLoginHandler()
        loading.value=false
    }
}
const verifyHandler = (token:string,ekey:string)=>{
    validateToken.value = token
}
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
    }else{
        if(!needVerify.value) needVerify.value = result.verify
        if(invisibleHcaptcha.value && needVerify.value) invisibleHcaptcha.value.reset()
        ElMessage.error({message:'账号或密码错误'})
    }
}

const forwardWorkspaceHandler = ()=>{
    location.href='/space';
}
const redicetToRegist = ()=>{
    location.href='/regist'
}
const redicetToForgot = ()=>{
    location.href='/forgot'
}
const clearCompanyChoosenHandler = ()=>{
    multipleUsers.value=[]
    model.value.tid=''
}

const loginOutHandler = ()=>{
    user.setUserLoginOut()
}
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>
<style>
.login-box{
    background-color: #f8f7fc;
    background-image: url('https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1711704450000_818.jpeg');
    background-position: center;
    background-attachment: fixed;
    background-size: cover;
    width: 100vw;
    height: 100vh;
    position: relative;
}
.login-box .logo{
    height: 30px;
    width: auto;
    top: 80px;
    left: 80px;
    position: absolute;
    z-index: 2;
}
.login-box .foot-box{
    position: absolute;
    bottom: 30px;
}
.login-box .login-form{
    width:600px;
    background-color: #FFF;
    border-radius: 15px;
}
.login-box .wel{
    text-align: center;
}
.login-box .wel img{
    width: 300px;
    height: auto;
}
.login-box .login-type{
    border:1px solid #dbdfe9;
    padding:10px 20px;
    border-radius: 6px;
    text-align: center;
    cursor: pointer;
    font-size: 14px;
}
.login-box .login-type:hover{
    background-color: #f8f7fc;
    color:var(--el-color-primary);
}
.login-box .login-type img{
    width:16px;
}

</style>