summaryrefslogtreecommitdiff
path: root/nezha-fronted/src/components/chart/panelChart.vue
blob: f10a03d8e03614684990d933523be89c7478370a (plain)
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
<template>
  <!-- chart外层箱子 -->
  <div
    :class="{
      'panel-chart--fullscreen': isFullscreen,
    }"
    class="panel-chart"
    :id="isFullscreen ? ('chart-screen-' + chartInfo.id ) : ('chart-local-' + chartInfo.id)"
    v-my-loading="loading"
  >
    <!-- title和工具栏,支持浮动 -->
    <chart-header
      v-if="!isFullscreen&&showHeader"
      :is-group="isGroup(chartInfo.type)"
      :isExportHtml="isExportHtml"
      :isError="isError"
      :from="from"
      :nowTimeType="nowTimeType"
      :chartData="chartData"
      :chart-info="chartInfo"
      :showAllData.sync="showAllData"
      :allDataLength="allDataLength"
      :hiddenText="hiddenText"
      @unitChange="unitChange"
      @loadMore="loadMore"
      @edit-chart="$emit('edit-chart', chartInfo)"
      @refresh="refresh"
      @sync="chartSync"
      :showTool="showTool"
      @downloadCSV="beforeDownloadCSV"
      @groupShow="groupShow"
      @showFullscreen="showFullscreen"
      @changeStack="changeStack"
    ></chart-header>
    <!-- 全屏的header -->
    <chart-screen-header
      v-if="isFullscreen"
      :isPreview="isPreview"
      :is-group="isGroup(chartInfo.type)"
      :isExportHtml="isExportHtml"
      :isError="isError"
      :from="from"
      :nowTimeType="nowTimeType"
      :chartData="chartData"
      :chart-info="chartInfo"
      :showAllData.sync="showAllData"
      :allDataLength="allDataLength"
      @unitChange="unitChange"
      @saveChart="saveChart"
      @loadMore="loadMore"
      @refresh="refresh"
      @dateChange="dateChange"
      @close="showFullscreen"
      @changeStack="changeStack"
    ></chart-screen-header>
    <!-- chart -->
    <!-- 数据查询后传入chart组件,chart组件内不查询,只根据接传递的数据来渲染 -->
    <chart
      ref="chart"
      :globalVariables="globalVariables"
      :chart-data="chartData"
      :chart-info="chartInfo"
      :panelLock="panelLock"
      :isExportHtml="isExportHtml"
      :filter="filter"
      :from="from"
      :showTool="showTool"
      @refreshLogs="refreshLogs"
      :show-header="showHeader"
      :isError="isError"
      :loading="loading"
      :minusTime="minusTime"
      :multipleTime="multipleTime"
      :isFullscreen="isFullscreen"
      :showAllData="showAllData"
      v-if="(!isGroup(chartInfo.type) || !chartInfo.param.collapse) && snapshotShow"
    ></chart>
  </div>
</template>

<script>
import chartHeader from '@/components/chart/chartHeader'
import ChartScreenHeader from '@/components/chart/ChartScreenHeader'
import chart from '@/components/chart/chart'
import { isStat, isTimeSeries, getGroupHeight, isGroup } from './chart/tools'
import { chartType, fromRoute } from '@/components/common/js/constants'
import bus from '@/libs/bus'
import axios from 'axios'
import chartTempData from '@/components/chart/chartTempData'
import assetInfoData from '@/components/chart/assetInfoData'
import endpointInfoData from '@/components/chart/endpointInfoData'
import logsData from '@/components/chart/logsData'
import lodash from 'lodash'
import globalVariablesMixin from '@/components/common/mixin/globalVariables'
export default {
  // 该组件用于获取chart的具体数据
  name: 'panelChart',
  mixins: [globalVariablesMixin],
  components: {
    chartHeader,
    chart,
    ChartScreenHeader
  },
  props: {
    chartInfo: Object, // 其中的param json串已转化为对象  // 当前chart的具体信息
    timeRange: Array, // 时间范围
    isFullscreen: Boolean, // 是否全屏
    panelLock: Boolean, // 是否被锁定
    chartDetailInfo: Object,
    from: String, // 使用该组件的位置
    filter: {},
    showHeader: { // 是否显示header
      type: Boolean,
      default: true
    },
    nowTimeType: {
      type: Object
    },
    isExportHtml: { // 是否是导出的html
      type: Boolean,
      default: false
    },
    dataJson: { // 导出的html的数据
      type: Object
    },
    variablesInit: {
      type: Boolean,
      default: true
    },
    showTool: {
      type: Boolean,
      default: true
    },
    hiddenText: { // 隐藏图表的悬浮文字
      type: String
    },
    isPreview: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      chartData: [], // 当前chart的数据
      loading: true,
      isError: false,
      multipleTime: false, // 是否开启对比
      minusTime: '', // 是否开启对比相差的时间
      showAllData: false, // 是否显示所有legend
      allDataLength: 0,
      severityData: this.$store.getters.severityData, // 告警级别的数据
      severityDataWeight: this.$store.getters.severityDataWeight,
      myVariables: [], // 添加当前使用的变量 用于判断是否需要重新加载
      snapshotShow: true
      // isExportData: false
    }
  },
  computed: {
    headerH () { // 50px header所包含的高
      return this.$store.getters.getHeaderH
    },
    headerHPadding () { // 50px header + padding 主要用于展开的空group
      return this.$store.getters.getHeaderHPadding
    },
    variablesArr () {
      return this.$store.getters.getVariablesArr
    }
  },
  methods: {
    isGroup,
    variablesHandle (searchTime) {
      this.setGlobalVariablesValue(searchTime)
      this.myVariables = []
      // eslint-disable-next-line vue/no-mutating-props
      this.chartInfo.elements = this.$lodash.cloneDeep(this.chartInfo.oldElements.filter(item => item.state)) // 处理不显示的表达式
      // eslint-disable-next-line vue/no-mutating-props
      this.chartInfo.elements = this.chartInfo.elements.map((item, index) => { // 处理表达式的变量
        // 全局变量替换
        item.expression = this.globalVariablesReplace(item.expression)
        // group图表设置repeat的表达式替换
        if (this.chartInfo.repeatVariable) {
          item.expression = this.variablesReplaceRepeat(item.expression)
        }
        const variables = this.variablesReplace((item.expression))
        this.myVariables.push(variables)
        return {
          ...item,
          expression: variables
        }
      })
    },
    dateChange (filter, multipleTime) {
      this.loading = true
      // TODO assetInfo、endpointInfo、echarts等进行不同的处理
      let startTime = bus.formateTimeToTime(filter.start_time)
      let endTime = bus.formateTimeToTime(filter.end_time)
      const step = bus.getStep(startTime, endTime)
      startTime = this.$stringTimeParseToUnix(startTime)
      endTime = this.$stringTimeParseToUnix(endTime)
      this.variablesHandle([filter.start_time, filter.end_time])
      const elements = this.chartInfo.elements || []
      if (multipleTime.length) {
        const minusTime = (new Date(bus.formateTimeToTime(filter.start_time)).getTime() - new Date(bus.formateTimeToTime(multipleTime[0])).getTime())
        this.minusTime = minusTime
        this.multipleTime = true
      } else {
        this.minusTime = ''
        this.multipleTime = false
      }
      if (this.chartInfo.type === 'diagram') {
        this.chartInfo.loaded && this.query(elements, startTime, endTime, step, '', true)
      } else {
        this.chartInfo.loaded && this.query(elements, startTime, endTime, step)
      }
    },
    // 参数 isRefresh 标识是否是刷新操作
    getChartData (isRefresh, params) { // 获取chart的数据前的准备 主要用于处理时间参数
      if (!this.variablesInit) { // 变量未加载完成 不请求数据
        return
      }
      this.chartData = window.dataJson ? this.chartData : []
      this.loading = true
      // TODO assetInfo、endpointInfo、echarts等进行不同的处理
      let startTime = ''
      let endTime = ''
      // todo 刷新 需要判断是否是相对时间
      if (isRefresh || this.isFullscreen) { // 刷新则视情况更新时间范围
        const now = new Date(bus.computeTimezone(new Date().getTime()))
        const origin = new Date(bus.timeFormate(bus.formateTimeToTime(this.timeRange[1]), 'YYYY-MM-DD HH:mm:ss'))
        const numInterval = now.getTime() - origin.getTime()
        let nowTimeType = this.nowTimeType
        console.log(nowTimeType)
        if (!nowTimeType) {
          nowTimeType = {
            value: 1
          }
        }
        if (numInterval >= 15000 && nowTimeType.value !== -1) { // 大于1分钟,则start、end均往后移numInterval,否则时间不变
          startTime = bus.getNewTime(bus.formateTimeToTime(this.timeRange[0]), numInterval, 'YYYY-MM-DD HH:mm:ss')
          endTime = bus.timeFormate(now, 'YYYY-MM-DD HH:mm:ss')
        } else {
          startTime = bus.formateTimeToTime(this.timeRange[0])
          endTime = bus.formateTimeToTime(this.timeRange[1])
        }
      } else {
        startTime = bus.formateTimeToTime(this.timeRange[0])
        endTime = bus.formateTimeToTime(this.timeRange[1])
      }
      const step = bus.getStep(startTime, endTime)
      startTime = this.$stringTimeParseToUnix(startTime)
      endTime = this.$stringTimeParseToUnix(endTime)
      if (!this.chartInfo.oldElements) { // 创建一个备份 用于判断变量替换 能拿到原本变量的位置
        this.chartInfo.oldElements = this.chartInfo.elements ? JSON.parse(JSON.stringify(this.chartInfo.elements)) : []
      }
      this.variablesHandle([startTime * 1000, endTime * 1000])
      const elements = this.chartInfo.elements || []
      if (this.isExportHtml) {
        this.chartInfo.loaded && this.queryData(elements, startTime, endTime, step, params, isRefresh)
        return
      }
      this.chartInfo.loaded && this.query(elements, startTime, endTime, step, params, isRefresh)
    },
    getIemStep (element, step) {
      let myStep = step
      if (element.step) {
        myStep = element.step + 's'
      }
      return myStep
    },
    query (elements, startTime, endTime, step, params, isRefresh) { // 获取chart的数据
      this.isError = false
      this.allDataLength = 0
      // this.chartData = this.chartInfo.chartData
      try {
        switch (this.chartInfo.datasource) {
          case 'metrics':
          case 'logs': {
            if (this.from === fromRoute.chartTemp || this.from === fromRoute.dashboardTemp || this.from === fromRoute.integration) {
              setTimeout(() => {
                this.chartData = []
                elements.forEach(item => {
                  const data = this.$lodash.cloneDeep(chartTempData.data.result)
                  data[0].elements = item
                  this.chartData.push(data)
                })
                this.loading = false
              }, 100)
              return
            }
            let urlPre = ''
            if (this.chartInfo.datasource === 'metrics') {
              urlPre += '/prom'
            } else if (this.chartInfo.datasource === 'logs') {
              urlPre += '/logs/loki'
            }
            let requests = elements.map((element) => {
              const myStep = this.getIemStep(element, step)
              if (this.from === fromRoute.chartTemp || this.from === fromRoute.dashboardTemp) {
                return chartTempData
              }
              let queryStr = 'query_range'
              let query = ''
              if (element.queryType == 2) {
                queryStr = 'query_instant'
                query = `${urlPre}/api/v1/${queryStr}?time=${endTime}`
              } else {
                query = `${urlPre}/api/v1/${queryStr}?start=${startTime}&end=${endTime}&step=${myStep}`
              }
              if (isTimeSeries(this.chartInfo.type)) {
                let nullType = this.chartInfo.param.nullType || 'null'
                nullType = (nullType === 'connected' ? 'null' : nullType)
                query += `&nullType=${nullType}`
              }
              if (element.filter) {
                query += `&filter=${element.filter}`
              }
              if (this.chartInfo.datasource === 'logs') {
                query += '&format=1'
              }
              if (this.chartInfo.type === 'log') {
                if (!params || params.descending) {
                  this.chartInfo.descending = true
                  query += '&direction=backward'
                } else {
                  this.chartInfo.descending = false
                  query += '&direction=forward'
                }
                const limit = this.$lodash.get(this.chartInfo, 'param.limit', 100)
                query += `&limit=${limit}`
              }
              query += `&query=${encodeURIComponent(this.variablesReplace(element.expression))}`
              return this.$get(query)
            })
            if (this.multipleTime) {
              const multipleRequests = elements.map((element) => {
                const myStep = this.getIemStep(element, step)
                if (this.from === fromRoute.chartTemp || this.from === fromRoute.dashboardTemp) {
                  return chartTempData
                }
                let query = `${urlPre}/api/v1/query_range?start=${startTime - this.minusTime / 1000}&end=${endTime - this.minusTime / 1000}&step=${myStep}`
                if (isTimeSeries(this.chartInfo.type)) {
                  let nullType = this.chartInfo.param.nullType || 'null'
                  nullType = (nullType === 'connected' ? 'null' : nullType)
                  query += `&nullType=${nullType}`
                }
                if (element.filter) {
                  query += `&filter=${element.filter}`
                }
                if (this.chartInfo.datasource === 'logs') {
                  query += '&format=1'
                }
                query += `&query=${encodeURIComponent(element.expression)}`
                return this.$get(query)
              })
              requests = requests.concat(multipleRequests)
            }

            // stat图表开启对比
            if (isStat(this.chartInfo.type)) {
              let comparisonSt // 比较开始时间
              let comparisonEt // 比较结束时间
              const oneDay = 86400
              switch (this.chartInfo.param.comparison) {
                case 'none': {
                  break
                }
                case 'hour': { // 比较一小时前
                  comparisonSt = startTime - 3600
                  comparisonEt = endTime - 3600
                  break
                }
                case 'day': { // 比较一天前
                  comparisonSt = startTime - oneDay
                  comparisonEt = endTime - oneDay
                  break
                }
                case 'week': { // 比较一星期前
                  comparisonSt = startTime - (oneDay * 7)
                  comparisonEt = endTime - (oneDay * 7)
                  break
                }
                case 'month': { // 比较一个月前
                  comparisonSt = startTime - (oneDay * 30)
                  comparisonEt = endTime - (oneDay * 30)
                  break
                }
              }
              if (comparisonSt && comparisonEt) {
                const comparisonRequests = elements.map((element) => {
                  const myStep = this.getIemStep(element, step)
                  let query = `${urlPre}/api/v1/query_range?start=${comparisonSt}&end=${comparisonEt}&step=${myStep}`
                  if (element.filter) {
                    query += `&filter=${element.filter}`
                  }
                  if (this.chartInfo.datasource === 'logs') {
                    query += '&format=1'
                  }
                  query += `&query=${encodeURIComponent(element.expression)}`
                  return this.$get(query)
                })
                requests = requests.concat(comparisonRequests)
              }
            }

            const chartData = []
            axios.all(requests).then((res) => {
              res.forEach((r, rIndex) => {
                if (rIndex < elements.length) {
                  if (r.status === 'success') {
                    r.data.result.forEach(item => {
                      item.elements = elements[rIndex]
                      this.allDataLength++
                    })
                    chartData.push(r.data.result)
                  } else {
                    chartData.push({ error: r.msg || r.error || r })
                    this.isError = true
                  }
                } else if (isTimeSeries(this.chartInfo.type)) {
                  if (r.status === 'success') {
                    r.data.result.forEach(item => {
                      item.elements = elements[rIndex - elements.length]
                      this.allDataLength++
                      item.values.forEach(values => {
                        values[0] = values[0] + this.minusTime / 1000
                      })
                    })
                    chartData.push(r.data.result)
                  } else {
                    chartData.push({ error: r.msg || r.error || r })
                    this.isError = true
                  }
                } else if (isStat(this.chartInfo.type)) { // stat图表开启对比
                  if (r.status === 'success') {
                    r.data.result.forEach(item => {
                      item.elements = elements[rIndex - elements.length]
                      this.allDataLength++
                    })
                    chartData.push(r.data.result)
                  } else {
                    chartData.push({ error: r.msg || r.error || r })
                    this.isError = true
                  }
                }
              })
              this.chartData = JSON.parse(JSON.stringify(chartData))
              if (this.chartInfo.type === 'log') {
                this.logChartDataFormat()
              }
            }).catch(res => {
              // console.info(res)
            }).finally(() => {
              this.loading = false
            })
            break
          }
          case 'system': {
            this.chartInfo.elements = this.chartInfo.param.datasource
            if (this.from === fromRoute.chartTemp || this.from === fromRoute.dashboardTemp) {
              let tempData
              if (this.chartInfo.type === 'assetInfo') {
                tempData = this.$lodash.cloneDeep(assetInfoData.data)
              } else if (this.chartInfo.type === 'endpointInfo') {
                tempData = this.$lodash.cloneDeep(endpointInfoData.data)
              } else {
                tempData = [chartTempData.data.result]
              }
              setTimeout(() => {
                this.chartData = tempData
                this.loading = false
              }, 100)
              return
            }
            // assetInfo or endpointInfo
            let linkId = ''
            if (this.from == 'dashboard') {
              linkId = this.chartInfo.varId
            } else {
              linkId = this.chartDetailInfo && this.chartDetailInfo.id
            }
            if (this.chartInfo.type === 'assetInfo') {
              this.$get('asset/asset/' + linkId + '?feature=1').then(res => {
                this.chartData = res.data
                this.loading = false
              })
              break
            }
            if (this.chartInfo.type === 'endpointInfo') {
              this.$get('monitor/endpoint/' + linkId).then(res => {
                this.chartData = res.data
                this.loading = false
              })
              break
            }
            const q = {
              type: this.chartInfo.param.datasource[0].type,
              group: this.chartInfo.param.datasource[0].group,
              select: [this.chartInfo.param.datasource[0].select],
              limit: this.chartInfo.param.datasource[0].limit,
              sort: this.chartInfo.param.datasource[0].sort,
              filter: this.chartInfo.param.datasource[0].filter ? this.chartInfo.param.datasource[0].filter.filter(item => item.value) : []
            }
            const chartData = []
            const params = {
              t: this.chartInfo.id,
              q: encodeURIComponent(JSON.stringify(q)),
              stat: startTime,
              end: endTime,
              resultType: 'matrix'
            }
            this.$get('/stat', params).then(res => {
              if (res.code === 200) {
                chartData.push(res.data.result)
              } else {
                chartData.push({ error: res.msg || res.error || res })
                this.isError = true
              }
              this.chartData = JSON.parse(JSON.stringify(chartData))
              this.loading = false
            })
            // this.sendAjax('/stat', params).then(res => {
            //   if (res.code === 200) {
            //     chartData.push(res.data.result)
            //   } else {
            //     chartData.push({ error: res.msg || res.error || res })
            //     this.isError = true
            //   }
            //   this.chartData = chartData
            //   this.loading = false
            // })
            break
          }
          case 'misc': {
            this.loading = false
            setTimeout(() => {
              this.loading = false
            })
            if (this.chartInfo.type === 'hexagon') {
              this.getHexagonFigureData().then(res => {
                this.chartData = JSON.parse(JSON.stringify(res))
              }).finally(() => {
                this.loading = false
              })
            }
            if (this.chartInfo.type === 'diagram') {
              this.chartData = [this.chartInfo.param.topo]
              if (!this.chartInfo.param.topo || !this.chartInfo.param.topo.pens.length) {
                this.chartData = []
              } else {
                this.chartData = [this.chartInfo.param.topo]
              }
              if (isRefresh) {
                const dom = this.$refs.chart.$refs['chart' + this.chartInfo.id]
                if (dom) {
                  dom.refresh([startTime * 1000, endTime * 1000])
                }
              }
            }
            if (this.chartInfo.type === 'group') {
              this.chartData = lodash.get(this, 'chartInfo.children', [])
              this.loading = false
              this.groupInit()
            }
            if (this.chartInfo.type === 'topology') {
              this.chartData = ['topology']
            }
            if (this.chartInfo.type === 'map') {
              this.chartData = ['map']
            }
            break
          }
          case 'topology': {
            this.loading = true
            const params = {
              type: this.chartInfo.linkType,
              id: this.chartInfo.id
            }
            this.$get('/stat/rel', params).then(res => {
              this.loading = false
              const parentId = this.chartInfo.linkType + '-' + this.chartInfo.id
              res.data.nodes.forEach(item => {
                item.parentId = [parentId]
                item.highlight = true
                item.x = 0
                item.y = 0
                if (item.id === parentId) {
                  item.hasChildren = true
                  item.parentId = []
                  item.fx = 0
                  item.fy = 0
                } else {
                  item.hasChildren = false
                }
                item.radius = this.getRadius(item) // 需要计算 分三级
                item.color = this.getColor(item) // 需要计算 分三级
              })
              res.data.links.forEach(item => {
                item.id = item.source + '-' + item.target
              })
              this.chartData = JSON.parse(JSON.stringify([res.data]))
            })
            break
          }
        }
      } catch (e) {
        this.loading = false
      }
    },
    queryData (elements, startTime, endTime, step, params) { // 获取chart的数据主要用于导出的html
      this.isError = false
      this.allDataLength = 0
      // this.chartData = this.chartInfo.chartData
      try {
        switch (this.chartInfo.datasource) {
          case 'metrics':
          case 'logs': {
            this.chartData = []
            elements.forEach((element, index) => {
              const data = this.dataJson[this.chartInfo.id + '_' + index].data.result.map(item => {
                this.allDataLength++
                return {
                  ...item,
                  elements: element
                }
              })
              this.chartData.push(data)
            })
            break
          }
          case 'system': {
            this.chartInfo.elements = this.chartInfo.param.datasource
            this.chartData = []
            if (this.chartInfo.type === 'assetInfo' || this.chartInfo.type === 'endpointInfo') {
              this.chartData = this.dataJson[this.chartInfo.id + '_' + 0].data
              this.loading = false
              break
            }
            this.chartData.push(this.dataJson[this.chartInfo.id + '_' + 0].result)
            break
          }
          case 'misc': {
            this.loading = false
            setTimeout(() => {
              this.loading = false
            })
            if (this.chartInfo.type === 'hexagon') {
              this.getHexagonFigureData().then(res => {
                this.chartData = JSON.parse(JSON.stringify(res))
              }).finally(() => {
                this.loading = false
              })
            }
            if (this.chartInfo.type === 'diagram') {
              this.chartData = [this.chartInfo.param.topo]
              if (!this.chartInfo.param.topo || !this.chartInfo.param.topo.pens.length) {
                this.chartData = []
              } else {
                this.chartData = [this.chartInfo.param.topo]
              }
            }
            if (this.chartInfo.type === 'group') {
              this.chartData = lodash.get(this, 'chartInfo.children', [])
              this.loading = false
              this.groupInit()
            }
            if (this.chartInfo.type === 'topology') {
              this.chartData = ['topology']
            }
            if (this.chartInfo.type === 'map') {
              this.chartData = ['map']
            }
            break
          }
          case 'topology': {
            this.loading = true
            const params = {
              type: this.chartInfo.linkType,
              id: this.chartInfo.id
            }
            this.$get('/stat/rel', params).then(res => {
              this.loading = false
              const parentId = this.chartInfo.linkType + '-' + this.chartInfo.id
              res.data.nodes.forEach(item => {
                item.parentId = [parentId]
                item.highlight = true
                item.x = 0
                item.y = 0
                if (item.id === parentId) {
                  item.hasChildren = true
                  item.parentId = []
                  item.fx = 0
                  item.fy = 0
                } else {
                  item.hasChildren = false
                }
                item.radius = this.getRadius(item) // 需要计算 分三级
                item.color = this.getColor(item) // 需要计算 分三级
              })
              res.data.links.forEach(item => {
                item.id = item.source + '-' + item.target
              })
              this.chartData = JSON.parse(JSON.stringify([res.data]))
            })
            break
          }
        }
        if (this.chartInfo.type === 'log') {
          this.logChartDataFormat()
        }
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    variablesReplace (expression) {
      let str = expression
      let confirmReg = []
      this.variablesArr.forEach(item => {
        const reg = '$' + item.name // 后续需要考虑 item,name 使用特殊字符的问题
        const index = expression.indexOf(reg)
        if (index !== -1) {
          confirmReg.push(item)
        }
      })
      confirmReg = this.$lodash.orderBy(confirmReg, function (item) { // 根据 匹配的name的长度排序 避免匹配的 $a 没匹配 $asset的问题
        return item.name.length
      }, 'desc')
      if (confirmReg.length) {
        confirmReg.forEach(item => {
          const reg = new RegExp('\\$' + item.name, 'g') // 后续需要考虑 item,name 使用特殊字符的问题
          str = str.replace(reg, item.checked.map(label => label.replace(/\\"/g, '"').replace(/\\'/g, "'")).join('|'))
        })
      }
      return str
    },
    // group图表repeat 表达式替换
    variablesReplaceRepeat (expression) {
      let str = expression
      const variable = this.chartInfo.repeatVariable
      const reg = new RegExp('\\$' + variable, 'g')
      str = str.replace(reg, this.chartInfo.repeatValue.replace(/\\"/g, '"').replace(/\\'/g, "'"))
      return str
    },
    getHexagonFigureData () {
      return new Promise(resolve => {
        this.$get('stat/alertMessage/topN', { size: 48, dimension: 'module' }).then(response => {
          if (response.code === 200) {
            const moduleData = response.data.list
            moduleData.sort((a, b) => b.alertNum - a.alertNum)
            const alertTopModules = moduleData.slice(0, 48)
            const requests = alertTopModules.map(a => axios.get(`stat/alertMessage/severity?moduleId=${a.id}`))
            const moduleStateData = []
            axios.all(requests).then(result => {
              result.forEach((alert, i) => {
                const severityData = {}
                alert.data.data.list && alert.data.data.list.forEach(a => {
                  severityData[a.name] = a.num
                })
                !severityData.P1 && (severityData.P1 = 0)
                !severityData.P2 && (severityData.P2 = 0)
                !severityData.P3 && (severityData.P3 = 0)
                moduleStateData.push({ ...alertTopModules[i], alert: [severityData] })
              })
              resolve(moduleStateData)
            })
          }
        })
      })
    },
    resize () {
      this.$refs.chart && this.$refs.chart.resize()
    },
    refresh () {
      this.getChartData(true)
    },
    refreshLogs (params) {
      this.getChartData(true, params)
    },
    logChartDataFormat () {
      this.chartData.forEach((item, index) => {
        const elements = this.chartInfo.elements[index]
        item.forEach(row => {
          row.elements = elements
        })
      })
    },
    groupInit () {
      const height = getGroupHeight(this.chartInfo.children || [])
      if (this.chartInfo.param.collapse) {
        this.chartInfo.height = this.headerH
        this.chartInfo.h = this.headerH
        bus.$emit('groupMove', '', '', true)
        return
      }
      if (this.chartInfo.children && this.chartInfo.children.length) {
        this.chartInfo.height = height + this.headerHPadding
        this.chartInfo.h = height + this.headerHPadding
      } else {
        this.chartInfo.height = height
        this.chartInfo.h = height
      }
    },
    showFullscreen (show) {
      this.$emit('showFullscreen', show, this.chartInfo)
    },
    groupShow (flag) {
      if (this.chartInfo.type === 'group' && !flag) {
        this.chartData = lodash.get(this, 'chartInfo.children', [])
      }
      if (!this.chartInfo.param) {
        this.chartInfo.param = {}
      }
      this.chartInfo.param.collapse = flag
      const chartGroupExpand = localStorage.getItem('nz-chart-group-expand') ? JSON.parse(localStorage.getItem('nz-chart-group-expand')) : {}
      if (this.chartInfo.id && this.chartInfo.id > 0) {
        chartGroupExpand[this.chartInfo.id] = this.chartInfo.param.collapse
        localStorage.setItem('nz-chart-group-expand', JSON.stringify(chartGroupExpand))
      }
      this.groupInit()
      bus.$emit('groupMove', '', '', true)
      this.$emit('groupShow', this.chartInfo)
    },
    showMultiple (type) {
      switch (type) {
        case 'line' :
        case 'area' :
        case 'point' :
          return true
        default: return false
      }
    },
    loadMore () {
      this.showAllData = true
      this.$nextTick(() => {
        this.$refs.chart && this.$refs.chart.$refs['chart' + this.chartInfo.id].initChart()
      })
    },
    changeStack () {
      this.$nextTick(() => {
        this.$refs.chart && this.$refs.chart.$refs['chart' + this.chartInfo.id].changeStack()
      })
    },
    unitChange (val) {
      this.$emit('update:chartInfo', 'unit', val)
      this.chartInfo.unit = val
      this.$nextTick(() => {
        this.$refs.chart && this.$refs.chart.$refs['chart' + this.chartInfo.id].initChart()
      })
    },
    saveChart () {
      this.$emit('saveChart', this.chartInfo)
    },
    chartSync () {
      this.loading = true
      this.$post('visual/dashboard/chart/syncTmpl', { ids: [this.chartInfo.id] }).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t('tip.syncSuccess'))
          this.$emit('refreshPanel')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    getRadius (item) {
      let sum = 0
      item.alert && item.alert.forEach(alert => {
        sum += Number(alert.num)
      })
      if (sum === 0) {
        return 14
      } else if (sum <= 10) {
        return 20
      } else {
        return 27
      }
    },
    getColor (item) {
      // const arr = []
      let color = ''
      // item.alert && item.alert.forEach(alert => {
      //   arr.push(alert.priority)
      // })
      this.severityDataWeight.forEach(severity => {
        const num = item.alert.find(alert => alert.priority === severity.name)
        if (num && !color && num.num > 0) {
          color = severity.color
        }
      })
      if (!color) {
        color = '#23bf9a'
      }
      return color
    },
    sendAjax (url, params) {
      // 构造表单数据
      return new Promise(resolve => {
        let nowUrl = url
        Object.keys(params).forEach((key, index) => {
          if (index == 0) {
            nowUrl += '?' + key + '=' + params[key]
          } else {
            nowUrl += '&' + key + '=' + params[key]
          }
        })
        const formData = new FormData()
        formData.append('username', 'johndoe')
        formData.append('id', 123456)
        // 创建xhr对象
        const xhr = new XMLHttpRequest()
        // 设置xhr请求的超时时间
        xhr.timeout = 3000
        // 设置响应返回的数据格式
        xhr.responseType = ''
        // 创建一个 post 请求,采用异步
        xhr.open('get', 'http://192.168.44.100/' + nowUrl, true)
        xhr.setRequestHeader('Authorization', localStorage.getItem('nz-token'))
        // 注册相关事件回调处理函数
        xhr.onload = function (e) {
          if (this.status == 200 || this.status == 304) {
            // alert(this.responseText)
            resolve(JSON.parse(this.responseText))
          }
        }
        xhr.onerror = function (e) { console.log(e) }
        // 发送数据
        xhr.send()
      })
    },
    beforeDownloadCSV () {
      this.$refs.chart && this.$refs.chart.$refs['chart' + this.chartInfo.id].beforeDownloadCSV(this.chartInfo)
    }
  },
  watch: {
    timeRange: {
      deep: true,
      handler (n) {
        // this.refresh()
      }
    },
    loading: {
      immediate: true,
      deep: true,
      handler (n) {
        if (window.dataJson && this.loading) {
          this.loading = false
        }
      }
    },
    variablesArr: {
      handler (n) {
        const elements = this.$lodash.cloneDeep(this.chartInfo.oldElements) || []
        const variables = elements.map((element) => {
          return this.variablesReplace(element.expression)
        })
        let flag = false
        this.myVariables.forEach((item, index) => {
          if (item !== variables[index]) {
            flag = true
          }
        })
        if (flag) {
          this.chartInfo.loaded && this.getChartData(true)
        }
      }
    }
  },
  created () {
    if (window.dataJson) {
      this.snapshotShow = false
      this.getChartData()
    }
  },
  mounted () {
    this.chartInfo.loaded && this.getChartData()
    setTimeout(() => {
      this.snapshotShow = true
    })
    this.showAllData = !this.showMultiple(this.chartInfo.type)
  }
}
</script>