/*2014-05-30 add by yb
 * describe:菜单管理
 * 
 */
var menutree = null;
var functiontree = null;
var treecodeStart = 0;
var newCount = 1;
var className = "dark";
var serverId = '';
var port = '1';
var funIds = "";
//菜单树setting配置
var setting1 = {
  view: {
    addHoverDom: addHoverDom,
    removeHoverDom: removeHoverDom,
    selectedMulti: false
  },
  edit: {
    enable: true,
    editNameSelectAll: true,
    showRemoveBtn: showRemoveBtn,
    showRenameBtn: true
  },
  data: {
    simpleData: {
      enable: true
    }
  },
  check: {
    enable: true,
    chkStyle: "checkbox",
    chkboxType: {
      "Y": "ps",
      "N": "ps"
    }
  },
  callback: {
    onCheck: zTreeOnCheck
  }
};
//系统功能树setting配置
var setting2 = {
  data: {
    simpleData: {
      enable: true
    }
  },
  check: {
    enable: true,
    chkStyle: "checkbox",
    chkDisabledInherit: true,
    chkboxType: {
      "Y": "ps",
      "N": "ps"
    }
  },
  callback: {
 
  }
};

function beforeDrag(treeId, treeNodes) {
  return false;
}

function addHoverDom(treeId, treeNode) {
  var sObj = $("#" + treeNode.tId + "_span");
  if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
  var addStr = "<span class='button add' id='addBtn_" + treeNode.tId +
    "' title='add node' onfocus='this.blur();'></span>";
  sObj.after(addStr);
  var btn = $("#addBtn_" + treeNode.tId);
  if (btn) btn.bind("click", function () {
    var zTree = $.fn.zTree.getZTreeObj("menutree");
    var treeid = treecodeStart + newCount;
    var name = "new code" + (newCount++);
    zTree.addNodes(treeNode, {
      id: treeid,
      pId: treeNode.id,
      name: name
    });

    var newNode = {
      id: treeid,
      pId: treeNode.id,
      name: name
    };
    saveOrUpdateMenu(newNode, "add");
    return false;
  });
};

function removeHoverDom(treeId, treeNode) {
  $("#addBtn_" + treeNode.tId).unbind().remove();
};

function showRemoveBtn(treeId, treeNode) {
  if (treeNode.isParent || treeNode.id == "0") {
    return false;
  } else {
    return true;
  }
  //return !treeNode.isFirstNode;
}
//  每次点击 checkbox后， 弹出该节点的 tId、name 以及当前勾选状态的信息
function zTreeOnCheck(event, treeId, treeNode) {
  let list = [];
  // console.log(treeNode.id + ", " + treeNode.name + "," + treeNode.checked);
  menutree = $.fn.zTree.getZTreeObj("menutree");
  var nodes = menutree.getCheckedNodes(true);
  // console.log(nodes, 'ccc');
  $.each(nodes, function (index, value) {
    list.push(value.id)
  })
  funIds = list.join(",");
  console.log('ceshi：',funIds);
  initFunctionTree(funIds);
};
//编辑按钮的 click 事件
function beforeEditName(treeId, treeNode) {
  className = (className === "dark" ? "" : "dark");
  var zTree = $.fn.zTree.getZTreeObj("menutree");
  zTree.selectNode(treeNode);
  return confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？");
}

//捕获节点被删除之前的事件
function beforeRemove(treeId, treeNode) {
  className = (className === "dark" ? "" : "dark");
  var zTree = $.fn.zTree.getZTreeObj("menutree");
  zTree.selectNode(treeNode);
  return confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
}

//捕获删除节点之后的事件回调函数
function onRemove(e, treeId, treeNode) {
  var contextPath = $("#contextPath").val();
  $.ajax({
    url: contextPath + "/admin/ajax/deleMenu",
    type: "POST",
    data: {
      treeCode: treeNode.id,
      parentCode: treeNode.pId
    },
    dataType: "json",
    success: function (data) {
      if (data != null && data.errcode == "200") {
        alert("菜单 -" + treeNode.name + " 删除成功");
      } else {
        alert("删除失败." + data.errcode + " 请刷新");
      }
    },
    error: function (data) {
      alert("删除失败." + data.errcode + " 请刷新");
    }
  });
}

//捕获节点编辑名称结束（Input 失去焦点 或 按下 Enter 键）
function beforeRename(treeId, treeNode, newName, isCancel) {
  className = (className === "dark" ? "" : "dark");
  if (newName.length == 0) {
    alert("节点名称不能为空.");
    var zTree = $.fn.zTree.getZTreeObj("menutree");
    setTimeout(function () {
      zTree.editName(treeNode)
    }, 10);
    return false;
  }
  return true;
}

//用于捕获节点编辑名称结束之后的事件回调函数
function onRename(e, treeId, treeNode, isCancel) {
  if (!isCancel) {
    saveOrUpdateMenu(treeNode, "update");
  }
}

//查询节点基本信息
function onClick_Menuinfo(e, treeId, treeNode, isCancel) {
  $("#menuName").val(treeNode.name);
  var contextPath = $("#contextPath").val();
  $.ajax({
    url: contextPath + "/admin/ajax/getMenu",
    type: "POST",
    data: {
      treeCode: treeNode.id,
      parentCode: treeNode.pId
    },
    dataType: "json",
    success: function (data) {
      if (data != null && data != "") {
        //描述信息
        $("#description").val(data.description);
        $("#isApp").val(data.isApp);
        $("#iconUrl").val(data.iconUrl);
        $("#menuCode").val(data.menuCode);

        //url 信息
        $("#url").val(data.url);
        if (data.appfunctionId != null) {
          //关联右侧功能菜单
          var nodes = functiontree.getNodes();
          $.each(nodes, function (index, node) {
            if (node.id == data.appfunctionId) {
              node.checked = true;
            } else {
              node.checked = false;
            }
          });
        } else {
          $("#url").val("");
          reloadFunctree();
        }
        functiontree.refresh();
      }
    },
    error: function (data) {}
  });

}

//勾选功能菜单
function onCheck_appFunc(e, treeId, treeNode) {
  $("#url").val(treeNode.url);
}

//TODO 加载功能树
function initMenuTree(serverId, port) {
  var contextPath = $("#contextPath").val();
  $.ajax({
    url: contextPath + "/admin/serveConfig/functiontree",
    type: "POST",
    dataType: "json",
    data: {
      serverId: serverId,
      port: port
    },
    success: function (data) {
      // console.log(data, '功能');
      let list = [];
      $.fn.zTree.init($("#menutree"), setting1, data.data);
      menutree = $.fn.zTree.getZTreeObj("menutree");
      menutree.expandAll(true);
      var nodes = menutree.getCheckedNodes(true);
      // console.log(nodes,'ccc');
      $.each(nodes, function (index, value) {
        list.push(value.id)
      })
      funIds = list.join(",");
      initFunctionTree(funIds);
    },
    error: function (data) {
      // alert("系统繁忙,加载失败..");
    }
  });
}

//TODO 加载菜单树
function initFunctionTree(funIds) {
  var contextPath = $("#contextPath").val();
  $.ajax({
    url: contextPath + "/admin/serveConfig/menutree",
    type: "POST",
    dataType: "json",
    data: {
      funIds: funIds
    },
    success: function (data) {
      // console.log(data, '菜单')
      $.fn.zTree.init($("#functiontree"), setting2, data.data);
      functiontree = $.fn.zTree.getZTreeObj("functiontree");
      functiontree.expandAll(true);
      var nodes = functiontree.getNodesByFilter(filter);
      // console.log(nodes, 'ddd');
      for (var i = 0, l = nodes.length; i < l; i++) {
        functiontree.setChkDisabled(nodes[i], true);
      }
    },
    error: function (data) {
      // alert("系统繁忙,加载菜单树失败..");
    }
  });
}
//过滤节点的机制 直接return node表示不做任何过滤
function filter(node) {
  return node;
}

function saveOrUpdateMenu(treeNode, actType, description, ordernum, funcId, menuName, isApp, iconUrl, menuCode) {
  var contextPath = $("#contextPath").val();
  $.ajax({
    url: contextPath + "/admin/ajax/addOrUpdateMenu",
    type: "POST",
    data: {
      treeCode: treeNode.id,
      parentCode: treeNode.pId,
      menuName: menuName,
      actType: actType,
      description: description,
      ordernum: ordernum,
      funcId: funcId,
      isApp: isApp,
      iconUrl: iconUrl,
      menuCode: menuCode
    },
    dataType: "json",
    success: function (data) {
      if (data.errcode == "200") {
        alert("保存成功.");
      } else {
        alert("保存失败." + data.errcode);
      }
    },
    error: function (data) {
      // alert("系统繁忙,保存失败");
    }
  });
}

// 列表1点击事件
function itemClick(id) {
  serverId = id;
  // console.log(serverId, 'aaa');

  $("#list1 li").removeClass("active");
  $("#" + id).addClass("active");
  initMenuTree(serverId, port);
}
// 列表2点击事件
function item2Click(id) {
  port = id;
  // console.log(port, 'bbb');
  $(".list2 li").removeClass("focus");
  if (id == 1) {
    $(".list2 li:first-of-type").addClass("focus");
  } else {
    $(".list2 li:last-of-type").addClass("focus");
  };
  initMenuTree(serverId, port);
}

$(function () {
  var service = $("#contextPath").val();
  var api = {
    get_service_list: function () {
      var serviceIn = "";
      $.ajax({
        type: "post",
        url: service + "/admin/serveConfig/serverList",
        data: {},
        success: function (data) {
          if (data.code == "200") {
            let list = data.data;
            $.each(list, function (index, value) {
              var trs = "";
              trs += "<li id='" + value.id + "' onclick='itemClick(" + value.id + ")'>" + value.name + "<i></i></li>";
              serviceIn += trs;
            })
            $("#list1").append(serviceIn);
            $("#list1 li:first-of-type").addClass("active");
            serverId = list[0].id;
            //初始化菜单树
            initMenuTree(serverId, port);
          }
          // console.log(data, 111);
        },
        error: function (error) {
          console.log("error")
        }
      });
    },
    save_service_list: function (serverId, port, funIds) { //保存
      $.ajax({
        type: "post",
        url: service + "/admin/serveConfig/saveUpdateServiceFunctionRelation",
        data: {
          serverId: serverId,
          port: port,
          funIds: funIds
        },
        success: function (data) {
          console.log(data, '999');
          if(data.code == "200"){
            $(".alert").css("display","block");
            setTimeout(() => {
              $(".alert").css("display","none");
            }, 1000);
          }
        },
        error: function (error) {
          console.log("error")
        }
      });
    }
  }
  api.get_service_list();

  // 保存修改
  $(".btn2").click(function () {
    api.save_service_list(serverId, port, funIds);
  })
  // 取消修改
  $(".btn1").click(function () {
    serverId = '';
    port = '1';
    funIds = "";
    $("#list1 li").removeClass("active");
    $(".list2 li").removeClass("focus");
    $(".list2 li:first-of-type").addClass("focus");
    api.get_service_list();
  })

});


function reloadFunctree() {
  var nodes = functiontree.getCheckedNodes(true);
  $.each(nodes, function (index, node) {
    node.checked = false;
  });
  functiontree.refresh();
}