import {VisibleComponent} from "../controller.js";

/**
 * 树型组件
 * @param {[type]} dataModel [description]
 */
export default class Tree extends VisibleComponent {

  constructor(__tfp, dataModel, parent) {
    super(__tfp, "Tree", dataModel, parent);

    this.nodes = {};
    this.leafNodes = {};
    this.rootNodes = [];
    this.rootLeafNodes = [];

    this.iconPath = this._tfp.rootPath+"/src/components/tree/images/";
    this.iconColor = this._tfp.curPage.contentColorMode;
  }

  //属性
  get loadDataService() { return this.dataModel.loadDataService }
  set loadDataService(value) {this.dataModel.loadDataService = value }

  //属性
  get deleteNodeService() { return this.dataModel.deleteNodeService }
  set deleteNodeService(value) {this.dataModel.deleteNodeService = value }

  //属性
  get deleteLeafNodeService() { return this.dataModel.deleteLeafNodeService }
  set deleteLeafNodeService(value) {this.dataModel.deleteLeafNodeService = value }

  //属性
  get nodeDataMember() { return this.dataModel.nodeDataMember }
  set nodeDataMember(value) {this.dataModel.nodeDataMember = value }

  //属性
  get rootNodeParentId() { return this.dataModel.rootNodeParentId }
  set rootNodeParentId(value) {this.dataModel.rootNodeParentId = value }

  //属性
  get nodeIdFieldName() { return this.dataModel.nodeIdFieldName }
  set nodeIdFieldName(value) {this.dataModel.nodeIdFieldName = value }

  //属性
  get nodeNameFieldName() { return this.dataModel.nodeNameFieldName }
  set nodeNameFieldName(value) {this.dataModel.nodeNameFieldName = value }

  //属性
  get nodeParentIdFieldName() { return this.dataModel.nodeParentIdFieldName }
  set nodeParentIdFieldName(value) {this.dataModel.nodeParentIdFieldName = value }

  //属性
  get leafNodeDataMember() { return this.dataModel.leafNodeDataMember }
  set leafNodeDataMember(value) {this.dataModel.leafNodeDataMember = value }

  //属性
  get leafNodeIdFieldName() { return this.dataModel.leafNodeIdFieldName }
  set leafNodeIdFieldName(value) {this.dataModel.leafNodeIdFieldName = value }

  //属性
  get leafNodeNameFieldName() { return this.dataModel.leafNodeNameFieldName }
  set leafNodeNameFieldName(value) {this.dataModel.leafNodeNameFieldName = value }

  //属性
  get leafNodeParentIdFieldName() { return this.dataModel.leafNodeParentIdFieldName }
  set leafNodeParentIdFieldName(value) {this.dataModel.leafNodeParentIdFieldName = value }

  get expandAll() { return this.dataModel.expandAll }
  set expandAll(value) { 
    this.dataModel.expandAll = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get showNodeCheckbox() { return this.dataModel.showNodeCheckbox }
  set showNodeCheckbox(value) { 
    this.dataModel.showNodeCheckbox = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get showNodeEditButton() { return this.dataModel.showNodeEditButton }
  set showNodeEditButton(value) { 
    this.dataModel.showNodeEditButton = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get showNodeDeleteButton() { return this.dataModel.showNodeDeleteButton }
  set showNodeDeleteButton(value) { 
    this.dataModel.showNodeDeleteButton = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get showLeafNodeCheckbox() { return this.dataModel.showLeafNodeCheckbox }
  set showLeafNodeCheckbox(value) { 
    this.dataModel.showLeafNodeCheckbox = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get showLeafNodeEditButton() { return this.dataModel.showLeafNodeEditButton }
  set showLeafNodeEditButton(value) { 
    this.dataModel.showLeafNodeEditButton = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get showLeafNodeDeleteButton() { return this.dataModel.showLeafNodeDeleteButton }
  set showLeafNodeDeleteButton(value) { 
    this.dataModel.showLeafNodeDeleteButton = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get checkParentOnCheckChild() { return this.dataModel.checkParentOnCheckChild }
  set checkParentOnCheckChild(value) { 
    this.dataModel.checkParentOnCheckChild = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get checkAllChildOnCheckParent() { return this.dataModel.checkAllChildOnCheckParent }
  set checkAllChildOnCheckParent(value) { 
    this.dataModel.checkAllChildOnCheckParent = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get unCheckAllChildOnUnCheckParent() { return this.dataModel.unCheckAllChildOnUnCheckParent }
  set unCheckAllChildOnUnCheckParent(value) { 
    this.dataModel.unCheckAllChildOnUnCheckParent = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get unCheckParentOnUnCheckAllChild() { return this.dataModel.unCheckParentOnUnCheckAllChild }
  set unCheckParentOnUnCheckAllChild(value) { 
    this.dataModel.unCheckParentOnUnCheckAllChild = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get multiCheck() { return this.dataModel.multiCheck }
  set multiCheck(value) { 
    this.dataModel.multiCheck = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  get deepBackground() { return this.dataModel.deepBackground }
  set deepBackground(value) { 
    this.dataModel.deepBackground = value ? true : false;
    if(this._jqObj) {
      //
    }
  }

  clear() {
    this.nodes = {};
    this.leafNodes = {};
    this.rootNodes = [];
    this.rootLeafNodes = [];
    if(this._jqObj) this._jqObj.empty();
  }

  bindData(data) {
    if(!data) {
      this._tfp.showMsg("请提供要绑定的数据！");
      return;
    }
    
    if(!this.dataModel.nodeDataMember) {
      this._tfp.showMsg("请为组件["+this.id+"]设置[nodeDataMember]参数！");
      return;
    }

    let nodesData = data[this.dataModel.nodeDataMember];
    if(!nodesData) {
      this._tfp.showMsg("服务响应结果中没有名为["+this.dataModel.nodeDataMember+"]的参数！");
      return;
    }

    this.clear();
    var nodeIdArr = []; 
    
    //将服务器端返回数据转换为节点对象
    if(nodesData instanceof Array) {
      for(var i=0;i<nodesData.length;i++) {
        var nodeData = nodesData[i];
        var node = {};
        node.id = nodeData[this.dataModel.nodeIdFieldName];
        node.name = nodeData[this.dataModel.nodeNameFieldName];
        node.parentId = nodeData[this.dataModel.nodeParentIdFieldName];
        node.data = nodeData;
        node.childNodes = [];
        if(this.dataModel.leafNodeDataMember) node.leafNodes = [];
        this.nodes[node.id] = node;
        nodeIdArr.push(node.id);
      }
    } else {
      for(objId in nodesData) {
        var nodeData = nodesData[objId];
        var node = {};
        node.id = nodeData[this.dataModel.nodeIdFieldName];
        node.name = nodeData[this.dataModel.nodeNameFieldName];
        node.parentId = nodeData[this.dataModel.nodeParentIdFieldName];
        node.data = nodeData;
        node.childNodes = [];
        if(this.dataModel.leafNodeDataMember) node.leafNodes = [];
        this.nodes[node.id] = node;
        nodeIdArr.push(node.id);
      }
    }

    //如果有页节点数据，则生成页节点对象
    if(this.dataModel.leafNodeDataMember && data[this.dataModel.leafNodeDataMember]) {
      var leafNodesData = data[this.dataModel.leafNodeDataMember];
      for(var i=0;i<leafNodesData.length;i++) {
        var nodeData = leafNodesData[i];
        var node = {};
        node.id = nodeData[this.dataModel.leafNodeIdFieldName];
        node.name = nodeData[this.dataModel.leafNodeNameFieldName];
        node.parentId = nodeData[this.dataModel.leafNodeParentIdFieldName];
        this.leafNodes[node.id] = node;
        var parentNode = this.nodes[node.parentId];
        if(parentNode) {
          parentNode.leafNodes.push(node.id);
        }
      }
    }

    //生成节点之间的关系
    for(var i=0;i<nodeIdArr.length;i++) {
      var nodeId = nodeIdArr[i];
      var node = this.nodes[nodeId];
      if(node.parentId==this.dataModel.rootNodeParentId) {
        this.rootNodes.push(nodeId);
      } else {
        var parentNode = this.nodes[node.parentId];
        if(parentNode) {
          parentNode.childNodes.push(nodeId);
        }
      }
    }

    for(var i=0;i<this.rootNodes.length;i++) {
      var node = this.nodes[this.rootNodes[i]];
      if(!node.parentId) node.parentId = this.dataModel.rootNodeParentId;
      this.createNode(this._jqObj, node, 5);
    }
    /*if(this.dataModel.onLoaded) {
      eval(this.dataModel.onLoaded+"(req, res)");
    }*/
  }

  bindTreeNodes(rootNodes, nodes, leafNodes) {
    if(!rootNodes) {
      this._tfp.showMsg("请提供根节点数据！");
      return;
    }
    if(!nodes) {
      this._tfp.showMsg("请提供节点数据！");
      return;
    }
    this.rootNodes = rootNodes;
    this.nodes = nodes;
    if(leafNodes) this.leafNodes = leafNodes;

    for(var i=0;i<this.rootNodes.length;i++) {
      var node = this.nodes[this.rootNodes[i]];
      if(!node.parentId) node.parentId = this.dataModel.rootNodeParentId;
      this.createNode(this._jqObj, node, 5);
    }
  }

  loadData() {
    if(!this.dataModel.loadDataService) {
      this._tfp.showMsg("请为["+this.id+"]设置加载数据服务！");
      return;
    }
    let serviceCpt = this._tfp.get(this.dataModel.loadDataService);
    if(!serviceCpt) {
      this._tfp.showMsg("ID为["+this.dataModel.loadDataService+"]的组件不存在！");
      return;
    }

    let that = this;
    serviceCpt.status = 0;
    serviceCpt.request(null, function(req, res) {
      that.bindData(res);
    });
  }

  getNodeTextDivWidth(marginLeft) {
    //动态计算每个节点内文本框的最大宽度，以便文字过长时能自动出现省略号
    var divWidth = this._jqObj.get(0).offsetWidth;
    var nodeTextWidth = divWidth-marginLeft-16-22;
    if(this.dataModel.showNodeCheckbox) nodeTextWidth -= 25;
    if(this.dataModel.showNodeDeleteButton) nodeTextWidth -= 21;
    if(this.dataModel.showNodeEditButton) nodeTextWidth -= 21;
    return nodeTextWidth;
  }

  /**
   * 创建节点
   * @param  {[type]} parentDiv  [description]
   * @param  {[type]} node       [description]
   * @param  {[type]} marginLeft [description]
   */
  createNode(parentDiv, node, marginLeft) {
    var toggleIcon = "dot";
    var haveChild = false;
    if(node.childNodes.length>0 || (node.leafNodes && node.leafNodes.length>0)) haveChild = true;
    if(haveChild) toggleIcon = this.dataModel.expandAll ? "toggle" : "expand";
    var nodeHtml = "<div class=\"tfp-tree-node\" nodeId=\""+node.id+"\">"
      +"<div class=\"tfp-tree-node-icon\"><img src=\""+(this.iconPath+toggleIcon
      +"-"+this.iconColor)+".png\" style=\"margin-left: "+marginLeft+"px;\"></div>";
    if(this.dataModel.showNodeCheckbox) {
      let cbkType = this.dataModel.multiCheck ? "checkbox" : "radio";
      nodeHtml += "<div class=\"tfp-tree-node-checkbox\">"
        +"<input type=\""+cbkType+"\" value=\""+node.id+"\"";
      if(cbkType=="radio") nodeHtml += " name=\""+this.id+"\"";
      nodeHtml += "></div>";
    }
    nodeHtml += "<div class=\"tfp-tree-node-text\" style=\"";
      //+"width:"+this.getNodeTextDivWidth(marginLeft)+"px;"
    if(!this.dataModel.deepBackground) nodeHtml += "color:#333333";
    nodeHtml += "\">"+node.name+"</div>";
    if(this.dataModel.showNodeDeleteButton) {
      nodeHtml += "<div class=\"tfp-tree-node-button\">"
        +"<img src=\""+(this.iconPath+"del-"+this.iconColor)+".png\" title=\"删除\" style=\"cursor:pointer\"></div>";
    }
    if(this.dataModel.showNodeEditButton) {
      nodeHtml += "<div class=\"tfp-tree-node-button\">"
        +"<img src=\""+(this.iconPath+"edit-"+this.iconColor)+".png\" title=\"修改\" style=\"cursor:pointer\"></div>";
    }
    nodeHtml += "</div>";
    parentDiv.append(nodeHtml);

    let nodeDivNew = parentDiv.children(".tfp-tree-node").last();
    let that = this;
    nodeDivNew.mouseover(function() {
      var bgColor = that.dataModel.deepBackground ? "#444444" : "#EEEEEE";
      //$(this).css("background-color", bgColor);
      $(this).find(".tfp-tree-node-button").show();
    });
    nodeDivNew.mouseout(function() {
      //$(this).css("background-color", "");
      $(this).find(".tfp-tree-node-button").hide();
    });
    nodeDivNew.find(".tfp-tree-node-text").click(function() {
      if(that.dataModel.onClickNode) {
        let eventFucName = that._tfp.getCptEventFuncName(that.dataModel.onClickNode);
        eval(eventFucName+"('"+node.id+"')");
      }
      that.toggleNode(node.id);
    });
    nodeDivNew.find(".tfp-tree-node-icon").find("img").click(function() {
      that.toggleNode(node.id);
    });
    nodeDivNew.find(".tfp-tree-node-checkbox").find("input").click(function() {
      that.checkNode(node.id);
      if(that.dataModel.onClickNode) {
        let eventFucName = that._tfp.getCptEventFuncName(that.dataModel.onClickNode);
        eval(eventFucName+"('"+node.id+"')");
      }
    });
    nodeDivNew.find(".tfp-tree-node-button").find("img").click(function() {
      if($(this).attr("title")=="修改") {
        if(that.dataModel.onClickNodeEditButton) {
          let eventFucName = that._tfp.getCptEventFuncName(that.dataModel.onClickNodeEditButton);
          eval(eventFucName+"('"+node.id+"')");
        }
      } else {
        that.onClickDeleteNodeButton(node.id);
      }
    });
      
    var childDisplay = this.dataModel.expandAll ? "" : "display:none";
    var childNodesDiv = $("<div class=\"tfp-tree-node-childs\" "
      +"nodeId=\""+node.id+"\" style=\""+childDisplay+"\"></div>");
    parentDiv.append(childNodesDiv);
    if(haveChild) {
      for(var i=0;i<node.childNodes.length;i++) {
        var childNode = this.nodes[node.childNodes[i]];
        //如果子节点没有设置父节点编号属性，则在此设置一下
        //目前在选择部门和人员时需要这么做
        if(!childNode.parentId) childNode.parentId = node.id;
        this.createNode(childNodesDiv, childNode, marginLeft+20);
      } 
      if(node.leafNodes && node.leafNodes.length>0) {
        for(var i=0;i<node.leafNodes.length;i++) {
          var leafNode = this.leafNodes[node.leafNodes[i]];
          if(!leafNode) continue;
          if(!leafNode.parentId) leafNode.parentId = node.id;
          this.createLeafNode(childNodesDiv, leafNode, marginLeft+20);
        } 
      }
    }
  }

  /**
   * 处理节点删除按钮点击事件
   * @param  {[type]} nodeId     [description]
   */
  onClickDeleteNodeButton(nodeId) {
    if(!confirm("确定删除？")) return;
    if(this.dataModel.onClickNodeDeleteButton) {
      let eventFucName = this._tfp.getCptEventFuncName(this.dataModel.onClickNodeDeleteButton);
      eval(eventFucName+"('"+node.id+"')");
    } else if(this.dataModel.deleteNodeService) {
      var args = {};
      args[this.dataModel.nodeIdFieldName] = nodeId;
      args.childs = "";
      var childNodesDiv = $("#"+this.id).find(".tfp-tree-node-childs[nodeId="+nodeId+"]");
      childNodesDiv.find(".tfp-tree-node").each(function() {
        if(args.childs!="") args.childs += ",";
        args.childs += $(this).attr("nodeId");
      });
      let serviceCpt = this._tfp.components[this.dataModel.deleteNodeService];
      if(!serviceCpt) return;
      let that = this;
      serviceCpt.request(args, function(req, res) {
        if(res.code!=0) {
          that._tfp.showMsg(res.message);
          return;
        }
        that.deleteNode(nodeId);
      });
    }
  }

  /**
   * 删除节点
   * @param  {[type]} nodeId [description]
   * @return {[type]}        [description]
   */
  deleteNode(nodeId) {
    if(!(nodeId in this.nodes)) return;
    //删除节点对应的html元素
    var nodeDiv = this._jqObj.find(".tfp-tree-node[nodeId="+nodeId+"]");
    nodeDiv.remove();
    var childNodesDiv = this._jqObj.find(".tfp-tree-node-childs[nodeId="+nodeId+"]");
    childNodesDiv.remove();
    var node = this.nodes[nodeId];
    //删除子节点
    this.deleteChildNode(node);
    //解除与父节点的关联
    if(node.parentId!=this.dataModel.rootNodeParentId) {
      var parentNode = this.nodes[node.parentId];
      parentNode.childNodes.deleteMember(node.id);
      //如果父节点没有其他子节点了，则应该修改父节点的图标为无法收起或展开
      if(parentNode.childNodes.length==0 && parentNode.leafNodes.length==0) {
        let iconColor = this.dataModel.deepBackground ? "" : "-dark";
        var parentDiv = this._jqObj.find(".tfp-tree-node[nodeId="+node.parentId+"]");
        parentDiv.find(".tfp-tree-node-icon").find("img").get(0).src = 
          this.iconPath+"dot-"+this.iconColor+".png";
      }
    }
    //删除自己
    delete this.nodes[nodeId];
    node = null;
  }

  /**
   * 删除子节点
   * @param  {[type]} node [description]
   * @return {[type]}      [description]
   */
  deleteChildNode(node) {
    for(var i=0;i<node.childNodes.length;i++) {
      var childNodeId = node.childNodes[i];
      var childNode = this.nodes[childNodeId];
      if(!childNode) continue;
      this.deleteChildNode(childNode);
      delete this.nodes[childNode.id];
      childNode = null;
    }
    if(!node.leafNodes) return;
    for(var i=0;i<node.leafNodes.length;i++) {
      var leafNodeId = node.leafNodes[i];
      var leafNode = this.leafNodes[leafNodeId];
      delete this.leafNodes[leafNode.id];
      leafNode = null;
    }
  }

  /**
   * 处理节点选择框点击事件
   * @param  {[type]} nodeId [description]
   */
  checkNode(nodeId) {
    var node = this.nodes[nodeId];
    if(!node) return;
    var nodeDiv = this._jqObj.find(".tfp-tree-node[nodeId="+nodeId+"]");
    var cbk = nodeDiv.find(".tfp-tree-node-checkbox").find("input").get(0);
    var childNodesDiv = this._jqObj.find(".tfp-tree-node-childs[nodeId="+nodeId+"]");
    if(cbk.checked) {
      if(this.dataModel.multiCheck) {
        if(this.dataModel.checkAllChildOnCheckParent) {
          childNodesDiv.find(".tfp-tree-node-checkbox").find("input").each(function() {
            $(this).get(0).checked = cbk.checked;
          });
        }
        if(this.dataModel.checkParentOnCheckChild) {
          var parentId = node.parentId;
          while(parentId!=this.dataModel.rootNodeParentId) {
            var parentNode = this.nodes[parentId];
            var parentDiv = this._jqObj.find(".tfp-tree-node[nodeId="+parentId+"]");
            var parentCbk = parentDiv.find(".tfp-tree-node-checkbox").find("input");
            if(parentCbk.length==0) break;
            parentCbk.get(0).checked = true;
            parentId = parentNode.parentId;
          }
        }
      } else {
        $(":radio").each(function(){
          if($(this).parent().parent().attr("nodeId")!=nodeId) $(this).get(0).checked = false;
        });
      }
    } else {
      if(this.dataModel.unCheckAllChildOnUnCheckParent) {
        childNodesDiv.find(".tfp-tree-node-checkbox").find("input").each(function() {
          $(this).get(0).checked = cbk.checked;
        });
      }
      if(this.dataModel.unCheckParentOnUnCheckAllChild) {
        this.unCheckParentNode(node);
      }
    }
  }

  /**
   * 取消选中父节点
   * @param  {[type]} node [description]
   */
  unCheckParentNode(node) {
    var parentId = node.parentId;
    if(parentId==this.dataModel.rootNodeParentId) return;
    var parentNode = this.nodes[parentId];
    if(!parentNode) return;
    for(var i=0;i<parentNode.childNodes.length;i++) {
      var childId = parentNode.childNodes[i];
      var childDiv = this._jqObj.find(".tfp-tree-node[nodeId="+childId+"]");
      var childCbk = childDiv.find(".tfp-tree-node-checkbox").find("input");
      if(childCbk.length==0) continue;
      //如果父节点有其他子节点已选中，则不能取消选中父节点
      if(childCbk.get(0).checked) return;
    }
    if(this.dataModel.showLeafNodeCheckbox && parentNode.leafNodes) {
      for(var i=0;i<parentNode.leafNodes.length;i++) {
        var childId = parentNode.leafNodes[i];
        var childDiv = this._jqObj.find(".tfp-tree-node[nodeId="+childId+"]");
        var childCbk = childDiv.find(".tfp-tree-node-checkbox").find("input");
        if(childCbk.length==0) continue;
        //如果父节点有叶节点已选中，则不能取消选中父节点
        if(childCbk.get(0).checked) return;
      }
    }
    
    var parentDiv = this._jqObj.find(".tfp-tree-node[nodeId="+parentId+"]");
    var parentCbk = parentDiv.find(".tfp-tree-node-checkbox").find("input");
    if(parentCbk.length==0) return;
    parentCbk.get(0).checked = false;
    this.unCheckParentNode(parentNode);
  }

  haveChild(nodeId) {
    return (this.nodes[nodeId].childNodes.length>0 
      || (this.nodes[nodeId].leafNodes
      && this.nodes[nodeId].leafNodes.length>0));
  }

  /**
   * 处理节点展开收起按钮点击事件
   * @param  {[type]} nodeId [description]
   */
  toggleNode(nodeId) {
    if(!this.haveChild(nodeId)) return;
    var nodeDiv = this._jqObj.find(".tfp-tree-node[nodeId="+nodeId+"]");
    var childNodesDiv = this._jqObj.find(".tfp-tree-node-childs[nodeId="+nodeId+"]");
    let img = nodeDiv.find(".tfp-tree-node-icon").find("img").get(0);
    var iconColor = this.dataModel.deepBackground ? "" : "-dark";
    if(img.src.indexOf("images/toggle")>=0) {
      img.src = this.iconPath+"expand-"+this.iconColor+".png";
      childNodesDiv.hide();
    } else {
      img.src = this.iconPath+"toggle-"+this.iconColor+".png";
      childNodesDiv.show();
    }
  }

  getLeafNodeTextDivWidth(marginLeft) {
    //动态计算每个节点内文本框的最大宽度，以便文字过长时能自动出现省略号
    var divWidth = this._jqObj.get(0).offsetWidth;
    var nodeTextWidth = divWidth-marginLeft-16-22;
    if(this.dataModel.showLeafNodeCheckbox) nodeTextWidth -= 25;
    if(this.dataModel.showLeafNodeDeleteButton) nodeTextWidth -= 21;
    if(this.dataModel.showLeafNodeEditButton) nodeTextWidth -= 21;
    return nodeTextWidth;
  }

  /**
   * 创建页节点
   * @param  {[type]} parentDiv  [description]
   * @param  {[type]} node       [description]
   * @param  {[type]} marginLeft [description]
   */
  createLeafNode(parentDiv, node, marginLeft) {
    var nodeHtml = "<div class=\"tfp-tree-leaf-node\" nodeId=\""+node.id+"\">";
    if(this.dataModel.showLeafNodeCheckbox) {
      let margin = this.dataModel.showNodeCheckbox ? marginLeft+16 : marginLeft;
      let cbkType = this.dataModel.multiCheck ? "checkbox" : "radio";
      nodeHtml += "<div class=\"tfp-tree-node-checkbox\">"
        +"<input type=\""+cbkType+"\" value=\""+node.id
        +"\" style=\"margin-left: "+margin+"px;\"";
      if(cbkType=="radio") nodeHtml += " name=\""+this.id+"\"";
      nodeHtml += "></div>";
    } 
    nodeHtml += "<div class=\"tfp-tree-node-text\" style=\"";
      //+"width:"+this.getLeafNodeTextDivWidth(marginLeft)+"px;"
    if(!this.dataModel.deepBackground) nodeHtml += "color:#333333";
    nodeHtml += "\">"+node.name+"</div>";
    var iconColor = this.dataModel.deepBackground ? "" : "-dark";
    if(this.dataModel.showLeafNodeDeleteButton) {
      nodeHtml += "<div class=\"tfp-tree-node-button\">"
        +"<img src=\""+this.iconPath+"del-"+this.iconColor+".png\" title=\"删除\"></div>";
    }
    if(this.dataModel.showLeafNodeEditButton) {
      nodeHtml += "<div class=\"tfp-tree-node-button\">"
        +"<img src=\""+this.iconPath+"edit-"+this.iconColor+".png\" title=\"修改\"></div>";
    }
    nodeHtml += "</div>";
    parentDiv.append(nodeHtml);

    let that = this;
    let nodeDivNew = parentDiv.children(".tfp-tree-leaf-node").last();
    nodeDivNew.mouseover(function() {
      var bgColor = that.dataModel.deepBackground ? "#444444" : "#EEEEEE";
      //$(this).css("background-color", bgColor);
      $(this).find(".tfp-tree-node-button").css("display", "inline-flex");
    });
    nodeDivNew.mouseout(function() {
      //$(this).css("background-color", "");
      $(this).find(".tfp-tree-node-button").hide();
    });
    nodeDivNew.find(".tfp-tree-node-text").click(function() {
      if(that.dataModel.onClickLeafNode) {
        let eventFucName = that._tfp.getCptEventFuncName(that.dataModel.onClickLeafNode);
        eval(eventFucName+"('"+node.id+"')");
      }
    });
    nodeDivNew.find(".tfp-tree-node-checkbox").find("input").click(function() {
      that.checkLeafNode(node.id);
      if(that.dataModel.onClickLeafNode) {
        let eventFucName = that._tfp.getCptEventFuncName(that.dataModel.onClickLeafNode);
        eval(eventFucName+"('"+node.id+"')");
      }
    });
    nodeDivNew.find(".tfp-tree-node-button").find("img").click(function() {
      if($(this).attr("title")=="修改") {
        if(that.dataModel.onClickLeafNodeEditButton) {
          let eventFucName = that._tfp.getCptEventFuncName(that.dataModel.onClickLeafNodeEditButton);
          eval(eventFucName+"('"+node.id+"')");
        }
      } else {
        that.onClickDeleteLeafNodeButton(node.id);
      }
    });
  }

  checkLeafNode(nodeId) {
    var node = this.leafNodes[nodeId];
    var nodeDiv = this._jqObj.find(".tfp-tree-leaf-node[nodeId="+nodeId+"]");
    var cbk = nodeDiv.find(".tfp-tree-node-checkbox").find("input").get(0);
    if(cbk.checked) {
      if(this.dataModel.multiCheck) {
        if(this.dataModel.checkParentOnCheckChild) {
          var parentId = node.parentId;
          while(parentId!=this.dataModel.rootNodeParentId) {
            var parentNode = this.nodes[parentId];
            var parentDiv = this._jqObj.find(".tfp-tree-node[nodeId="+parentId+"]");
            var parentCbk = parentDiv.find(".tfp-tree-node-checkbox").find("input");
            if(parentCbk.length==0) break;
            parentCbk.get(0).checked = true;
            parentId = parentNode.parentId;
          }
        }
      } else {
        $(":radio").each(function(){
          if($(this).parent().parent().attr("nodeId")!=nodeId) $(this).get(0).checked = false;
        });
      }
    } else {
      if(this.dataModel.unCheckParentOnUnCheckAllChild) {
        this.unCheckParentNode(node);
      }
    }
  }

  onClickDeleteLeafNodeButton(nodeId) {
    if(!confirm("确定删除？")) return;
    if(this.dataModel.onClickLeafNodeDeleteButton) {
      let eventFucName = this._tfp.getCptEventFuncName(this.dataModel.onClickLeafNodeDeleteButton);
      eval(eventFucName+"('"+node.id+"')");
    } else if(this.dataModel.deleteLeafNodeService) {
      var args = {};
      args[this.dataModel.leafNodeIdFieldName] = nodeId;
      let serviceCpt = this._tfp.components[this.dataModel.deleteLeafNodeService];
      if(!serviceCpt) return;
      let that = this;
      serviceCpt.request(args, function(req, res) {
        if(res.code!=0) {
          that._tfp.showMsg(res.message);
          return;
        }
        that.deleteLeafNode(nodeId);
      });
    }
  }

  /**
   * 删除叶节点
   * @param  {[type]} nodeId [description]
   * @return {[type]}        [description]
   */
  deleteLeafNode(nodeId) {
    if(!(nodeId in this.leafNodes)) return;
    //删除节点对应的html元素
    var nodeDiv = this._jqObj.find(".tfp-tree-node[nodeId="+nodeId+"]");
    nodeDiv.remove();
    var node = this.leafNodes[nodeId];
    //解除与父节点的关联
    var parentNode = this.nodes[node.parentId];
    parentNode.leafNodes.deleteMember(node.id);
    //如果父节点没有其他子节点了，则应该修改父节点的图标为无法收起或展开
    if(parentNode.childNodes.length==0 && parentNode.leafNodes.length==0) {
      let iconColor = this.dataModel.deepBackground ? "" : "-dark";
      var parentDiv = this._jqObj.find(".tfp-tree-leaf-node[nodeId="+node.parentId+"]");
      parentDiv.find(".tfp-tree-node-icon").find("img").get(0).src = 
        this.iconPath+"dot-"+this.iconColor+".png";
    }
    //删除自己
    delete this.leafNodes[nodeId];
    node = null;
  }

  /**
   * 获得图标颜色
   * @return {[type]} [description]
   */
  getIconColor() {
    return this.dataModel.deepBackground ? "" : "-dark";
  }

  /**
   * 获得节点HTML元素
   * @param  {[type]} nodeId [description]
   * @return {[type]}        [description]
   */
  getNodeEl(nodeId) {
    return this._jqObj.find(".tfp-tree-node[nodeId="+nodeId+"]");
  }

  /**
   * 获得子节点容器HTML元素
   * @param  {[type]} nodeId [description]
   * @return {[type]}        [description]
   */
  getNodeChildsEl(nodeId) {
    return this._jqObj.find(".tfp-tree-node-childs[nodeId="+nodeId+"]");
  }

  /**
   * 获得叶节点HTML元素
   * @param  {[type]} nodeId [description]
   * @return {[type]}        [description]
   */
  getLeafNodeEl(nodeId) {
    return this._jqObj.find(".tfp-tree-leaf-node[nodeId="+nodeId+"]");
  }

  /**
   * 添加节点
   * @param {[type]} id       [description]
   * @param {[type]} name     [description]
   * @param {[type]} parentId [description]
   * @param {[type]} tag      [description]
   */
  addNode(id, name, parentId, tag) {
    var node = {};
    node.id = id;
    node.name = name;
    node.parentId = parentId;
    node.childNodes = [];
    if(this.dataModel.leafNodeDataMember) node.leafNodes = [];
    if(tag) node.tag = tag;
    this.nodes[node.id] = node;
    var marginLeft = 5;
    var parentDiv = $("#"+this.id);
    if(node.parentId!=this.dataModel.rootNodeParentId) {
      let parentEl = this.getNodeEl(node.parentId);
      marginLeft = this._tfp.getPixel(parentEl.css("margin-left"))+20;
      parentDiv = this.getNodeChildsEl(node.parentId);
      if(parentDiv.length==0) return;
      var parentNode = this.nodes[node.parentId];
      if(!parentNode) return;
      parentNode.childNodes.push(node.id);
      var parentIcon = parentEl.find(".tfp-tree-node-icon").find("img");
      if(parentIcon.get(0).src.indexOf("/dot")>0) {
        parentIcon.get(0).src = this.iconPath+"expand-"+this.iconColor+".png";
      }
    }
    this.createNode(parentDiv, node, marginLeft);
  }

  /**
   * 添加叶节点
   * @param {[type]} id       [description]
   * @param {[type]} name     [description]
   * @param {[type]} parentId [description]
   * @param {[type]} tag      [description]
   */
  addLeafNode(id, name, parentId, tag) {
    var node = {};
    node.id = id;
    node.name = name;
    node.parentId = parentId;
    if(tag) node.tag = tag;
    this.leafNodes[node.id] = node;
    var marginLeft = 5;
    var parentDiv = $("#"+this.id);
    if(node.parentId!=this.dataModel.rootNodeParentId) {
      let parentEl = this.getNodeEl(node.parentId);
      marginLeft = this._tfp.getPixel(parentEl.css("margin-left"))+20;
      parentDiv = this.getNodeChildsEl(node.parentId);
      if(parentDiv.length==0) return;
      var parentNode = this.nodes[node.parentId];
      if(!parentNode) return;
      parentNode.leafNodes.push(node.id);
      var parentIcon = parentEl.find(".tfp-tree-node-icon").find("img");
      if(parentIcon.get(0).src.indexOf("/dot")>0) {
        parentIcon.get(0).src = this.iconPath+"expand-"+this.iconColor+".png";
      }
    }
    this.createLeafNode(parentDiv, node, marginLeft);
  }

  /**
   * 更新节点
   * @param  {[type]} id       [description]
   * @param  {[type]} name     [description]
   * @param  {[type]} parentId [description]
   * @return {[type]}          [description]
   */
  updateNode(id, name, parentId) {
    var node = this.nodes[id];
    if(!node) return;
    var nodeDiv = this.getNodeEl(id);
    var childNodesDiv = this.getNodeChildsEl(id);
    var nodeIcon = nodeDiv.find(".tfp-tree-node-icon").find("img");
    if(node.name!=name) {
      node.name = name;
      nodeDiv.find(".tfp-tree-node-text").html(name);
    }
    //如果父节点变了，则需要重新关联
    if(node.parentId != parentId) {
      if(node.parentId!=this.dataModel.rootNodeParentId) {
        var parentOld = this.nodes[node.parentId];
        parentOld.childNodes.deleteMember(node.id);
        //如果老的父节点没有其他子节点了，则应该修改老父节点的图标为无法收起或展开
        if(parentOld.childNodes.length==0) {
          var parentOldEl = this.getNodeEl(node.parentId);
          var parentOldIcon = parentOldEl.find(".tfp-tree-node-icon").find("img");
          parentOldIcon.get(0).src = this.iconPath+"dot-"+this.iconColor+".png";
        }
      }
      var parentDiv = null;
      var parentMargin = 5;
      if(parentId==this.dataModel.rootNodeParentId) {
        parentDiv = $("#"+this.id);
      } else {
        parentDiv = this.getNodeEl(parentId);;
        var parentNewIconDiv = parentDiv.find(".tfp-tree-node-icon");
        parentMargin = this._tfp.getPixel(parentNewIconDiv.css("margin-left"))+20;
        this.setChildMargin(node, parentMargin);
        var parentNew = this.nodes[parentId];
        //如果新的父节点原来没有子节点，则应该修改新父节点的图标为展开
        if(parentNew.childNodes.length==0) {
          parentNewIconDiv.find("img").get(0).src = this.iconPath+"expand-"+this.iconColor+".png";
        }
        parentNew.childNodes.push(id);
      }
      nodeIcon.css("margin-left", parentMargin+"px");
      //nodeDiv.css("background-color", "");
      nodeDiv.find(".tfp-tree-node-button").hide();
      parentDiv.append(nodeDiv.clone());
      parentDiv.append(childNodesDiv.clone());
      node.parentId = parentId;
      nodeDiv.remove();
      childNodesDiv.remove();
    }
  }

  /**
   * 设置子节点左边距
   * @param {[type]} parent       [description]
   * @param {[type]} parentMargin [description]
   */
  setChildMargin(parent, parentMargin) {
    for(var i=0;i<parent.childNodes.length;i++) {
      var node = this.nodes[parent.childNodes[i]];
      var nodeDiv = this.getNodeEl(node.id);
      var nodeIconDiv = nodeDiv.find(".tfp-tree-node-icon");
      nodeIconDiv.css("margin-left", (parentMargin+20)+"px");
      this.setChildMargin(node, parentMargin+20);
    }
    if(!parent.leafNodes) return;
    for(var i=0;i<parent.leafNodes.length;i++) {
      var leafNode = this.leafNodes[parent.leafNodes[i]];
      var nodeDiv = this.getLeafNodeEl(leafNode.id);
      var nodeIconDiv = nodeDiv.find(".tfp-tree-node-icon");
      nodeIconDiv.css("margin-left", (parentMargin+20)+"px");
    }
  }

  /**
   * 获得选中的节点
   * @param  {[type]} getData [description]
   * @return {[type]}         [description]
   */
  getCheckedNodes(getData) {
    var nodes = [];
    let that = this;
    this._jqObj.find(".tfp-tree-node").each(function() {
      var input = $(this).first(".tfp-tree-node-checkbox").find("input");
      if(input.get(0).checked && input.val()!="") {
        var node = that.nodes[input.val()];
        if(getData) {
          nodes.push(node);
        } else {
          nodes.push({
            id: node.id,
            name: node.name,
            parentId: node.parentId
          });
        }
      }
    });
    return nodes;
  }

  /**
   * 获得选中的叶节点
   * @param  {[type]} getData [description]
   * @return {[type]}         [description]
   */
  getCheckedLeafNodes(getData) {
    var nodes = [];
    let that = this;
    this._jqObj.find(".tfp-tree-leaf-node").each(function() {
      var input = $(this).first(".tfp-tree-node-checkbox").find("input");
      if(input.get(0).checked && input.val()!="") {
        var node = that.leafNodes[input.val()];
        if(getData) {
          nodes.push(node);
        } else {
          nodes.push({
            id: node.id,
            name: node.name,
            parentId: node.parentId
          });
        }
      }
    });
    return nodes;
  }

  /**
   * 获得选中的节点值
   * @return {[type]} [description]
   */
  getCheckedNodesValue() {
    var values = "";
    this._jqObj.find(".tfp-tree-node").each(function() {
      var input = $(this).find(".tfp-tree-node-checkbox").find("input");
      if(input.get(0).checked && input.val()!="") {
        if(values!="") values += ",";
        values += input.val();
      }
    });
    return values;
  }

  /**
   * 获得选中的叶节点值
   * @return {[type]} [description]
   */
  getCheckedLeafNodesValue() {
    var values = "";
    this._jqObj.find(".tfp-tree-leaf-node").each(function() {
      var input = $(this).find(".tfp-tree-node-checkbox").find("input");
      if(input.get(0).checked && input.val()!="") {
        if(values!="") values += ",";
        values += input.val();
      }
    });
    return values;
  }

  initRuntime() {
    if(!this.dataModel.loadDataService) return;
    this.loadData();
  }
}