echarts 树状图

// 树结构
function creatTreeCharts(options) {

  // 获取参数
  options = this.getOptions(options);
  // 初始化树
  this.initTree(options);

}

creatTreeCharts.prototype.getOptions = function(options) {
  // 参数
  options = $.extend({}, {
    id: 'main',
    menuFloor: 'all',
    orient: 'LR'
  }, options || {});

  this.options = options;

  return options;
}

// 获取树状图数据
creatTreeCharts.prototype._getData = function() {
  let self = this;
  let arr = [];
  let paramJson = getEditParamJson(form);
  baseAjax(serverUrl + serviceInfo.LINKPATH002.url,
    JSON.stringify(paramJson), function (data) {
        if (data && "0" === data.resCode) {
          arr = data.rows;
        } else {
            if (data && data.resMsg != undefined) {
                $.msg.alert(data.resMsg);
            }
        }
    }, false);

    return arr;
}

// 初始化树结构
creatTreeCharts.prototype.initTree = function(options) {
  options = this.getOptions(options);
  let self = this;
  // 获取数据 
  let arr = deepClone(this._getData());
  let chartDom = document.getElementById(options.id);
  let myChart = echarts.init(chartDom);
  let option;
  let numArr = [];
  let color={
		color:"red"
  };
  
  if(!arr || arr.length == 0) {
    return;
  }

  // 销毁后重新渲染,避免多次渲染导致的一些列问题
  myChart.dispose();
  chartDom = document.getElementById(options.id);
  myChart = echarts.init(chartDom);
  
  // 处理数据
  if(options.menuFloor == 'all') {
    arr.forEach(function (datum, index) {
      datum.collapsed = false;
      if(datum.recursion != ''){
        datum.itemStyle = color;	
        datum.label = color;
      }
      numArr.push(datum);
    });
  }else{
    arr.forEach(function (datum, index) {
      if(datum.recursion != ''){
        datum.itemStyle = color;	
        datum.label = color;
      }
      datum.menuFloor == options.menuFloor && (datum.collapsed = true) && numArr.push(datum);
    });
  }
  
  // 构造数据
  let datas = deepClone(buildTree(numArr)[0]);   //层级数据
  let numLevel = deepLevel(datas);  //最深层级数
  
  // 赋值高度
  let autoHeight = numArr.length * 30; //每个节点高度设为30
  let autoWith = numLevel * 180; //每个节点高度设为30
  let opsition = {
    top: '10%',
    right: '15%'
  }
 
  if(numArr.length == 1){  //只有一个节点时,下载图片提示显示不全
    autoHeight = 50;
    if(options.orient == 'RL'){  //方向从右到左
      opsition = {
        top: '80%',
        right: '30%'
      }
    }
  }else if(numArr.length == 2) {
    opsition = {
      top: '10%',
      right: '20%'
    }
  }

  if(numLevel >= 5) {
    opsition = {
      top: '5%',
      right: '15%'
    }
    myChart.resize({height:autoHeight, width: autoWith}); 
  }else{
    myChart.resize({height:autoHeight}); 
  }
  



  this.optionChart = {
    tooltip: {   //提示信息
        trigger: 'item',
        triggerOn: 'mousemove',
        formatter: function (params) { 
          let { data } = params;
          let info = '<p>类型:'+data.typeName+'</p>'+'<p>编码:'+data.code+'</p>'+'<p>描述:'+data.desc+'</p>'+(data.recursion && data.recursion != ""? '<p>'+data.recursion+'</p>':"")+(data.bakMsg && data.bakMsg != ""?'<p>备注:'+data.bakMsg+'</p>': "");
          return info;
        },
    },
    toolbox: {
      show: true,
      right: 20,
      top: -5,
      feature: {
          mark: {show: true},
          dataView: {show: false, readOnly: false},
          restore: {show: true},
          saveAsImage: {show: true}
      }
    },
    series: [
        {
            type: 'tree',

            data: [datas],

            top: opsition.top,
            left: '10%',
            bottom: '1%',
            right: opsition.right,

            symbolSize: 7,

            orient: options.orient,  //控制方向,从右到左

            // initialTreeDept: -1,

            label: {
                position: 'top',
                verticalAlign: 'middle',
                align: 'middle',
                fontSize: 12,
            },

            leaves: {
                label: {
                    position: 'top',
                    verticalAlign: 'middle',
                    align: 'middle'
                }
            },

            emphasis: {
                focus: 'ancestor'  //祖先:ancestor ,后代:descendant 
            },

            expandAndCollapse: true,
            animationDuration: 550,
            animationDurationUpdate: 750
        }
      ]
    }
  
    // 渲染
    myChart.setOption(this.optionChart);
    option && myChart.setOption(option, true);

    // // 清除点击事件
    // myChart.off('click');

    // // 点击事件
    // myChart.on('click', function(params) {
    //   var name = params.data.name;//点击的节点的name
    //   alert('点击---'+name)
    // });
}

// 刷新
creatTreeCharts.prototype.refersh = function(options) {
  // let newOPtions = $.extend({}, this.options, options || {});
  // this.initTree(newOPtions);
  let chartDom = document.getElementById(this.options.id);
  let myChart = echarts.init(chartDom);
  myChart.setOption(this.optionChart, true);
}

creatTreeCharts.prototype.reverse = function() {
  let newOPtions = this.options;
  newOPtions.orient = newOPtions.orient == 'RL'? 'LR': 'RL';
  this.initTree(newOPtions);
}

function buildTree (arr) {
  let temp = {}
  let tree = {}
  // 数组转 键值对
  arr.forEach(item => {
    item.name = item.code+'('+item.typeName+')';
    // item.children = []
    temp[item.id] = item
  })

  let tempKeys = Object.keys(temp)

  tempKeys.forEach(key => {
    // 获取当前项
    let item = temp[key]
    // 当前项 pId
    let _itemPId = item.pid
    // 获取父级项
    let parentItemByPid = temp[_itemPId]
    if (parentItemByPid) {
      if (!parentItemByPid.children) {
        parentItemByPid.children = [];
      }

      parentItemByPid.children.push(item)
    } else {
      tree[item.id] = item
    }
  })
  // 对象转数组并返回
  return Object.keys(tree).map(key => tree[key])
}


function deepLevel(data) {
  var num = 0;
  function recursion(obj,k) {
      num = Math.max(num,k);
      // console.log(k);
      if (obj.children)
          obj.children.forEach(function(v, i){
              recursion(v,k+1);
          });
  }
  recursion(data,1);
  // console.log("最深层级数"+num);
  return num;
}


// 深拷贝
function deepClone(obj) {
  let objClone = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === "object") {
      for (key in obj) {
          if (obj.hasOwnProperty(key)) {
              //判断ojb子元素是否为对象,如果是,递归复制
              if (obj[key] && typeof obj[key] === "object") {
                  objClone[key] = deepClone(obj[key]);
              } else {
                  //如果不是,简单复制
                  objClone[key] = obj[key];
              }
          }
      }
  }
  return objClone;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值