wujingjing
2024-12-13 667c08a39b523e7afdf00a6af17ac2d4274b659a
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
<template>
    <div class="w100 h100">
        <titleBox :title="state.selectSinalInfo?.LogicalName">
            <template v-slot:right>
                <div class="titleBoxRightSlot">
                    开始/结束日期:
                    <el-date-picker
                        v-model="state.themetime"
                        range-separator="~"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :disabled-date="disablesDate"
                        type="daterange"
                        :default-time="defaultTime"
                        clearable
                        value-format="YYYY-MM-DD HH:mm:ss"
                        @change="getDateTime"
                    />
 
                    <el-button class="ml10 mb5" type="primary" @click="timeQuery(1)" :disabled="queryDisabled">查询</el-button>
                </div>
            </template>
        </titleBox>
        <div style="width: 100%; height: 100%" v-loading="state.lineChartLoading">
            <div id="chartRangeMain" style="width: 100%; height: calc(100% - 30px)"></div>
        </div>
    </div>
</template>
 
<script setup lang="ts">
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import moment from 'moment';
import { onMounted, reactive, ref, shallowRef, toRefs } from 'vue';
import { GetDisplayParasByID, GetLimitBySignalIDOfTimeRange } from '/@/api/monitor/rangeHistory';
import titleBox from '/@/components/titleBox.vue';
import { calMaxMinIntervalByChartData } from '/@/utils/chart';
const myChart = shallowRef(null);
const defaultTime = ref<[Date, Date]>([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]);
// 定义变量内容
const state = reactive({
    themetime: '' as any,
    loadingPumpStationTree: false,
    treeDataLoading: false,
    queryBtn: false,
    option: null,
    lineChartLoading: true,
    queryDisabled: false,
    chartData: [], //获取图表的data
    getFormatJsonInfo: {
        FormatType: '' as any,
        DisplayParas: {
            UnitValue: '',
            DecimalPlaces: '',
            BreakSpace: '',
            AxisCoord: '',
            AxisLabels: '',
        },
    } as any, //获取参数
    selectSignalName: '',
    selectSinalInfo: {} as any,
});
//#region ====================== 参数传参 ======================
const props = defineProps({
    selectDataInfo: {
        type: Object,
    },
    request: {
        type: Function,
    },
    queryDisabled: {
        type: Boolean,
        default: false,
    },
});
let { selectDataInfo, queryDisabled } = toRefs(props);
//#endregion
// 页面加载时
onMounted(async () => {
    state.themetime = getdatatime();
    window.addEventListener('resize', selfAdaption);
});
//#region ====================== 时间事件 ======================
// 时间限制
const disablesDate = (time) => {
    return time.getTime() > new Date().getTime();
};
//默认时间选择前7天/默认选择当天
const getdatatime = () => {
    let sevenAgo = moment(new Date()).subtract(7, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss');
    let today = moment().endOf('day').format('YYYY-MM-DD HH:mm:ss');
    return [sevenAgo, today];
};
//获取日期的时间
const getDateTime = (val) => {
    state.themetime[0] = val[0];
    state.themetime[1] = val[1];
    if (!queryDisabled.value) {
        getChartList();
    }
};
//查询时间
const timeQuery = (type) => {
    getChartList();
};
//#endregion
//#region ====================== init 图表 ======================
//清空图表
const clearEChartData = () => {
    setTimeout(() => {
        ElMessage.warning('该区间暂无数据');
        myChart.value &&
            myChart.value.setOption({
                xAxis: {
                    min: '',
                    max: '',
                },
                yAxis: [],
                series: [
                    {
                        data: [],
                    },
                ],
            });
    }, 300);
    return;
};
const clearTableData = () => {
    setTimeout(() => {
        state.chartData = [];
        myChart.value && myChart.value.clear();
    }, 300);
    return;
};
const getTableData = () => {
    state.selectSinalInfo = selectDataInfo.value;
    getFormatJson();
};
//获取格式显示参数
const getFormatJson = async () => {
    myChart.value && myChart.value.clear();
    state.lineChartLoading = true;
    let res = await GetDisplayParasByID(
        {
            ID: state.selectSinalInfo.LogicalID,
        },
        props.request
    );
 
    if (res.Code != 0) {
        return;
    }
    if (res.Data == null || res.Data == '') {
        return;
    }
    state.getFormatJsonInfo = res.Data;
    state.getFormatJsonInfo.DisplayParas.UnitValue = res.Data.DisplayParas.UnitName;
    getChartList();
};
//获取data数据列表
const getChartList = async () => {
    myChart.value && myChart.value.clear();
    let res = await GetLimitBySignalIDOfTimeRange(
        {
            Limit: 10000,
            SignalID: state.selectSinalInfo.LogicalID,
            StartTime: state.themetime[0],
            EndTime: state.themetime[1],
        },
        props.request
    );
    state.lineChartLoading = false;
    if (res.Code != 0) {
        return;
    }
    if (res.Data == null || res.Data == '') {
        clearEChartData();
    }
 
    state.chartData = res.Data || [];
    if (state.getFormatJsonInfo.FormatType == 1) {
        setTimeout(() => {
            initChart();
        }, 100);
    }
    if (state.getFormatJsonInfo.FormatType == 2) {
        setTimeout(() => {
            formatBar();
        }, 100);
    }
};
// 初始化chart
const initChart = () => {
    myChart.value && myChart.value.clear();
    //先获取Dom上的实例
    let chartDom = echarts.getInstanceByDom(document.getElementById('chartRangeMain') as HTMLDivElement);
    //然后判断实例是否存在,如果不存在,就创建新实例
    if (chartDom == null) {
        chartDom = echarts.init(document.getElementById('chartRangeMain') as HTMLDivElement);
        myChart.value = chartDom;
    }
    let x_yData = [];
    let y_calData = []; //Y轴的数据源
    state.chartData.forEach((item) => {
        x_yData.push([item.DataTime, item.DataValue]);
        y_calData.push(item.DataValue);
    });
    let series_arr = [];
 
    if (state.getFormatJsonInfo.FormatType == 1) {
        series_arr.push({
            type: 'line',
            showSymbol: false,
            emphasis: { scale: false },
            data: x_yData,
            itemStyle: {
                color: '#4169E1',
            },
        });
    }
    let yMin_axis = Math.min(...y_calData); //获取数据源的最小值
    let yMax_axis = Math.max(...y_calData); //获取数据源的最大值
    let option = {
        tooltip: {
            trigger: 'axis',
        },
        grid: {
            containLabel: true,
            x: '25',
            y: '65',
            x2: '60',
            y2: '90',
        },
        xAxis: {
            type: 'time',
            name: '时间',
            minorTick: {
                show: false,
                splitNumber: 2,
            },
            splitLine: {
                show: true, //是否显示分隔线
                interval: 'auto', //坐标轴分隔线的显示间隔
            },
        },
        yAxis: {
            name: state.getFormatJsonInfo.DisplayParas.UnitValue,
            type: 'value',
            axisLabel: {
                formatter: function (val) {
                    // console.log(val);
                    var value = val;
                    if (val >= 1000 && val < 1000000) {
                        value = val / 1000 + 'k';
                    } else if (val >= 1000000) {
                        value = val / 1000000 + 'm';
                    }
                    return value;
                },
            },
            min: yMin_axis,
            max: yMax_axis,
            // 整条y轴
            axisLine: {
                show: true,
            },
            // y轴上的小横线
            axisTick: {
                show: true,
            },
        },
        dataZoom: [
            {
                type: 'inside',
                start: 0,
                end: 100,
            },
            {
                id: 'dataZoomY',
                type: 'slider',
                xAxisIndex: [0],
                filterMode: 'empty',
            },
        ],
        series: series_arr,
    };
 
    myChart.value.setOption(option);
    setTimeout(() => {
        state.lineChartLoading = false;
    }, 3000);
    let calYAxis = calMaxMinIntervalByChartData(y_calData, 2);
    myChart.value &&
        myChart.value.setOption({
            yAxis: {
                min: calYAxis.min,
                max: calYAxis.max,
                data: calYAxis,
            },
        });
    selfAdaption();
};
//#endregion
//#region ====================== 文本图表 ======================
 
const 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('chartRangeMain') as HTMLDivElement);
    //然后判断实例是否存在,如果不存在,就创建新实例
    if (chartDom == null) {
        chartDom = echarts.init(document.getElementById('chartRangeMain') as HTMLDivElement);
        myChart.value = chartDom;
    }
    var formatData = getFormatData4Enum(state.chartData); //数据转换
    const series_data_enum = [];
    const getParamsList = state.getFormatJsonInfo.DisplayParas.Items;
    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 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: '90',
        },
        axisPointer: {
            link: { xAxisIndex: 'all' },
        },
        xAxis: [
            {
                name: '时间',
                type: 'time',
                axisLabel: {
                    show: true,
                    formatter: function (val) {
                        let date = moment(val).format('MM-DD');
                        return date;
                    },
                },
                axisLine: { onZero: true, show: true },
                splitLine: {
                    show: true,
                },
                axisTick: {
                    // 轴刻度
                    show: true,
                },
            },
        ],
        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.setOption(option);
    selfAdaption();
};
//自定义图表方法
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',
        },
    };
}
//  自适应
const selfAdaption = () => {
    if (!myChart.value) return;
    myChart.value.resize();
};
//#endregion
// 导出对象
defineExpose({ getTableData, clearEChartData, clearTableData });
</script>
<style scoped lang="scss">
.titleBoxRightSlot {
    width: 100%;
}
</style>