var $, tab, sysDic = { data: null, method: null };
var IdCard = document.getElementById("IdCard"),
    canvas = document.createElement("canvas"),
    btnTakeSnapshot = document.getElementById("btnTakeSnapshot"),
    isSendFlag = false,
    tabIndex = 0,
    WebcamObj = null;
var timeout = null;
Date.prototype.format = function (format) {
    var o =
    {
        "M+": this.getMonth() + 1,                   //month
        "d+": this.getDate(),                        //day
        "h+": this.getHours(),                       //hour
        "m+": this.getMinutes(),                     //minute
        "s+": this.getSeconds(),                     //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds()                  //millisecond
    }
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}

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

function Cancellation() {
    layer.confirm('确认要注销吗?', {
        btn: ['确定', '取消']//按钮
    }, function (index) {
        window.sessionStorage.removeItem("menu");
        menu = [];
        window.sessionStorage.removeItem("curmenu");
        window.location = "/Login/Logout";
    }, function (index) {
        layer.close(index);
    });
}

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

layui.config({
    base: "/js/"
}).use(['bodyTab', 'form', 'element', 'layer', 'jquery'], function () {
    var form = layui.form,
        layer = layui.layer,
        element = layui.element;
    $ = layui.jquery;
    //【openTabNum】最大可打开窗口数量
    tab = layui.bodyTab({ openTabNum: "50", url: "/base/UserSession/GetModulesTree" });

    function getSysDic() {
        $.ajax({
            url: "/base/SysDictData/GetSysDictList",
            type: "post",
            dataType: "json",
            async: false,
            success: function (json) {
                if (json.Code === 200) {
                    sysDic.data = json.Result;
                } else {
                    layer.alert("获取字典数据错误", { icon: 2, shadeClose: true, title: "错误提示" });
                }
            }
        });
    }

    setTimeout(() => { getSysDic(); }, 2500);

    //其他页面获取  window.top.sysDic.method();
    sysDic.method = getSysDic;

    $("#Name").html(localStorage.getItem("Account"));
    $("#loginInfo").html("<i class= 'layui-icon'>&#xe66f;</i>&nbsp;" + localStorage.getItem("Name"));
    $("#loginTime").html("<i class= 'layui-icon'>&#xe60e;</i>&nbsp;" + new Date().format("yyyy-MM-dd"));

    //退出
    $(".signOut").click(function () {

    });

    //隐藏左侧导航
    $(".hideMenu").click(function () {
        $(".layui-layout-admin").toggleClass("showMenu");
        //渲染顶部窗口
        tab.tabMove();
    });

    //渲染左侧菜单
    tab.render();

    //锁屏
    function lockPage() {
        layer.open({
            title: false,
            type: 1,
            content: '	<div class="admin-header-lock" id="lock-box">' +
                '<div class="admin-header-lock-img"><img src="/images/lock.png"/></div>' +
                '<div class="admin-header-lock-name" id="lockUserName">System</div>' +
                '<div class="input_btn">' +
                '<input type="password" class="admin-header-lock-input layui-input" autocomplete="off" placeholder="请输入密码解锁.." name="lockPwd" id="lockPwd" />' +
                '<button class="layui-btn" id="unlock">解锁</button>' +
                '</div>' +
                '</div>',
            closeBtn: 0,
            shade: 0.9
        }),
            $(".admin-header-lock-input").focus();
        if ($("#usernametop").html() != "") {
            $("#lockUserName").html($("#usernametop").html());
        }
    }
    $(".lockcms").on("click", function () {
        window.sessionStorage.setItem("lockcms", true);
        lockPage();
    });

    // 判断是否显示锁屏
    if (window.sessionStorage.getItem("lockcms") == "true") {
        lockPage();
    }
    // 解锁
    $("body").on("click", "#unlock", function () {
        if ($(this).siblings(".admin-header-lock-input").val() == '') {
            layer.alert("请输入解锁密码!", { icon: 2, shadeClose: true, title: "错误信息" });
            $(this).siblings(".admin-header-lock-input").focus();
        } else {

            $.post("/Login/Login"
                , {
                    username: $("#lockUserName").html(),
                    password: $(this).siblings(".admin-header-lock-input").val(),
                }
                , function (data) {
                    var dataJson = JSON.parse(data);
                    if (dataJson.Code == 200) {
                        window.sessionStorage.setItem("lockcms", false);
                        $(this).siblings(".admin-header-lock-input").val('');
                        layer.closeAll("page");
                    } else {
                        layer.alert("密码错误,请重新输入!", { icon: 2, shadeClose: true, title: "错误信息" });
                        $(this).siblings(".admin-header-lock-input").val('').focus();
                    }
                });
        }
    });

    //手机设备的简单适配
    var treeMobile = $('.site-tree-mobile'),
        shadeMobile = $('.site-mobile-shade');

    treeMobile.on('click', function () {
        $('body').addClass('site-mobile');
    });

    shadeMobile.on('click', function () {
        $('body').removeClass('site-mobile');
    });

    // 添加新窗口
    $("body").on("click", ".layui-nav .layui-nav-item a", function () {
        var thisInfo = $(this),
            url = thisInfo.attr("data-url");
        //默认加上缓存的动态参数
        if (url != null && url.indexOf("sysWhere") > -1) {
            Object.keys(localStorage).forEach(x => {
                if (x.indexOf("sysWhere") > -1) {
                    url += `${url}&${x}=${localStorage.getItem(x)}`
                }
            })
            thisInfo.attr("data-url", url)
            url = thisInfo.attr("data-url");
        }
        //如果不存在子级 _x
        if (thisInfo.siblings().length == 0 && url != undefined) {
            if (url && url.indexOf("fullScreen") > -1) {
                window.open(url, url);
            } else {
                tab.tabAdd($(this));
            }
            $('body').removeClass('site-mobile');  //移动端点击菜单关闭菜单层
        }
        thisInfo.parent("li").siblings().removeClass("layui-nav-itemed");
    });

    //刷新当前
    $(".refresh").on("click", function () {
        $(".clildFrame .layui-tab-item.layui-show").find("iframe")[0].contentWindow.location.reload(true);
    });

    //关闭其他
    $(".closePageOther").on("click", function () {
        if ($("#top_tabs li").length > 2 && $("#top_tabs li.layui-this cite").text() != "首页") {
            var menu = JSON.parse(window.sessionStorage.getItem("menu"));
            $("#top_tabs li").each(function () {
                if ($(this).attr("lay-id") != '' && !$(this).hasClass("layui-this")) {
                    element.tabDelete("bodyTab", $(this).attr("lay-id")).init();
                    //此处将当前窗口重新获取放入session,避免一个个删除来回循环造成的不必要工作量
                    for (var i = 0; i < menu.length; i++) {
                        if ($("#top_tabs li.layui-this cite").text() == menu[i].title) {
                            menu.splice(0, menu.length, menu[i]);
                            window.sessionStorage.setItem("menu", JSON.stringify(menu));
                        }
                    }
                }
            })
        } else if ($("#top_tabs li.layui-this cite").text() == "首页" && $("#top_tabs li").length > 1) {
            $("#top_tabs li").each(function () {
                if ($(this).attr("lay-id") != '' && !$(this).hasClass("layui-this")) {
                    element.tabDelete("bodyTab", $(this).attr("lay-id")).init();
                    window.sessionStorage.removeItem("menu");
                    menu = [];
                    window.sessionStorage.removeItem("curmenu");
                }
            })
        } else {
            layer.alert("没有可以关闭的窗口了@_@", { icon: 2, shadeClose: true, title: "错误信息" });
        }
        //渲染顶部窗口
        tab.tabMove();
    })

    //关闭全部
    $(".closePageAll").on("click", function () {
        if ($("#top_tabs li").length > 1) {
            $("#top_tabs li").each(function () {
                if ($(this).attr("lay-id") != '') {
                    element.tabDelete("bodyTab", $(this).attr("lay-id")).init();
                    window.sessionStorage.removeItem("menu");
                    menu = [];
                    window.sessionStorage.removeItem("curmenu");
                }
            })
        } else {
            layer.alert("没有可以关闭的窗口了@_@", { icon: 2, shadeClose: true, title: "错误信息" });
        }
        //渲染顶部窗口
        tab.tabMove();
    });

    //修改密码
    $(".changepwd").on("click", function () {
        layer.open({
            title: "修改密码",
            shift: 2,
            type: 2,
            content: '/base/SysUser/ChangePassword',
            area: ['450px', '280px'], //宽高
            shade: 0.9
        });
    });

    $("#inputSearch").on('input', function (e) {
        var strings = e.delegateTarget.value;
        if (strings.replace(/(^s*)|(s*$)/g, "").length > 0) {
            tab.renderMenu({ value: strings });
        } else {
            tab.renderMenu({ value: "" });
        }
    });

    $("#inputSearch").keypress(function (e) {
        if (e.which == 13 && $("#inputSearch").val() != "") {
            tab.selectedMenu();
        }
    });

    $(document).bind("keydown", function (e) {
        //禁用页面F5刷新
        if (e.which == 116) {
            e.preventDefault(); //Skip default behavior of the enter key
        }
    });

    element.on("tab(loginWebcam)", function (data) {
        tabIndex = data.index;
        if (data.index === 0) {
            login.initWebCam();
        } else if (data.index === 1) {
            IdCard.focus();
            login.cancalCloseVideo();
        }
    });
});

var qp = {
    //全屏 类
    fullScreen: function () {
        var isFullScreen = false;
        var requestFullScreen = function () { //全屏
            var de = document.documentElement;
            if (de.requestFullscreen) {
                de.requestFullscreen();
            } else if (de.mozRequestFullScreen) {
                de.mozRequestFullScreen();
            } else if (de.webkitRequestFullScreen) {
                de.webkitRequestFullScreen();
            } else {
                alert("该浏览器不支持全屏");
            }
        };

        //退出全屏 判断浏览器种类
        var exitFull = function () {
            // 判断各种浏览器,找到正确的方法
            var exitMethod = document.exitFullscreen || //W3C
                document.mozCancelFullScreen || //Chrome等
                document.webkitExitFullscreen || //FireFox
                document.webkitExitFullscreen; //IE11
            if (exitMethod) {
                exitMethod.call(document);
            } else if (typeof window.ActiveXObject !== "undefined") { //for Internet Explorer
                var wscript = new ActiveXObject("WScript.Shell");
                wscript.SendKeys("{F11}");
            }
        };

        return {
            handleFullScreen: function ($this) {
                $this = $($this);
                if (isFullScreen) {
                    exitFull();
                    isFullScreen = false;
                    $this.find("i").removeClass("wb-contract");
                    $this.find("i").addClass("wb-expand");
                } else {
                    requestFullScreen();
                    isFullScreen = true;
                    $this.find("i").removeClass("wb-expand");
                    $this.find("i").addClass("wb-contract");
                }
            },
        };
    }()
}


//信息提示
let LogTipsIndex = 0;
var infoTips = {
    LogTips: function () {
        $.ajax({
            url: "/Home/LogTips",
            type: "get",
            dataType: "json",
            async: true,
            success: function (json) {
                if (json.Code == 200) {
                    if (json.Result.interLog == "" && json.Result.jobLog == "" && json.Result.serverLog == "" && json.Result.pdaLog == "" && json.Result.upstreamLog == "") return;
                    if (LogTipsIndex > 0) {
                        $("#inter-body").text(json.Result.interLog);
                        $("#job-body").text(json.Result.jobLog);
                        $("#pda-body").text(json.Result.pdaLog);
                        $("#upstream-body").text(json.Result.upstreamLog);
                        $("#server-body").text(json.Result.serverLog);
                        return;
                    }

                    LogTipsIndex = layer.open({
                        title: "异常信息提示",
                        type: 1,
                        area: ['300px', '320px'],
                        offset: 'rb',
                        id: 'logStatisticsWindow',
                        content: $('.LogTips'),
                        success: function (layero, index) {
                            $("#inter-body").text(json.Result.interLog);
                            $("#job-body").text(json.Result.jobLog);
                            $("#pda-body").text(json.Result.pdaLog);
                            $("#upstream-body").text(json.Result.upstreamLog);
                            $("#server-body").text(json.Result.serverLog);
                        },
                        shade: 0
                    });
                }
            }
        });
    },
    updateLogTips: function (falg) {
        if (falg == "job") {
            $("#SysJobLog").trigger("click");
        } else {
            $("#SysInterfaceLog").trigger("click");
        }
        $.ajax({
            url: "/Home/UpdateLogTips?flag=" + falg,
            type: "get",
            success: function (val) {
                layer.close(LogTipsIndex);
                LogTipsIndex = 0;
            }
        });
    }
}

//未完成工单信息
function UnfinishedOrderInfo(index) {
    $.ajax({
        url: "/Home/UnfinishedOrderInfo",
        type: "post",
        dataType: "json",
        async: false,
        success: function (json) {
            if (index == 1) {
                $('#RedDot').attr({ 'class': '' });
                if (json.Code === 200) {
                    layer.open({
                        title: "未完成工单信息",
                        type: 1,
                        offset: 'rb',
                        id: 'layerDemorb',
                        content: json.Message,
                        btn: '关闭',
                        btnAlign: 'c',
                        shade: 0,
                    });
                } else {
                    layer.alert("获取工单信息错误!", { icon: 2, shadeClose: true, title: "错误提示" });
                }
            } else if (index == 2) {
                if (json.Status) {
                    $('#RedDot').attr({ 'class': 'layui-badge-dot' });
                    $('#RedDot').parent().parent().removeClass("layui-this");
                } else {
                    $('#RedDot').attr({ 'class': '' });
                }
            }

        }
    });
};


setInterval(() => {
    infoTips.LogTips();
}, 15000);



//考勤记录 300000
function WorkAttendanceLog() {
    layer.open({
        title: "考勤记录",
        area: ["900px", "600px"],
        type: 2,
        content: "/WorkAttendance/Index"
    });
};

//考勤功能
function WorkAttendance() {
    layer.open({
        title: "考勤",
        area: ["800px", "600px"],
        type: 1,
        content: $('#clock'),
        success: function () {
            login.initWebCam();
            login.initEvents();
            login.initWebcamLogin();

        },
        cancel: function () {
            // 右上角关闭事件的逻辑
            login.cancalCloseVideo();
        }
    });
};

var login = {
    initWebCam: () => {
        Webcam.set({
            width: 420,
            height: 440,
            image_format: "jpeg",
            jpeg_quality: 90
        });
        Webcam.attach("#webcam");
        WebcamObj = true;
    },

    //销毁摄像头
    cancalCloseVideo: () => {
        Webcam.reset("#webcam");
        Webcam.reset();
    },
    //登入方法
    LoginMethod: (bodyValue) => {
        isSendFlag = true;
        var index = 0;
        if (tabIndex != 0) index = layer.load();

        fetch("/WorkAttendance/Clock", {
            method: "post",
            headers: new Headers({
                "Content-Type": "application/x-www-form-urlencoded"
            }),
            body: bodyValue
        }).then(function (res) {
            return res.json();
        }).then(function (data) {
            isSendFlag = false;
            document.getElementById("IdCard").value = "";
            var src;
            if (data.Code === 200) {
                src = "/mp3/成功.mp3";

                layer.msg(data.Result.account + "用户,考勤成功 ", { icon: 6, shade: 0.4, time: 1000 });
                document.getElementById("loginMessage").innerHTML = data.Message;

            } else {
                src = "/mp3/失败.mp3";
                document.getElementById("loginMessage").innerHTML = data.Message;
            }
            var mp3 = new Audio(src);
            mp3.play();
            layer.close(index);
        }).catch(function (error) {
            isSendFlag = false;
            if (layer != null) document.getElementById("loginMessage").innerHTML = "登入失败";
        });
    },

    //自动刷脸登入
    initWebcamLogin: () => {
        setInterval(() => {
            if (WebcamObj == null) return;
            if (isSendFlag) {
                console.log("请求中 ");
                return;
            };
            if (tabIndex != 0) return;
            var v = document.querySelector('#webcam video');
            if (v == null) return;
            var ctx = canvas.getContext('2d');
            var height = v.videoHeight;
            var width = v.videoWidth;
            if (height == 0 || width == 0) return;
            canvas.height = height;
            canvas.width = width;
            ctx.drawImage(v, 0, 0, width, height);

            var comp = ccv.detect_objects({
                "canvas": ccv.grayscale(ccv.pre(canvas)),
                "cascade": cascade,
                "interval": 5,
                "min_neighbors": 1
            });
            if (comp.length > 0) {
                btnTakeSnapshot.click();
            }
            document.getElementById("ccvMessage").innerHTML = "检测图片结果: " + (comp.length ? '有人脸' : "没人脸");
        }, 6000);
    },

    //注册事件
    initEvents: () => {
        //刷卡登入
        if (timeout != null) timeout = null;
        IdCard.addEventListener('input', debounce(handle, 1000))

        //拍照
        btnTakeSnapshot.addEventListener("click", function () {
            if (WebcamObj == null) {
                alert("请等待摄像启动完成后再拍照登入");
                return;
            }
            Webcam.snap(function (data_uri) {
                if (data_uri == null) {
                    alert("请等待摄像启动完成后再拍照登入");
                    return;
                }
                var value = `username=''&password=''&webcam=${data_uri}&idcard=`;
                login.LoginMethod(value);
            });
        });
    }
}