import wstVaildate from "./wst"
import {ElMessage, ElLoading } from "element-plus";
import { getLogin, postLogin } from "./api"

export const SINGLE_LOGIN_KEY = "mcj_platform_single_login"
const OPTION_LOADING = {
    // 声明一个loading对象
    lock: true, // 是否锁屏
    text: "正在检查key，请稍后...", // 加载动画的文字
    spinner: "el-icon-loading", // 引入的loading图标
    background: "rgba(0, 0, 0, 0.5)", // 背景颜色
    target: ".sub-main", // 需要遮罩的区域
    body: true,
    customClass: "mask", // 遮罩层新增类名
}

// 单点登录校验
const singleLogin = async () => {
    return new Promise(async (resolve, reject) => {
        const loading = ElLoading.service(OPTION_LOADING);
        try {
            getLogin().then(async (res) => {
                const { data } = res || {}
                if (!data) {
                    loading.close();
                    ElMessage.error("身份校验失败");
                    return resolve(true)
                }

                const { result = false, params = {} } = await wstVaildate(data);
                const { challenge, ticket } = params;

                if (result) {
                    postLogin(challenge, ticket).then((res) => {
                        resolve(res)
                    }).catch(() => {
                        reject()
                    })
                }
            }).catch(() => {
                reject()
            })

        } catch (error) {
            console.log("error:", error);

            reject()
        } finally {
            loading.close();
        }
    })
}

export default singleLogin