
var locked = false;
var autologin = false;

function lock(value) {
    locked = value ? true : false;
    if (locked) {
        document.getElementById("submit").setAttribute("disabled", "disabled");
        document.getElementById("username").setAttribute("disabled", "disabled");
        document.getElementById("password").setAttribute("disabled", "disabled");
    } else {
        document.getElementById("submit").removeAttribute("disabled");
        document.getElementById("username").removeAttribute("disabled");
        document.getElementById("password").removeAttribute("disabled");
    }
}

function switchAutoLogin() {
    autologin = !autologin;
    if (autologin) {
        document.getElementById("autologin").setAttribute("enabled", "enabled");
    } else {
        document.getElementById("autologin").removeAttribute("enabled");
    }
}

function onKeyDown(event) {
    if (event.keyCode == 13) {
        switch (event.target.id) {
            case "username":
                document.getElementById("password").focus();
                break;
            case "password":
                submit();
                break;
        }
    }
}

function submit() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;

    if (!username) {
        toast("未输入用户名");
        document.getElementById("username").focus();
        return;
    }

    if (!password) {
        toast("未输入密码");
        document.getElementById("password").focus();
        return;
    }

    if (username && password) {
        showLoading(true);
        lock(true);
        api.post("/api/login", {
            username: username,
            password: password,
            autologin: autologin
        }, (r) => {
            showLoading(false);
            toast("登录成功");
            setTimeout(() => {
                window.close();
            }, 1000);
        }, (e) => {
            showLoading(false);
            lock(false);
            toast(e.message, 5000);
        });
    }
}

function checkOnline() {
    showLoading(true);
    api.post("/api/online", null, (r) => {
        showLoading(false);
        if (r.data.server) {
            document.getElementById("form-login").style.display = "none";
            document.getElementById("form-online").style.display = "block";
        } else {
            document.getElementById("form-login").style.display = "block";
            document.getElementById("form-online").style.display = "none";
        }
    }, (e) => {
        showLoading(false);
    });
}

window.onload = function () {
    document.getElementById("username").onkeydown = onKeyDown;
    document.getElementById("password").onkeydown = onKeyDown;
    document.getElementById("autologin").onclick = switchAutoLogin;
    document.getElementById("submit").onclick = submit;
    document.getElementById("close").onclick = function () { window.close(); };

    checkOnline();
};