wujingjing
2024-12-23 6d82ad4fb10f7015059b1b2cbcf72e8a949e83fa
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
<template>
    <div class="model-binding-right-box">
        <titleBox :title="state.selectSinalInfo?.LogicalName"> </titleBox>
        <div :style="`display: flex; height: ${boxHeight}`" v-loading="state.echartLoading">
            <div id="chartMain" class="w100 h100"></div>
        </div>
    </div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts';
import moment from 'moment';
import type { PropType } from 'vue';
import { onMounted, reactive, shallowRef, toRefs } from 'vue';
import { ElMessage } from 'element-plus';
import { formatTime, getDay } from '/@/utils/istation/common.js';
import { GetBySignalIDOfNumberDay, GetDisplayParasByID } from '/@/api/monitor/list';
import titleBox from '/@/components/titleBox.vue';
import request from '/@/utils/request';
import type { SignalTypeFormatEnum } from '/@/projectCom/basic/types';
const myChart = shallowRef(null);
// 定义变量内容
const state = reactive({
    getFormatJsonInfo: {
        DisplayParas: {
            DisplayItems: [],
        },
        FormatType: '',
    } as any, //获取参数
    chartData: [],
    getFreshData: [], //x轴y轴的数据
    selectSignalID: '',
    selectSignalName: '',
    echartTitle: '',
    selectSinalInfo: {} as any,
    echartLoading: false,
    main_chart_option_: {} as any, //获取图表option所有的数据
});
 
onMounted(() => {
    selfAdaption();
    window.addEventListener('resize', selfAdaption);
});
//#region ====================== 图表传参 ======================
const props = defineProps({
    selectDataInfo: {
        type: Object as PropType<{
            last_dataValue: null;
            LogicalID: string;
            FormatType: SignalTypeFormatEnum;
            unitNameList: [string, string];
            LogicalName: string;
            LastDataValue: any;
            LastDataTime: string;
        }>,
    },
    request: {
        type: Function,
        default: request,
    },
    boxHeight: {
        type: String,
        default: '100%',
    },
    modelValue: {
        type: Array,
        default: () => {
            return [];
        },
    },
    queryDisabled: {
        type: Boolean,
        default: false,
    },
});
let { selectDataInfo, queryDisabled } = toRefs(props);
//#endregion
//#region ====================== 绘图init ======================
const getTableData = async () => {
    selfAdaption();
    state.selectSinalInfo = selectDataInfo.value;
    if (state.selectSinalInfo.FormatType == 6) {
        boxingBar();
    } else {
        await getFormatJson();
    }
};
 
//获取格式显示参数
const getFormatJson = async () => {
    myChart.value && myChart.value.clear();
    state.echartLoading = true;
    await GetDisplayParasByID({
        ID: state.selectSinalInfo.LogicalID,
    }).then((res) => {
        if (res.Code != 0) {
            return ElMessage.error('测点不可选');
        }
        if (res.Data == null || res.Data == '') {
            return clearEChart();
        }
        state.getFormatJsonInfo = res.Data;
        state.getFormatJsonInfo.DisplayParas.DisplayItems = res.Data.DisplayParas.Items;
 
        getChartList();
    });
};
//获取data数据列表getDataID
const getChartList = async () => {
    myChart.value && myChart.value.clear();
    await GetBySignalIDOfNumberDay({
        SignalID: state.selectSinalInfo.LogicalID,
        Day: state.selectSinalInfo.LastDataTime,
    }).then((res) => {
        state.echartLoading = false;
        if (res.Code != 0) {
            return;
        }
        if (res.Data == null || res.Data == '') {
            ElMessage.warning('该日期暂无数据');
            return;
        }
        state.chartData = res.Data || [];
        if (state.getFormatJsonInfo.FormatType == 1) {
            setTimeout(() => {
                drawBar();
            }, 100);
        }
        if (state.getFormatJsonInfo.FormatType == 2) {
            setTimeout(() => {
                formatBar();
            }, 100);
        }
    });
};
 
//#endregion
 
//#region ====================== formatType=1 折线图  ======================
//  初始化echarts折线图
const drawBar = () => {
    myChart.value && myChart.value.clear();
    //先获取Dom上的实例
    let chartDom = echarts.getInstanceByDom(document.getElementById('chartMain') as HTMLDivElement);
    //然后判断实例是否存在,如果不存在,就创建新实例
    if (chartDom == null) {
        chartDom = echarts.init(document.getElementById('chartMain') as HTMLDivElement);
    }
    myChart.value = chartDom;
    var chartRecordList = TransChartRecordPoint(state.chartData);
    state.getFreshData = chartRecordList; //给刷新的赋值
    var series_arr = [];
    series_arr.push({
        type: 'line',
        showSymbol: false,
        emphasis: {
            scale: false,
        },
        data: chartRecordList,
        itemStyle: {
            color: '#4169E1',
        },
    });
 
    let option = {
        tooltip: {
            trigger: 'axis',
        },
        legend: {
            show: false,
            fontSize: 12,
            color: '#7e8390',
        },
        grid: {
            top: 50,
            left: 50,
            right: 50,
            containLabel: true,
        },
        xAxis: {
            name: '时间',
            type: 'time',
            splitLine: {
                show: true,
                interval: 'auto', //坐标轴分隔线的显示间隔
            },
            axisLabel: {
                showMaxLabel: true,
                formatter: function (v, index) {
                    var date = new Date(v);
                    let text = formatTime('hh:mm', date);
                    return text;
                },
            },
            minInterval: 3600 * 4 * 1000, //12
        },
        yAxis: {
            boundaryGap: ['20%', '20%'],
            name: state.getFormatJsonInfo.DisplayParas.UnitName,
            type: 'value',
            axisLabel: {
                formatter: function (val) {
                    //console.log(val)
                    var value = val;
                    if (val >= 1000 && val < 1000000) {
                        value = parseFloat(formatNumber(val / 1000).toFixed(2)) + 'k';
                    } else if (val >= 1000000) {
                        value = parseFloat(formatNumber(val / 1000000).toFixed(2)) + 'm';
                    }
                    return value;
                },
            },
            min: 0,
            // 整条y轴
            axisLine: {
                show: true,
            },
        },
        dataZoom: [
            {
                id: 'dataZoomX',
                type: 'slider',
                xAxisIndex: [0],
                start: 0,
                end: 100,
                bottom: 30,
                filterMode: 'filter',
                handleIcon:
                    'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                handleSize: '80%',
                handleStyle: {
                    color: '#fff',
                    shadowBlur: 3,
                    shadowColor: 'rgba(0, 0, 0, 0.9)',
                    shadowOffsetX: 2,
                    shadowOffsetY: 2,
                },
                borderColor: '#999',
            },
            {
                // 这个dataZoom组件,也控制x轴。
                type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
                start: 0, // 左边在 24% 的位置。
                end: 100, // 右边在 100% 的位置。
            },
        ],
        series: series_arr,
    };
    state.main_chart_option_ = option; //将配置项弄成全局
    myChart.value && myChart.value.setOption(option);
    getFuturePredictTime();
    selfAdaption();
};
//解决小数精度问题
const formatNumber = (n) => {
    return parseFloat(parseFloat(n).toFixed(12));
};
//数据格式转换
const TransChartRecordPoint = (record) => {
    let m_chartRecordList = [];
    let length = record.length;
    for (let i = 0; i < length; i++) {
        let dataValue = {
            value: [record[i].DataTime, record[i].DataValue],
        };
        m_chartRecordList.push(dataValue);
    }
    return m_chartRecordList;
};
//预测未来时间的markLine
const getFuturePredictTime = () => {
    if (state.chartData.length == 0) return;
    //获取Y轴的刻度范围
    var rangeY = myChart.value.getModel().getComponent('yAxis').axis.scale._extent;
    let _markLine = {
        //盒须图样式。
        label: {
            formatter: `数据值: ${state.selectSinalInfo.LastDataValue}${state.getFormatJsonInfo.DisplayParas.UnitName}`,
            color: 'red',
            distance: [0, 15],
        },
        lineStyle: {
            color: '#FF0000',
        },
        silent: true,
        data: [
            [
                {
                    coord: [state.selectSinalInfo.LastDataTime, '0'],
                },
                {
                    coord: [state.selectSinalInfo.LastDataTime, state.selectSinalInfo.LastDataValue],
                },
            ],
        ],
    };
    state.main_chart_option_.series[0].markLine = _markLine;
    setTimeout(() => {
        myChart.value.setOption(state.main_chart_option_); //将_markPoint在option的值重新赋值
    }, 500);
};
 
//#endregion
//#region ====================== formatType=2 文本图 ======================
//枚举数据格式化
function getFormatData4Enum(arr) {
    var temp = arr[0];
    var formatData = [];
    for (var i = 0; i < arr.length - 1; i++) {
        //var node = arr[i];
        if (arr[i].DataValue != arr[i + 1].DataValue) {
            var duration = ((+new Date(arr[i + 1].DataTime) - +new Date(temp.DataTime)) / 1000 / 60 / 60).toFixed(2);
            formatData.push({ StartTime: temp.DataTime, EndTime: arr[i + 1].DataTime, Status: temp.DataValue, Duration: duration });
            temp = arr[i + 1];
        }
        if (i == arr.length - 2) {
            var len = arr.length - 1;
            let duration = null;
            duration = Math.round(((+new Date(arr[len].DataTime) - +new Date(temp.DataTime)) / 1000 / 60 / 60) * 100) / 100;
            formatData.push({ StartTime: temp.DataTime, EndTime: arr[len].DataTime, Status: temp.DataValue, Duration: duration });
        }
    }
    return formatData;
}
 
//文本图
const formatBar = () => {
    myChart.value && myChart.value.clear();
    //先获取Dom上的实例
    let chartDom = echarts.getInstanceByDom(document.getElementById('chartMain') as HTMLDivElement);
    //然后判断实例是否存在,如果不存在,就创建新实例
    if (chartDom == null) {
        chartDom = echarts.init(document.getElementById('chartMain') as HTMLDivElement);
    }
    myChart.value = chartDom;
 
    var formatData = getFormatData4Enum(state.chartData); //数据转换
    const series_data_enum = [];
    const getParamsList = state.getFormatJsonInfo.DisplayParas.DisplayItems;
    formatData.forEach((item) => {
        getParamsList.forEach((paramsItem) => {
            if (paramsItem.EnumName == item.Status) {
                series_data_enum.push({
                    name: state.selectSinalInfo.LogicalName,
                    value: [
                        0,
                        +new Date(item.StartTime) - 0,
                        +new Date(item.EndTime) - 0,
                        item.Status,
                        item.Duration,
                        { id: state.selectSinalInfo.LogicalID, name: state.selectSinalInfo.LogicalName },
                    ],
                    itemStyle: {
                        color: paramsItem.DisplayColor,
                    },
                });
            }
        });
    });
    let sel_record_day = formatData.length > 0 ? formatData[0].StartTime : '';
    let option = {
        tooltip: {
            show: true,
            formatter: function (params) {
                return (
                    params.marker +
                    params.name +
                    ': ' +
                    params.value[4] +
                    '小时' +
                    '<br/>&nbsp;&nbsp;&nbsp;' +
                    '开始时间: ' +
                    new Date(params.value[1]).getHours() +
                    ':' +
                    new Date(params.value[1]).getMinutes() +
                    '<br/>&nbsp;&nbsp;&nbsp;' +
                    '结束时间: ' +
                    new Date(params.value[2]).getHours() +
                    ':' +
                    new Date(params.value[2]).getMinutes()
                );
            },
        },
        title: {
            text: '',
            left: 'center',
        },
        legend: {
            data: [],
        },
        grid: {
            containLabel: true,
            x: '25',
            y: '65',
            x2: '60',
            y2: '80',
        },
        axisPointer: {
            link: { xAxisIndex: 'all' },
        },
        xAxis: [
            {
                name: '时间',
                min: +new Date(getDay(0, new Date(sel_record_day)) + ' 00:00:00'),
                max: +new Date(getDay(1, new Date(sel_record_day)) + ' 00:00:00'),
                interval: 60 * 60 * 1000 * 4,
                axisLabel: {
                    formatter: function (val) {
                        var date = new Date(val);
                        var texts = [date.getHours()]; //date.getMinutes()
                        return texts.join(':');
                    },
                },
                axisTick: {
                    alignWithLabel: true,
                    show: false,
                },
                axisLine: { onZero: true, show: true },
                minorTick: {
                    show: false,
                    splitNumber: 2,
                },
                minorSplitLine: {
                    show: true,
                    lineStyle: {
                        color: '#aaa',
                        type: 'dashed',
                    },
                },
            },
        ],
        yAxis: [
            {
                inverse: true,
                triggerEvent: true,
                data: [state.selectSinalInfo.LogicalName],
            },
        ],
        dataZoom: [
            {
                type: 'inside',
                start: 0,
                end: 100,
            },
            {
                start: 0,
                end: 100,
            },
        ],
 
        series: [
            {
                type: 'custom',
                renderItem: renderItemFunc,
                itemStyle: {
                    opacity: 0.8,
                },
                encode: {
                    x: [1, 2],
                    y: 0,
                },
                data: series_data_enum,
            },
        ],
    };
    myChart.value && myChart.value.setOption(option);
};
//自定义图表方法
function renderItemFunc(params, api) {
    var categoryIndex = api.value(0);
    var start = api.coord([api.value(1), categoryIndex]);
    var end = api.coord([api.value(2), categoryIndex]);
    var height = api.size([0, 1])[1] * 0.6 < 40 ? api.size([0, 1])[1] * 0.6 : 40;
    var barLength = end[0] - start[0];
    var runtime = api.value(3) + ':' + api.value(4) + 'h';
    var flightNumberWidth = echarts.format.getTextRect(runtime).width;
    var text = runtime;
    text = barLength > flightNumberWidth ? text : '';
 
    var rectShape = echarts.graphic.clipRectByRect(
        {
            x: start[0],
            y: start[1] - height / 2,
            width: end[0] - start[0],
            height: height,
        },
        {
            x: params.coordSys.x,
            y: params.coordSys.y,
            width: params.coordSys.width,
            height: params.coordSys.height,
        }
    );
 
    return {
        type: 'rect',
        shape: rectShape,
        style: {
            ...api.style(),
            text: text,
            textFill: '#fff',
        },
    };
}
//#endregion
//#region ====================== formatType=6 波形图 ======================
const boxingBar = () => {
    myChart.value && myChart.value.clear();
    let chartData = [];
    let EChartData = [];
    if (!state.selectSinalInfo.last_dataValue || state.selectSinalInfo.last_dataValue == null) return ElMessage.warning('暂无数据');
    state.selectSinalInfo.last_dataValue.forEach((item) => {
        EChartData.push([item.X, item.Y]);
    });
    chartData.push({
        chartType: '波形图',
        name: '值',
        chart: null,
        x: null,
        data: EChartData,
        x_unit: state.selectSinalInfo.UnitNameList[0],
        y_unit: state.selectSinalInfo.UnitNameList[1],
        boundaryGap: ['20%', '20%'],
    });
 
    state.chartData = chartData;
    setTimeout(() => {
        boxingInitChart();
    }, 100);
};
//图表初始化
const boxingInitChart = () => {
    state.chartData.forEach((x) => {
        //先获取Dom上的实例
        let chartDom2 = echarts.getInstanceByDom(document.getElementById('chartMain') as HTMLDivElement);
        //然后判断实例是否存在,如果不存在,就创建新实例
        if (chartDom2 == null) {
            chartDom2 = echarts.init(document.getElementById('chartMain') as HTMLDivElement);
        }
        myChart.value = chartDom2;
        var series_arr2 = [];
        var yAxisArr = [];
        series_arr2.push({
            name: x.y_unit,
            type: 'line',
            smooth: true,
            symbolSize: 0,
            sampling: 'max',
            itemStyle: {
                lineStyle: {
                    width: 1,
                },
                color: 'rgb(0, 0, 255)',
            },
            data: x.data,
        });
 
        yAxisArr.push({
            type: 'value',
            name: x.y_unit,
            nameGap: 35,
            nameLocation: 'center',
            boundaryGap: x.boundaryGap,
            scale: true,
            axisLine: {
                show: true,
            },
        });
        let option = {
            grid: {
                top: 20,
                left: 50,
                right: 50,
                containLabel: true,
            },
            xAxis: {
                name: x.x_unit,
                type: 'value',
                // position: "bottom",
                nameLocation: 'center',
                axisLine: {
                    onZero: false,
                },
                nameGap: 23,
                data: x.x,
            },
            yAxis: yAxisArr,
            dataZoom: [
                {
                    type: 'inside',
                    start: 0,
                    end: 100,
                },
                {
                    id: 'dataZoomY',
                    type: 'slider',
                    xAxisIndex: [0],
                    filterMode: 'empty',
                },
            ],
 
            tooltip: {
                trigger: 'axis',
                hideDelay: 1000,
                axisPointer: {
                    type: 'cross',
                },
                position: (pt: any) => {
                    return [pt[0], '10%'];
                },
            },
            series: series_arr2,
            //   animationEasing: "elasticOut",
        };
        myChart.value.setOption(option);
        x.chart = myChart.value;
        window.addEventListener('resize', selfAdaption);
    });
};
//#endregion
//#region ====================== 图表自适应 ======================
//  自适应
const selfAdaption = () => {
    if (!myChart.value) return;
    myChart.value.resize();
};
//清除图表
const clearEChart = () => {
    setTimeout(() => {
        ElMessage.warning('当日暂无数据');
        myChart.value &&
            myChart.value.setOption({
                xAxis: {
                    min: '',
                    max: '',
                },
                yAxis: [],
                series: [],
            });
    }, 300);
    return;
};
 
//#endregion
// 导出对象
defineExpose({ getTableData, clearEChart });
</script>
<style scoped lang="scss">
.model-binding-right-box {
    width: 100%;
    height: 100%;
    // background: #fff;
}
.titleBoxRightSlot {
    width: 100%;
}
</style>