function getSsoUrl() {
    var appId = "9aed0ecc-aed6-46bb-8754-2500198a3455";
    // var callback = encodeURIComponent("http://192.168.22.66:8003/static/ztt-oauth/callback.html");
    var callback = encodeURIComponent("https://192.168.22.66/static/ztt-oauth/callback.html");
    var state = String(Number(new Date()));
    var url = "https://ztt-sso.ztt.cn/oauth2/auth?response_type=code&scope=openid&client_id=" + appId + "&redirect_uri=" + callback + "&state=" + state;
    return url;
}

function parameter(name) {
    var value = urlQuery(name);
    if (!value) return "";
    value = value.replace(/\+/gm, " ");
    value = decodeURIComponent(value);
    return value;
}

function href(url, delay) {
    log("正在跳转 [ <a target=\"_top\" href=\"" + url + "\">" + url + "</a> ]", "info");
    switch (location.hostname) {
        case "127.0.0.1":
        case "localhost":
            return;
    }
    switch (location.port) {
        case "7003":
        case "9003":
            return;
    }

    if (typeof delay != "number") delay = 500;
    setTimeout(() => {
        window.location.href = url;
    }, delay);
}

function login() {
    log("正在跳转到 ZTT SSO 认证页面。");
    href(getSsoUrl());
}

function callback() {
    var jwtvalue = parameter("jwt");
    var code = parameter("code");
    var error = parameter("error");
    var error_description = parameter("error_description");
    var error_hint = parameter("error_hint");
    var state = parameter("state");

    if (jwtvalue) {
        jwt(jwtvalue);
        return;
    }

    if (code) {
        log("code: " + code, "info");
        log("正在连接到 ZTT SSO 获取用户信息。");
        ajaxGet("/api/login/ztt-login?code=" + code, (r) => {
            if (r.status == 1 && r.data) {
                var token = r.data.token;
                var user = r.data.user;
                var nick = r.data.nick
                if (token) {
                    if (user) log("username: " + String(user));
                    if (nick) log("nickname: " + String(nick));
                    log("认证成功。", "ok");
                    jwt(token);
                } else {
                    log("认证失败，服务器没有返回用户令牌。", "error");
                    log("即将跳转到 MES 首页。");
                    href(origin + "/", 5000);
                }
            } else {
                log("认证失败：" + String(r.msg), "error");
                log("即将跳转到 MES 首页。");
                href(origin + "/", 5000);
            }
        }, (e) => {
            log("连接服务器失败。", "error");
            log("即将跳转到 MES 首页。");
            href(origin + "/", 5000);
        });
        return;
    }

    if (error) {
        log("error: " + error, "error");
        log("error_description: " + error_description, "error");
        log("error_hint: " + error_hint, "error");
    }
    // http://192.168.22.66:8003/static/ztt-oauth/callback.html
    // ?error=invalid_state
    // &error_description=The+state+is+missing+or+has+less+than+8+characters+and+is+therefore+considered+too+weak
    // &error_hint=Request+parameter+%22state%22+must+be+at+least+be+8+characters+long+to+ensure+sufficient+entropy.
    // &state=145815
}

function jwt(value) {
    sessionStorage.removeItem("access-token");

    var origin = "http:" + "//" + window.location.host;
    if (!value) value = parameter("jwt");
    if (!value) value = parameter("value");
    if (!value) {
        log("未传入 JWT 参数，即将跳转到 MES 首页。", "error");
        href(origin + "/");
        return;
    }

    log("jwt: " + value);
    if (window.location.protocol == "http:") {
        function mesAuthInfo() {
            log("正在连接到 MES 进行认证。");
            ajaxGet("/api/login/auth-info", (r) => {
                if (r.status == 1) {
                    var info = r.data;
                    if (info.menuPath) sessionStorage.setItem("auth-menu-path", JSON.stringify(info.menuPath));
                    if (info.btnrole) sessionStorage.setItem("auth-btnrole", info.btnrole);
                    if (info.nick) sessionStorage.setItem("auth-nickname", info.nick);
                    if (info.username) sessionStorage.setItem("auth-username", info.username);
                    if (info.profile) sessionStorage.setItem("profile", info.profile);
                    log("认证成功。", "ok");
                } else {
                    log("认证失败：" + String(r.msg), "error");
                }
                href(origin + "/");
            }, (e) => {
                log("连接服务器失败：" + String(e.message), "error");
                log("5 秒后重试。");
                setTimeout(mesAuthInfo, 5000);
            });
        }

        sessionStorage.setItem("access-token", value);
        sessionStorage.removeItem("auth-username");
        sessionStorage.removeItem("auth-nickname");
        mesAuthInfo();
        return;
    }
    if (window.location.protocol == "https:") {
        log("当前页面属于 HTTPS 站点，即将跳转到 MES HTTP 站点。");
        href(origin + window.location.pathname + "?jwt=" + value);
        return;
    }
    log("不支持的协议: " + window.location.protocol, "error");
}

function afterLoad() {
    var pathname = window.location.pathname;
    var split = pathname.split("/");
    var filename = split[split.length - 1];
    switch (filename) {
        case "login.html":
            login();
            break;
        case "callback.html":
            callback();
            break;
        case "jwt.html":
            jwt();
            break;
    }
}

window.addEventListener("load", function () {
    document.body.style.margin = "0px";
    window.logLoad = afterLoad;

    var iframe = document.createElement("iframe");
    iframe.src = "/static/frame-log/";
    iframe.style.position = "fixed";
    iframe.style.width = "100%";
    iframe.style.height = "100%";
    iframe.style.borderStyle = "none";
    this.document.body.appendChild(iframe);
});
