var layer = null,
    $ = null,
    IdCard = document.getElementById("IdCard"),
    tabIndex=0;

var login = {
    //登入方法
    LoginMethod: (bodyValue) => {
        var index = 0;
        if (tabIndex != 1) index = layer.load();

        fetch("/Login/Login", {
            method: "post",
            headers: new Headers({
                "Content-Type": "application/x-www-form-urlencoded"
            }),
            body: bodyValue
        }).then(function (res) {
            return res.json();
        }).then(function (data) {
            if (data.Code === 200) {
                layer.msg(data.Result.Account + " " + data.Result.Name, { icon: 6, shade: 0.4, time: 10000 });
                localStorage.setItem("Account", data.Result.Account);
                localStorage.setItem("Name", data.Result.Name);
                setTimeout(function () {
                    window.location.href = "/Home/Index";
                }, 2000);
            } else {
                if (layer != null) document.getElementById("loginMessage").innerHTML = data.Message;
            }
            layer.close(index);
        }).catch(function (error) {
            if (layer != null) document.getElementById("loginMessage").innerHTML = "登入失败";
        });
    },


    //注册事件
    initEvents: () => {
        //刷卡登入
        IdCard.addEventListener('input', debounce(handle, 500));
    }
}
var isChrome = window.navigator.userAgent.indexOf("Chrome") > -1;
if (!isChrome) {
    alert("推荐使用谷歌浏览器登录使用,以免产生浏览器不兼容出现的错误");
}
login.initEvents();

// 防抖
function debounce(fn, delay) {
    let timeout = null; 
    return function () {
        clearTimeout(timeout); 
        timeout = setTimeout(() => { 
            fn.apply(this, arguments);
        }, delay);
    };
}

function handle() {
    if (IdCard.value == "") return;
    var value = `username=''&password=''&webcam=&idcard=${IdCard.value}`;
    login.LoginMethod(value);
}

layui.config({ base: "/js/" }).use(["form", "layer", "element"], function () {
    //如果在iframe中,则跳转
    if (self !== top) top.location.replace("/Login/Index");
    layer = parent.layer === undefined ? layui.layer : parent.layer;
    $ = layui.jquery;

    var form = layui.form,   
        element = layui.element;

    element.on("tab(loginWebcam)", function (data) {
        tabIndex = data.index;
        if (data.index===1) {
            IdCard.focus();
        } else {
            document.getElementById("loginMessage").innerHTML = "";
        }
    });


    //登录按钮事件
    form.on("submit(login)", function (data) {
        debugger;
        data.field.password = data.field.password.encryptPwd()  ;
        data["file"] = "";
        $.ajax({
            url: "/Login/Login",
            type: "post",
            data: data.field,
            dataType: "json",
            success: function (data) {
                if (data.Code === 200) {
                    localStorage.setItem("Account", data.Result.Account);
                    localStorage.setItem("Name", data.Result.Name);
                    window.location.href = "/Home/Index";
                } else {
                    layer.msg(data.Message, { time: 4000 });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert("【服务器响应超时,请检查WiFi网络Url地址、服务器网关服务是否启动,反复出现请联系管理员!】", { icon: 2, shadeClose: true, title: "错误信息" });
            }
        });
        return false;
    });
});