<template>
    <div class="auth-form-panel uni-login-panel">
        <div class="logo">
            <img alt="RunForge" src="/logo.svg" height="40">
            <span class="title">RunForge | 快捷登录</span>
        </div>

        <a-form size="large" :model="form" :rules="[]" class="form" @submit="handleSubmit">
            <div class="uniLoginButton">
                <div class="button" v-if="isTypeEnabled('qq')">
                    <a-tooltip content="QQ登录" mini>
                        <a-avatar :size="64" :style="{ backgroundColor: '#FE82A5' }"
                            @click="GetLoginUrl('qq')"><icon-qq /></a-avatar>
                    </a-tooltip>
                </div>
                <div class="button" v-if="isTypeEnabled('wx')">
                    <a-tooltip content="微信登录" mini>
                        <a-avatar :size="64" :style="{ backgroundColor: '#FE82A5' }"
                            @click="GetLoginUrl('wx')"><icon-wechat /></a-avatar>
                    </a-tooltip>
                </div>
            </div>
            <a-alert v-if="!optionsLoading && enabledTypes.length === 0" type="warning" class="disabled-tip">
                快捷登录暂未开启，请使用账号密码登录
            </a-alert>
            <div class="tip">未注册的第三方账号登录后将自动注册</div>
            <a-button type="text" class="forgetpass" @click="emit('changeMode', 'login')">账号密码登录</a-button>
        </a-form>
    </div>

    <div class="loading" v-if="loading">
        <div class="loadingTip">
            <icon-loading :size="32" />
            <div class="text">努力加载中</div>
        </div>
    </div>
</template>

<script setup>
import { getLoginUrl, getUniLoginOptions } from '@/api/login'
import { timeFix } from '@/utils/util'
import { useRoute, useRouter } from 'vue-router'
import { ref, onMounted } from 'vue'
import { Notification } from '@arco-design/web-vue'
import { useUserStore } from '@/store/modules/user'
import { isElectron } from '@/utils/electron'

const userStore = useUserStore()

const loading = ref(false)
const optionsLoading = ref(false)
const enabledTypes = ref(['qq', 'wx'])
const route = useRoute()
const router = useRouter()
const emit = defineEmits(['changeMode', 'changeLoading'])

const from = route.query.from

const isTypeEnabled = (type) => enabledTypes.value.includes(type)

const loadOptions = async () => {
    try {
        optionsLoading.value = true
        const res = await getUniLoginOptions()
        if (res?.code === 0 && Array.isArray(res.data?.enabledTypes))
            enabledTypes.value = res.data.enabledTypes
    } catch (error) {
        console.log(error)
    } finally {
        optionsLoading.value = false
    }
}

const GetLoginUrl = async (type) => {
    if (!isTypeEnabled(type))
        return requestFailed('该登录方式已关闭')

    try {
        changeLoading(true)
        const res = await getLoginUrl({ type })
        if (!res || res.code != 0)
            return requestFailed('获取登录链接失败！' + res?.msg ?? '')
        if (isElectron())
            window.electron.openNewWindow(res.data)
        else
            window.location.href = res.data
    } catch (error) {
        console.log(error)
        requestFailed('获取登录链接失败！')
    } finally {
        changeLoading(false)
    }
}

const UniLogin = async (type, code) => {
    try {
        changeLoading(true)
        const res = await userStore.uniLogin(type, code)
        loginSuccess(res)
    } catch (error) {
        requestFailed(error.message || '登录失败！请稍后再试')
    } finally {
        changeLoading(false)
    }
}

const BindSocial = async (type, code) => {
    try {
        changeLoading(true)
        const user = await userStore.getInfo()
        if (!user?.uuid || !user?.session)
            throw new Error('请先登录后再绑定第三方账号')

        await userStore.bindSocial(type, code)
        Notification.success({
            title: '绑定成功',
            content: `${type === 'qq' ? 'QQ' : '微信'}账号已绑定到当前账户`,
            duration: 2000
        })

        if (isElectron())
            window.electron.openOldWindow(from || '/user/setting')
        else
            router.push(from || '/user/setting')
    } catch (error) {
        requestFailed(error.message || '绑定失败！请稍后再试')
        router.push('/user/setting')
    } finally {
        changeLoading(false)
    }
}

const changeLoading = (value) => {
    loading.value = value
}

const loginSuccess = (res) => {
    Notification.success({
        title: `${timeFix()}，${res.username}`,
        content: '欢迎回来！',
        duration: 2000
    })
    if (isElectron())
        window.electron.openOldWindow(from || '/')
    else
        router.push(from || '/')
}

const requestFailed = (msg) => {
    Notification.error({
        title: '错误',
        content: msg || '请求出现错误，请稍后再试',
    })
}

onMounted(() => {
    loadOptions()
    if (route.query.type && route.query.code) {
        if (route.query.action === 'bind')
            BindSocial(route.query.type, route.query.code)
        else
            UniLogin(route.query.type, route.query.code)
    }
})

</script>

<style lang="less" scoped>
@import '@/styles/auth-marketing.less';

.loading {
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.2);
    z-index: 9999;
    border-radius: 10px;

    .loadingTip {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #FE82A5;

        .text {
            font-family: 'Alimama ShuHeiTi';
            font-size: 1.2em;
        }
    }
}

.uni-login-panel {
  position: relative;
}

.tip {
    color: #777;
    font-size: 0.9em;
    text-align: left;
    margin-bottom: 20px;
    margin-left: -8px;
}

.disabled-tip {
    margin-bottom: 16px;
    text-align: left;
}

.uniLoginButton {
    display: flex;
    gap: 40px;
    justify-content: center;
    height: 100px;

    .button {
        cursor: pointer;
    }
}

.forgetpass {
    width: 100px;
    margin-top: -10px;
    margin-left: -15px;
}
</style>
