var content_url = null;
//发票计数器
var countReceiot = 0;
//跨页面传递患者id参数核酸检测
var patientIdFullForNucleicAcid=null;
$(function () {
    if (localStorage.getItem("token") == undefined) {
        window.location.href = '/thmz/login/view'
    }
    $.ajax({
        type: "GET",
        contentType: "application/json;charset=UTF-8",
        url: "/thmz/getUserName",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (result) {
            if (result == '401' || result == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (result.code == 0) {
                $(".current_user").html(result.data.userName);
            }
        }
    });

    /**
     *初始化文件上传框
     */
    try {
        $("#mydropzone").dropzone({
            url: "/thmz/upload",
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token"),
                'fileType': localStorage.getItem("fileType")
            },
            init: function () {
                this.on("success", function (file, data) {
                    if (data == '401' || data == 401) {
                        window.location.href = '/thmz/login/view'
                        return;
                    }
                    if (data.code == 0) {
                        if (localStorage.getItem("fileType") == 0) {
                            window.location.href = '/thmz/menu/view'
                        }
                    }
                });
            },
        });
    } catch (e) {
        console.error("出现一些未知错误")
    }
    imgFun("/thmz/download-profile", "headImage,headImage1,headImage2,headImage3,headImage4,headImage5");


    //构造当前用户的菜单树
    getCurrentUserMenu();

    //设置主页
    changeContent('/thmz/index');
    //$("#home").click();


    $(document).keydown(function (event) { //监听键盘按下时的事件
        //按F4进行页面切换
        if (event.keyCode == 115) {
            if (content_url == '/thmz/registration') {
                changeContent('/thmz/toll-administration');
            } else {
                changeContent('/thmz/registration');
            }
            return;
        }

    });
    postCMD("connect",localStorage.getItem("userID"),'000000','收费项目',0,0,0, '','祝您早日康复',0,0,0);
});


/**
 * 构造当前用户的菜单树
 */
function getCurrentUserMenu() {
    $.ajax({
        type: "GET",
        url: '/thmz/getRoleMenuRelationForCurrentUser',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = "";
            for (var i = 0; i < res.data.length; i++) {
                var parentMenuVo = res.data[i];
                var parentMenu = parentMenuVo.menu;
                var menuList = parentMenuVo.menuList;
                if (parentMenu.menuUrl == null || parentMenu.menuUrl == "" || parentMenu.menuUrl.length == 0) {
                    html += '<li><a><i class="' + parentMenu.classCode + '"></i>' + parentMenu.name;
                } else {
                    html += '<li><a href="#" onclick="changeContent(\'' + parentMenu.menuUrl + '\')"><i class="' + parentMenu.classCode + '"></i>' + parentMenu.name;
                }
                if (menuList != null && menuList.length > 0) {
                    html += '<span class="fa fa-chevron-down"></span></a><ul class="nav child_menu">';
                    for (var j = 0; j < menuList.length; j++) {
                        var childMenu = menuList[j];
                        html += '<li><a href="#" onclick="changeContent(\'' + childMenu.menuUrl + '\')">' + childMenu.name + '</a></li>';
                    }
                    html += '</ul>';
                } else {
                    html += '</a>';
                }
                html += '</li>';
            }
            $("#menuBaseNode").html(html);
            init_sidebar();
        }
    });
}


function loginOut() {
    if (localStorage.getItem("token") == undefined) {
        window.location.href = '/thmz/login/view'
    }
    $.ajax({
        type: "POST",
        contentType: "application/json;charset=UTF-8",
        url: "/thmz/login-out",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (result) {
            if (result == '401' || result == 401 || result.code == 0) {
                postCMD("logout",localStorage.getItem("userID"),'000000','收费项目',0,0,0, '','祝您早日康复',0,0,0);
                window.location.href = '/thmz/login/view'
                return;
            }
        }
    });
}


/**
 * 编辑个人信息
 */
function editProfile() {
    NProgress.start();
    try {
        $('#reportrange').data('daterangepicker').remove();
        $("div.datetimepicker").remove();
    } catch (e) {
        console.log("不存在对应的日期选择器，无需销毁")
    }
    $("#profileimage").css("display", "none");
    $("#content").load("/thmz/html/profile.html");
    $.getScript('/thmz/js/profile.js');
    $.getScript('/thmz/js/message.js');
    NProgress.done();
}

/**
 * 密码修改
 */
function editPassword() {
    NProgress.start();
    try {
        $('#reportrange').data('daterangepicker').remove();
        $("div.datetimepicker").remove();
    } catch (e) {
        console.log("不存在对应的日期选择器，无需销毁")
    }
    $("#profileimage").css("display", "none");
    $("#content").load("/thmz/html/password.html");
    $.getScript('/thmz/js/password.js');
    NProgress.done();
}

/**
 * 头像修改
 */
function editProfileImage() {
    NProgress.start();
    try {
        $('#reportrange').data('daterangepicker').remove();
        $("div.datetimepicker").remove();
    } catch (e) {
        console.log("不存在对应的日期选择器，无需销毁")
    }
    $("#content").html("");
    $("#profileimage").css("display", "block");
    $("#mydropzone").css("display", "none");
    $(".x_content").append("<img id='headImage99'/>")
    imgFun("/thmz/download-profile", "headImage99");
    //设置文件类型为头像
    localStorage.setItem("fileType", "0");
    NProgress.done();
}


/**
 *  设置全屏：目前这个方法无法监听 ESC 键盘按键
 */
$('#alarm-fullscreen-toggler').on('click', function (e) {
    var element = document.documentElement;		// 返回 html dom 中的root 节点 <html>
    if (!$('body').hasClass('full-screen')) {
        $('body').addClass('full-screen');
        $('#alarm-fullscreen-toggler').addClass('active');
        // 判断浏览器设备类型
        if (element.requestFullscreen) {
            element.requestFullscreen();
        } else if (element.mozRequestFullScreen) {	// 兼容火狐
            element.mozRequestFullScreen();
        } else if (element.webkitRequestFullscreen) {	// 兼容谷歌
            element.webkitRequestFullscreen();
        } else if (element.msRequestFullscreen) {	// 兼容IE
            element.msRequestFullscreen();
        }
        $(this).attr("data-original-title", "退出全屏");
    } else {			// 退出全屏
        console.log(document);
        $('body').removeClass('full-screen');
        $('#alarm-fullscreen-toggler').removeClass('active');
        //	退出全屏
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
        $(this).attr("data-original-title", "全屏");
    }
});

/**
 * 锁屏按钮点击事件
 */
$("#lockScreen").on('click', function (t) {
    //默认10分钟不操作会锁屏
    fcode.Time = 600;
    fcode.customHtml = '<div style="margin-top:80px;"><img src="/thmz/images/img.jpg" style="width:70px;height:70px;border-radius:100px"><br><br></div>';
    fcode.bgImage = '/thmz/images/backgrounds/back5.jpg'; //设置背景图片，优先于背景颜色
    $.ajax({
        type: "POST",
        contentType: "application/json;charset=UTF-8",
        url: "/thmz/user-info",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (result) {
            if (result == '401' || result == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (result.code == 0) {
                if (result.data.lockScreenPassword != null && result.data.lockScreenPassword != "") {
                    fcode.bgImage = '/thmz/images/backgrounds/back6.jpg'; //设置背景图片，优先于背景颜色
                    fcode.Start(result.data.lockScreenPassword);
                } else {
                    fcode.Uppwd();
                }
            } else {
                errorMesage(result);
            }
        }
    });
});

/**
 * 下载远程的图片并加载到页面
 * @param url
 * @param imgs
 */
function imgFun(url, imgs) {
    var windowUrl = window.URL || window.webkitURL;//处理浏览器兼容性
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem("token"));
    xhr.onload = function () {
        //console.log(this);
        if (this.status == 200) {
            var blob = this.response;
            var arr = imgs.split(",");
            for (var i = 0; i < arr.length; i++) {
                $("#" + arr[i]).load(function (e) {
                    windowUrl.revokeObjectURL($("#" + arr[i]).src);
                }).attr("src", windowUrl.createObjectURL(blob));
            }
        }
    }
    xhr.send();
}

/**
 * 打开上传图片操纵框
 */
function profileImage() {
    $("#mydropzone").css("display", "block");
    $("#profileImageTitleInfo").removeClass('hide').addClass('in');
    $("#headImage99").remove();
}


/**
 * 页面跳转
 */
function changeContent(url) {
    var params = null;
    if(url.indexOf("?")>0){
        var realUrl=url.substring(0,url.indexOf("?"));
        params=url.substring(url.indexOf("?")+1);
        //跨页面传值
        if(params!=null && params!=""){
            patientIdFullForNucleicAcid=params;
        }
        url=realUrl;
    }
    NProgress.start();
    try {
        $('#reportrange').data('daterangepicker').remove();
        $("div.datetimepicker").remove();
    } catch (e) {
        console.log("不存在对应的日期选择器，无需销毁")
    }
    $("#profileimage").css("display", "none");
    $.ajax({
        type: "GET",
        url: url,
        dataType: 'html',
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (result) {
            content_url = url;
            $("#content").html(result);
        },
        error:function (jqXHR) {
           var responseText= JSON.parse(jqXHR.responseText);
            new PNotify({
                title: '错误提示',
                text: responseText.message,
                type: 'error',
                hide: false,
                styling: 'bootstrap3'
            });
        }
    });
    NProgress.done();
}
