hcong
2024-11-08 d7d7da5c09340eafcd2e2c672e6b2c001a4cc0be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// 递归的获取obj中的prop属性 解决有时需要取val.obj.prop的情况
function getPropValueLoop(obj, prop) {
  if (typeof prop !== 'string') {
    return obj;
  }
  const props = prop.split('.');
  let result = obj;
  props.forEach((item) => {
    result = result[item];
  });
  return result;
}
function getCount(array, element) {
  let count = 0;
  array.forEach((e) => {
    if (e == element) {
      count++;
    }
  });
  return count;
}
export default {
  getPieChartByDataAndProp(data, prop, label) {
    let chartData = []
    function addNewName(name) {
      chartData.push({
        name: name,
        value: 1
      })
    }
    function addCount(name) {
      chartData.map(item=>{
        if (item.name === name) {
          item.value++
        }
      })
    }
    function hasThisName(name) {
      for (let index = 0; index < chartData.length; index++) {
        const element = chartData[index];
        if (element.name === name) {
          return true
        }
      }
      return false
    }
 
    data
      .map((item) => {
        const name = getPropValueLoop(item, prop) 
        if (hasThisName(name)) {
          addCount(name)
        }else {
          addNewName(name)
        }
      })
 
    return {
      title: {
        text: label,
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: chartData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
  },
  getChartByDataAndProp(data, prop, label, chartType = 'bar') {
    let series = data.map((item) => getPropValueLoop(item, prop));
    const option = {
      title: {
        text: label //设置标题
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      xAxis: {
        type: 'category',
        data: Array.from(new Set(series)),
        axisLabel: {
          rotate: 45, // 旋转标签,避免重叠
          // 或者
          interval: 0 // 显示所有标签,可能导致重叠,根据需求调整
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: Array.from(new Set(series)).map((item) =>
            getCount(series, item)
          ),
          type: chartType,
          smooth: true
        }
      ]
    };
    return option;
  }
};