index.vue 13.7 KB
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
<script lang="ts" setup>
  import {
    ref,
    onMounted,
    unref,
    shallowReactive,
    nextTick,
    reactive,
    computed,
    onUnmounted,
  } from 'vue';
  import * as echarts from 'echarts';
  import { Empty } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useWebSocket } from '@vueuse/core';
  import { getAuthCache } from '/@/utils/auth';
  import { JWT_TOKEN_KEY } from '/@/enums/cacheEnum';
  import { useGlobSetting } from '/@/hooks/setting';
  import moment from 'moment';
  import { EdgeInstanceItemType } from '/@/api/edgeManage/model/edgeInstance';
  import { isArray, isNumber } from '/@/utils/is';
  import { formatSizeUnits } from '/@/utils';
  import cpuSvg from '/@/assets/icons/cpu.svg';
  import diskSvg from '/@/assets/icons/disk.svg';
  import memorySvg from '/@/assets/icons/memory.svg';

  interface ChartInstance {
    name: string;
    currentValue: number;
    totalKey: string;
    totalCount: Recordable;
    type: string;
    text: string;
    xAxisData: string[];
    seriesData: number[];
    icon: any;
  }

  enum DeviceInfoOfEdge {
    CPU_USAGE_OF_EDGE = 'cpuUsageOfEdge',
    DISC_USAGE_OF_EDGE = 'discUsageOfEdge',
    MEMORY_USAGE_OF_EDGE = 'memoryUsageOfEdge',
    CPU_COUNT_OF_EDGE = 'cpuCountOfEdge',
    TOTAL_MEMORY_OF_EDGE = 'totalMemoryOfEdge',
    TOTAL_DISC_SPACE_OF_EDGE = 'totalDiscSpaceOfEdge',
  }

  const props = defineProps({
    recordData: {
      type: Object as PropType<EdgeInstanceItemType>,
      default: () => {},
    },
  });

  const token = getAuthCache(JWT_TOKEN_KEY);

  const { socketUrl } = useGlobSetting();

  const socketInfo = reactive({
    entityId: '',
    origin: `${socketUrl}${token}`,
  });

  const { createMessage } = useMessage();

  const getSendValue = computed(() => {
    return {
      tsSubCmds: [
        {
          entityId: '',
          cmdId: 11,
          entityType: 'EDGE',
          keys: `${DeviceInfoOfEdge.CPU_USAGE_OF_EDGE},${DeviceInfoOfEdge.DISC_USAGE_OF_EDGE},${DeviceInfoOfEdge.MEMORY_USAGE_OF_EDGE},${DeviceInfoOfEdge.CPU_COUNT_OF_EDGE},${DeviceInfoOfEdge.TOTAL_MEMORY_OF_EDGE},${DeviceInfoOfEdge.TOTAL_DISC_SPACE_OF_EDGE}`,
          startTs: moment(moment().subtract(1, 'minute')).valueOf(),
          timeWindow: 3600000,
          interval: 10000,
          // intervalType: 'MILLISECONDS',
          limit: 360,
          // timeZoneId: 'Asia/Shanghai',
          agg: 'AVG',
          unsubscribe: false,
        },
      ],
    };
  });

  const chartInstance = ref<ChartInstance[]>([
    {
      name: 'CPU',
      text: 'CPU使用率',
      currentValue: 0,
      totalKey: DeviceInfoOfEdge.CPU_COUNT_OF_EDGE,
      totalCount: {},
      type: DeviceInfoOfEdge.CPU_USAGE_OF_EDGE,
      xAxisData: [],
      seriesData: [],
      icon: cpuSvg,
    },
    {
      name: '内存',
      text: '内存使用率',
      currentValue: 0,
      totalKey: DeviceInfoOfEdge.TOTAL_MEMORY_OF_EDGE,
      totalCount: {},
      type: DeviceInfoOfEdge.MEMORY_USAGE_OF_EDGE,
      xAxisData: [],
      seriesData: [],
      icon: memorySvg,
    },
    {
      name: '磁盘',
      text: '磁盘使用率',
      currentValue: 0,
      totalKey: DeviceInfoOfEdge.TOTAL_DISC_SPACE_OF_EDGE,
      totalCount: {},
      type: DeviceInfoOfEdge.DISC_USAGE_OF_EDGE,
      xAxisData: [],
      seriesData: [],
      icon: diskSvg,
    },
  ]);

  const chartsInstance = shallowReactive<{ [key: string]: echarts.ECharts }>({});

  // const cacheUsedSpace = (total, percentage) => {
  //   if (!total) return;
  //   const takeValue = total.split('.')[0];
  //   const takeUnit = total.split('.')[1];
  //   return `${(takeValue * (percentage / 100)).toFixed(1)}${takeUnit}`;
  // };

  const { send, close, data, open } = useWebSocket(socketInfo.origin, {
    immediate: false,
    autoReconnect: true,
    async onConnected() {
      getSendValue.value.tsSubCmds[0].entityId = socketInfo.entityId;
      send(JSON.stringify(unref(getSendValue)));
    },
    async onMessage() {
      try {
        const value = JSON.parse(unref(data)) as any;
        if (value) {
          const { data } = value;
          const keys = Object.keys(data);
          for (const key of keys) {
            chartInstance.value.forEach((chartItem: ChartInstance) => {
              if (chartItem.type === key) {
                chartItem.xAxisData.push(moment(data[key][0][0]).format('HH:mm'));
                // chartItem.seriesData = [];
                chartItem.seriesData = data[key][0][1] ? [data[key][0][1]] : [];
                chartItem.currentValue = Number(data[key][0][1]);
              }
              if (chartItem.totalKey === key) {
                chartItem.totalCount.cpuTotal =
                  key === DeviceInfoOfEdge.CPU_COUNT_OF_EDGE ? data[key][0][1] : 0;
                chartItem.totalCount.totalDisc =
                  key === DeviceInfoOfEdge.TOTAL_DISC_SPACE_OF_EDGE
                    ? formatSizeUnits(Number(data[key][0][1]))
                    : 0;
                chartItem.totalCount.totalMemory =
                  key === DeviceInfoOfEdge.TOTAL_MEMORY_OF_EDGE
                    ? formatSizeUnits(Number(data[key][0][1]))
                    : 0;
              }
            });
          }
          await nextTick();
          handleRenderChartInstance(chartInstance.value);
        }
      } catch (error) {}
    },
    onDisconnected() {},
    onError() {
      createMessage.error('webSocket连接超时,请联系管理员');
    },
  });

  function onResize(type) {
    if (!chartsInstance[type]) return;
    chartsInstance[type]?.resize();
  }

  const chartOption = {
    series: [
      {
        data: [],
        detail: {
          formatter: `暂无数据`,
        },
        type: 'gauge',
        axisLine: {
          lineStyle: {
            width: 10,
            color: [
              [0.2, '#739ded'],
              [0.8, '#5f89d8'],
              [1, '#377dff'],
            ],
          },
        },
        pointer: {
          itemStyle: {
            color: 'auto',
          },
        },
        axisTick: {
          distance: 0,
          length: 8,
          lineStyle: {
            color: 'auto',
          },
        },
        splitLine: {
          distance: 0,
          length: 10,
          lineStyle: {
            color: 'auto',
            width: 3,
          },
        },
        axisLabel: {
          color: 'inherit',
          distance: 15,
          fontSize: 8,
        },
      },
    ],
  };
  const pieOption = {
    grid: {
      top: 0,
      bottom: 0,
      left: 0,
      right: 0,
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>{d}%',
      textStyle: {
        fontSize: 12,
      },
    },
    title: {
      text: '磁盘容量',
      subtext: '暂无数据',
      textStyle: {
        fontSize: 12,
        color: '#72767c',
      },
      subtextStyle: {
        fontSize: 14,
        color: '#000000',
        fontWeight: 500,
      },
      textAlign: 'center',
      left: '48.5%',
      top: '44%',
    },
    legend: {
      show: true,
      icon: 'circle',

      bottom: '0%',
      data: [{ name: '磁盘已使用' }, { name: '磁盘剩余空间' }].map((item) => ({
        name: item.name,
      })),
      formatter(name: string) {
        return `{b_style|${name}} `;
      },
      textStyle: {
        color: '#000',
        rich: {
          b_style: {
            color: '#8d8ea0',
            fontSize: 12,
            padding: [0, 5, 0, 0],
          },
        },
      },
    },
    series: [
      {
        type: 'pie',
        // center: ['35%', '50%'],
        radius: ['40%', '67%'],
        startAngle: 30,
        emphasis: {
          scale: false,
        },
        label: {
          position: 'outside',
          alignTo: 'labelLine',
          height: 0,
          width: 0,
          lineHeight: 0,
          distanceToLabelLine: 75,
          borderRadius: 3,
          borderWidth: 1,
          borderColor: 'none',
          padding: [20, -15, 0, -10],
          rich: {
            a: {
              padding: [0, -80, 55, -80],
              fontSize: '12px',
              color: '#000000',
            },
            b: {
              padding: [20, -80, 40, -80],
              fontSize: '12px',
              color: '#72767c',
            },
          },
          // formatter: (params: any) => {
          //   const { data } = params;
          //   const { value } = data || {};

          //   const total = Number(totalCount.totalDisc?.split('.')[0] || 0);
          //   const totalUnit = totalCount.totalDisc?.split('.')[1] || 0;

          //   return `{a|${value && total ? value : ''}${value && total ? '%' : ''}} \n {b|${
          //     total ? (total * (value / 100)).toFixed(1) : ''
          //   }${total ? totalUnit : ''}}`;
          // },
        },
        labelLine: {
          show: false,
          length: 5,
          // align: 'bottom',
          lineStyle: {
            width: 1,
          },
        },
        data: [
          { name: '磁盘已使用', value: 0, itemStyle: { color: '#90b2f1' } },
          { name: '磁盘剩余空间', value: 100, itemStyle: { color: '#377dff' } },
        ],
      },
    ],
  };

  const handleRenderChartInstance = async (chartInstance: ChartInstance[]) => {
    await nextTick();
    if (!chartInstance) return;
    if (isArray(chartInstance) && chartInstance.length <= 0) return;
    for (const item of unref(chartInstance)) {
      const { type, seriesData, currentValue, totalCount } = item;
      // chartsInstance[type] = echarts.init(document.getElementById(`chart-${type}`) as HTMLElement);
      if (type !== DeviceInfoOfEdge.DISC_USAGE_OF_EDGE) {
        chartsInstance[type].setOption({
          series: [
            {
              data: seriesData,
              detail: {
                formatter: `${isNumber(currentValue) ? '{value} %' : '暂无数据'}`,
              },
            },
          ],
        });
      } else {
        chartsInstance[type].setOption({
          title: {
            subtext: totalCount.totalDisc,
          },
          series: [
            {
              label: {
                formatter: (params: any) => {
                  const { data } = params;
                  const { value } = data || {};

                  const total = Number(totalCount.totalDisc?.split('.')[0] || 0);
                  const totalUnit = totalCount.totalDisc?.split('.')[1] || 0;

                  return `{a|${value && total ? value : ''}${value && total ? '%' : ''}} \n {b|${
                    total ? (total * (value / 100)).toFixed(1) : ''
                  }${total ? totalUnit : ''}}`;
                },
              },
              data: [
                { name: '磁盘已使用', value: currentValue, itemStyle: { color: '#90b2f1' } },
                {
                  name: '磁盘剩余空间',
                  value: 100 - currentValue,
                  itemStyle: { color: '#377dff' },
                },
              ],
            },
          ],
        });
      }

      window.addEventListener('resize', () => onResize(type));
    }
  };

  onUnmounted(() => {
    window.removeEventListener('resize', onResize);
  });

  onMounted(() => {
    socketInfo.entityId = props.recordData?.id?.id as string;
    if (socketInfo.entityId) {
      open();
      [
        DeviceInfoOfEdge.CPU_USAGE_OF_EDGE,
        DeviceInfoOfEdge.MEMORY_USAGE_OF_EDGE,
        DeviceInfoOfEdge.DISC_USAGE_OF_EDGE,
      ].forEach((item) => {
        chartsInstance[item] = echarts.init(
          document.getElementById(`chart-${item}`) as HTMLElement
        );
        if (item !== DeviceInfoOfEdge.DISC_USAGE_OF_EDGE) {
          chartsInstance[item]?.setOption(chartOption);
        } else {
          chartsInstance[item]?.setOption(pieOption);
        }
      });
    }
  });

  onUnmounted(() => close());
</script>

<template>
  <div>
    <a-row justify="space-around" align="middle" :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
      <a-col
        class="gutter-row"
        style="background: #f5f5f5; border-radius: 20px"
        :span="7"
        v-for="(item, index) in chartInstance"
        :key="index"
      >
        <a-row align="middle">
          <div class="!flex justify-between items-center font-bold fill-dark-900 p-2.5 mt-4">
            <img :src="item.icon" />
            <span class="ml-1">{{ item.text }}</span>
            <!-- <span>{{ item.currentValue }}%</span>
            <span v-if="item.type !== DeviceInfoOfEdge.DISC_USAGE_OF_EDGE"
              >{{
                item.type === DeviceInfoOfEdge.CPU_USAGE_OF_EDGE
                  ? item.totalCount.cpuTotal
                  : item.type === DeviceInfoOfEdge.MEMORY_USAGE_OF_EDGE
                  ? item.totalCount.totalMemory
                  : 0
              }}{{ item.type === DeviceInfoOfEdge.CPU_USAGE_OF_EDGE ? 'cores' : '' }}</span
            >
            <span v-if="item.type === DeviceInfoOfEdge.DISC_USAGE_OF_EDGE" style="color: #d46b08"
              >已用{{ cacheUsedSpace(item.totalCount.totalDisc, item.currentValue) }}</span
            >
            <span v-if="item.type === DeviceInfoOfEdge.DISC_USAGE_OF_EDGE" style="color: #1677ff"
              >可用{{ item.totalCount.totalDisc }}</span
            > -->
          </div>
        </a-row>
        <a-row class="mt-8" justify="space-around" align="middle">
          <div class="flex w-full justify-center relative">
            <Empty
              description="暂无数据"
              class="text-dark-50 m-4 absolute"
              :style="{ display: item.seriesData.length == 0 ? 'block' : 'none' }"
            />
            <div
              :id="`chart-${item.type}`"
              class="m-4 w-9/10 h-300px"
              :style="{ opacity: item.seriesData.length > 0 ? 1 : 0 }"
            ></div>
          </div>
        </a-row>
      </a-col>
    </a-row>
  </div>
</template>