<template>
    <el-main></el-main>
</template>
<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
//登录请求接口
import { loginApi } from "@/api/modules/login";
//组织
import { getOrgsApi } from "@/api/modules/global";
//上线通知
import { useUcOnline } from "@/hooks/useUcOnline";
//下线通知
import { useUcOffline } from "@/hooks/useUcOffline";
//用户信息存储
import { useUserStore } from "@/stores/modules/user";

const userStore = useUserStore();
// 路由
const $route = useRoute();
const $router = useRouter();

//组织接口
const getOrgs = async () => {
    const relust = await getOrgsApi();
    if (relust.status === 200) {
        const { data } = relust;
        userStore.setOrgIdArr(data);
    }
};
//预请求(利用login页面跳转到index页面的这段时间可以做一些公共接口的提前请求)

//拼接token
const tokenSplicing = (data: any) => {
    // 组装token
    let newUserToken = data.tokenInfo.tokenType + " " + data.tokenInfo.token;
    let RefreshToken = data.tokenInfo.tokenType + " " + data.tokenInfo.refreshToken;
    let phpToken = data.tokenInfo.tokenType + " " + data.tokenInfo.phpToken;
    return {
        newUserToken,
        RefreshToken,
        phpToken
    };
};
// 设置用户数据
const setUserData = (data: any) => {
    const tokens = tokenSplicing(data);
    const { newUserToken, RefreshToken, phpToken } = tokens;
    // 设置token
    userStore.setToken(newUserToken);
    userStore.setRefreshToken(RefreshToken);
    userStore.setPhpToken(phpToken);
    // 设置用户信息
    userStore.setUserInfo(data.userInfo);
    // 设置组织id
    userStore.setOrgId(data.userInfo.orgId);
    //上线通知
    useUcOnline(phpToken, RefreshToken);
    //获取组织
    getOrgs();
    //跳转到首页
    setTimeout(() => {
        $router.push({ path: "/" });
    }, 500);
};

// 登录
const loginHttp = async (code: any) => {
    const result: Record<string, any> = await loginApi({ code: code });
    if (result.status === 200) {
        setUserData(result.data);
    } else {
        console.log("12323232");
        //  useUcOffline();
    }
};

// 登录前的判断
const login = () => {
    const { code } = $route.query;
    // 没有code直接跳转到登录页
    if (!code) {
        useUcOffline();
        return;
    }
    // 有code就登录请求
    loginHttp(code);
};
login();
</script>
<style lang="scss">
.el-main {
    height: 100vh;
}
</style>
