var MENU;
var myTree;
var zMenu = new Array(4);
var iconObj = new Array(4);

//计算左面的
$(document).ready(function() {
    // $('#mum_left').perfectScrollbar();
    //$('#mum_left').height($(document).height() - 60);
    $('#main_panel').height($(document).height() - 100);
    $('#main_panel_body').height($(document).height() - 130);
    // $('#mum_right .panel').height($(document).height()-100);
    initUserinfo();
    setletftime();
    getServerTime();

    $('#treeMenu').on('click', 'a', function() {
        if ($(this).hasClass("p_m")) { return; }
        $('#treeMenu li.active').removeClass('active');
        $(this).closest('li').addClass('active');
        getPageInfo(this.id)
            // $("#main_content").html(getPageInfo(this.id));
    });


    $('#treeMenu').on('expand.zui.tree', function($li) {
        myTree = $('#treeMenu').data('zui.tree');
        var c_s = myTree.$[0].children

        for (var i = 0; i < c_s.length; i++) {
            if ($(myTree.$[0].children[i]).attr("data-idx") == $li.attr("data-idx")) continue;
            myTree.collapse($(c_s[i]))
        }

        // myTree.expand($li)
    });

    //获取用户信息
    var user = $.zui.store.get("user")
    if (user == null || typeof(user) == "undefined") {
        layer.msg('登陆已经过期，将重新登陆！', {
            time: 2000, //20s后自动关闭
        }, function() {
            self.location = base_ui_url + UI_USER_LOGIN + "?time=" + (Date.parse(new Date()));
        })

        return;
    } else {
        var html = "<i class=\"icon icon-user\"></i>  " + user.truename + " " + user.organname + ",欢迎您"
        $("#user").html(html);
    }

    var offset = "auto";
    if (ISCLIENT) {
        offset = "t";
    }
    $("#login_out_btn").on("click", function() {
        layer.confirm('您确定要退出登录？', {
            offset: offset,
            shade: 0,
            btn: ['确定'] //按钮
        }, function() {
            UserLoginOUT(function() {

                self.location = base_ui_url + UI_USER_LOGIN
            }, function(error) {
                layer.msg(error, { icon: 3 });
            })
        });
    });



    //判断路径中是否包含其他稽查的路径
    var pathName = window.document.location.pathname;
    for(var i=0;i<4;i++){
        var typeid = (i+1)*10;
        var mbody ={
            type: typeid
        }
        //alert(mbody.type);
        MenuGetAll(menusuccess,function(error) {}, mbody);
    }     

});

function update_user_info_data() {
    edittype = "update"
    user = $.zui.store.get("user")
    loadUserData(user)
    $('#addUserModal').modal('show')
}

var roles = [];
var zdata = [];

function initUserinfo() {

    getJob();

    RoleGetALLNoData(function(data) {

        roles = [];
        for (var i = 0; i < data.length; i++) {
            var m = data[i];
            var zdataItem = {};
            zdataItem["id"] = m.id;
            zdataItem["title"] = m.des;
            roles.push(zdataItem);
        }
    }, function(error) {

    });

    DeptGetAll(function(data) {
        zdata = [];
        for (var i = 0; i < data.length; i++) {
            var m = data[i];
            var zdataItem = {};
            zdataItem["id"] = m.id;
            zdataItem["value"] = m.id;
            zdataItem["pId"] = null;
            zdataItem["name"] = m.organname;
            zdataItem["open"] = true;
            zdataItem["children"] = addobj_child(m);
            zdata.push(zdataItem);
        }
        // dept_tree = $.fn.zTree.init($("#department_tree"), setting, zdata)
    }, function(error) {

    });

}

function addobj_child(data) {
    var zdata = [];
    if (typeof(data.childs) != "undefined" && data.childs != null &&
        data.childs.length > 0) {
        for (var i = 0; i < data.childs.length; i++) {
            var m = data.childs[i];
            var zdataItem = {};
            zdataItem["id"] = m.id;
            zdataItem["value"] = m.id;
            zdataItem["pId"] = data.id;
            zdataItem["icon"] = "";
            zdataItem["open"] = true;
            zdataItem["name"] = m.organname;
            zdataItem["children"] = addobj_child(m);
            zdata.push(zdataItem);
        }
        return zdata;
    } else {
        return [];
    }
}


function chageToPageUI(menu) {
    $('#treeMenu').tree('expand', $("#" + menu.parentId).parent());
    $('#treeMenu li.active').removeClass('active');
    $("#" + menu.id).closest('li').addClass('active');
}



function setletftime() {
    // var height = window.innerHeight;
    // $("#mum_left").css("min-height", height - 90);
    // if ($("#main").height() > height) {
    //     $("#mum_left").css("min-height", $("#main").height() - 80);
    // }


    setTimeout(setletftime, 100);
}


function getPageInfo(id) {
    //设置当前页面
    $.zui.store.set("currentpage", id);
    if (typeof(MENU) != "undefined" && MENU != null) {
        for (var i = 0; i < MENU.length; i++) {
            var menu = MENU[i];
            if (menu.id == id) {
                if (typeof(menu.url) != "undefined") {
                    // current_mid = menu.id;
                    // alert(current_mid);
                    redirectPage(menu.url);
                    chageToPageUI(menu);
                    return;
                }
                break;
            }
            if (menu.childs.length > 0) {
                for (var j = 0; j < menu.childs.length; j++) {
                    var mtemp = menu.childs[j];
                    if (mtemp.id == id) {
                        if (typeof(mtemp.url) != "undefined") {
                            // current_mid = menu.id;
                            // alert(current_mid);
                            redirectPage(mtemp.url);
                            chageToPageUI(mtemp)
                            return;
                        }
                        break;
                    }
                }
            }

        }
    }
    return $("#main_content").load(base_ui_url + "/view/user/aa.html");


}

var current_url; //当前显示页面url
var current_mid; //当前显示页面id
var isnew = true;


function changePage_temp(url) {
    isnew = false;
    changePage(url);
}

function changePage(url, tableObj) {
    // var pre_param = $.zui.store.get('store_param_'+url);
    // console.log(pre_param);
    if (typeof(url) != "undefined") {
        //记住表格当前页
        if (tableObj) {
            var data_param = $.zui.store.get('store_param_' + current_url);
            if (data_param) data_param.currentpage = tableObj.options.pager.p_cur;
            $.zui.store.set('store_param_' + current_url, data_param);
        }

        CURRENT_PAGE_URL = url;
        var page_params = GetQueryString(url);
        $.zui.store.set("page_params", page_params);
        current_url = url;
        $("#main_content").load(base_ui_url + url);


        var name = $.zui.store.get(url);
        if (name) {
            // $("#breadcrumb_menu").html('<li murl="'+url+'" mname="'+name+'"><a href="#" onclick="changePage('+url+')">'+name+'</a></li>');
            addBreadMenu(url, name, isnew);
        } else {
            var t = url.split("?")[0];
            name = $.zui.store.get(t);

            if (name && page_params["jump"] == 1) {
                addBreadMenu(url, name, isnew);
            }
        }
        isnew = true;
        if (ISCLIENT) {
            event = document.createEvent('MessageEvent');
            var origin = window.location.protocol + '//' + window.location.host;
            event.initMessageEvent('changepage', true, true, CURRENT_PAGE_URL, origin, 1234, window, null);
            document.dispatchEvent(event);
        }
    }
}
//菜单跳转页面
function redirectPage(url) {
    var pre_param = $.zui.store.set('store_param_' + url, null);
    changePage(url);
}
//跳转到最新打开的菜单，并保存上次的请求参数
function redirectLastPage() {
    var currentpage = $.zui.store.get("currentpage");
    if (typeof(MENU) != "undefined" && MENU != null) {
        for (var i = 0; i < MENU.length; i++) {
            var menu = MENU[i];
            if (menu.childs.length > 0) {
                for (var j = 0; j < menu.childs.length; j++) {
                    var mtemp = menu.childs[j];
                    if (mtemp.id == currentpage) {
                        if (typeof(mtemp.url) != "undefined") {
                            changePage(mtemp.url);
                        }
                        break;
                    }
                }
            }
        }
    }
}

function GetQueryString(url) {
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.split("?")[1];
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

function addBreadMenu(url, name, flag) {
    console.log(flag)
    var menu = hasMenu(url, name, flag);
    if (menu >= 0) {
        // $("#breadcrumb_menu").remove($(menu).nextAll());
        var children = $("#breadcrumb_menu").children("li");
        for (var i = 0; i < children.length; i++) {
            if (i >= menu) {
                $(children[i]).remove();
            }
        }
    }
    if (flag)
        $("#breadcrumb_menu").html('<li murl="' + url + '" mname="' + name + '"><a href="javascript:void(0)" onclick="changePage_temp(\'' + url + '\')"><span>' + name + '</span></a></li>');
    else
        $("#breadcrumb_menu").append('<li murl="' + url + '" mname="' + name + '"><a href="javascript:void(0)" onclick="changePage_temp(\'' + url + '\')"><span>' + name + '</span></a></li>');

    isnew = true;
}

function hasMenu(url, name) {
    var children = $("#breadcrumb_menu").children("li");
    for (var i = 0; i < children.length; i++) {
        if ($(children[i]).attr("murl") == url && $(children[i]).attr("mname") == name) {
            return i;
        }
    }
    return -1;
}

function menusuccess(data){
    var menu = data;
    var obj;
    var divhtml = '';
    //console.log(data[0].type);
    if(menu.length>0){
        //var content ={};
        //console.log(menu);
        var id = "app"+menu[0].type;
        var typeid = "type"+menu[0].type;
        document.getElementById(typeid).style.display = "block";
        var j = menu[0].type/10-1;
        obj = document.getElementById(id);
        zMenu[j] = new Array(menu.length);
        iconObj[j] = new Array(menu.length);
        for(var i=0;i<menu.length;i++){
            zMenu[j][i]= menu[i].childs;
            var menuobj = {
                iconClass:menu[i].iconClass,
                menuname:menu[i].menuname
            }
            iconObj[j][i] = menuobj;
            //console.log(zMenu[j][i]);
            //zMenu[j][i] = menu[i].iconClass;
            //var setcontent = data[i].childs;
            //setcontent =  JSON.stringify(setcontent);
            //console.log(setcontent);
            //console.log(menu[i].iconClass);
            // var html = ' <div class="col-md-1" style="text-align: center"><buuton type="button" class="btn btn-primary" data-toggle="modal" data-target="#myLgModal" style="background-color: #86C7D8;border-radius: 10px;height:80px;width:80px" href="#" ><img class="imgsize" src="/images/'+menu[i].iconClass+'.png"/></button><br/><font style="">'+menu[i].menuname+'</font></div>';
            var html =' <div onclick="setdiv('+j+','+i+')" class="col-md-1" style="text-align: center"><button  style="background-color:#366ba5;border-radius: 10px;height: 80px;width: 80px" type="button"><img style="" src="/images/'+menu[i].iconClass+'.png"/></button><br/><font>'+menu[i].menuname+'</font></div>';
            if(menu[i].type == 30){
            html = ' <div onclick="noApp()" class="col-md-1" style="text-align: center"><button  style="background-color:#2c2d3096;border-radius: 10px;height: 80px;width: 80px" type="button"><img style="" src="/images/'+menu[i].iconClass+'.png"/></button><br/><font>'+menu[i].menuname+'</font></div>';
            }
            if(menu[i].iconClass == "desktop"){
                html = '';
                document.getElementById("typebase").style.display = "block";
            }
            divhtml = divhtml +html;
        }
       // console.log(zMenu);
        obj.innerHTML = divhtml;
    }
}

function setdiv(a,b){
    var divhtml = '';
    var divhtml2 = '';
   for(var i=0;i<zMenu[a][b].length;i++){
        var html ='<div class="col-md-1" style="text-align: center;margin-left:10px;margin-top:20px"><button style="width:60px;height:60px;background-color: #366ba5;border-radius: 10px" onclick="opennew(\''+zMenu[a][b][i].url+'\',\''+zMenu[a][b][i].id+'\')" ><img style="height:40px;width:40px;" src="/images/'+iconObj[a][b].iconClass+'.png"/></button><br/><font>'+zMenu[a][b][i].menuname+'</font></div>';
        divhtml = divhtml +html;
    }   // $("modal").append(html);
    layer.open({
        type: 1,
        title:iconObj[a][b].menuname,
        skin: 'layui-layer-rim', //加上边框
        area: ['918px', '300px'], //宽高
        content: divhtml
      });
}

function opennew(url,id){
    //alert(base_ui_url);
    var furl = url.split("/")[1];
    if(furl == "view"){
        furl = "view/main.html";
    }else{
        furl = furl +"/view/main.html";
    }
  //var mainurl = url.split("view")[0]+"view/main.html";
   // alert(furl);
    //alert(url);
    //alert(mainurl);
   window.location.href = base_ui_url+ furl+"?id="+id;
         //alert(url);
}

function noApp(){
   alert("待开发");
}