SiteAnalysis.vue 10.5 KB
<template>
  <Card
    :tab-list="tabListTitle"
    v-bind="$attrs"
    :active-tab-key="activeKey"
    @tabChange="onTabChange"
    v-if="!isAdmin(role)"
  >
    <template #tabBarExtraContent>
      <div class="extra-date">
        <template v-for="(item, index) in dateList" :key="item.value">
          <span
            @click="quickQueryDate(index, item.value)"
            :class="{ active: index === activeIndex }"
            >{{ item.label }}</span
          >
        </template>
        <DatePicker @change="onDateChange" />
      </div>
    </template>
    <div v-if="activeKey === '1'">
      <p class="center">告警数</p>
      <!-- 折线图 -->
      <VisitAnalysis v-if="!isAdmin(role)" :alarmList="state.alarmList" />
    </div>
    <div v-if="activeKey === '2'">
      <p class="center">消息量</p>
      <!-- 柱形图 -->
      <VisitAnalysisBar
        v-if="!isAdmin(role)"
        :dataPointList="state.dataPointList"
        :messageList="state.messageList"
      />
    </div>
  </Card>
  <Card v-bind="$attrs" v-if="isAdmin(role)" title="租户趋势">
    <TenantTrend />
  </Card>
  <Card v-bind="$attrs" v-if="isAdmin(role)" title="客户趋势">
    <CustomerTrend />
  </Card>
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { Card, DatePicker } from 'ant-design-vue';
  import VisitAnalysis from './VisitAnalysis.vue';
  import VisitAnalysisBar from './VisitAnalysisBar.vue';
  import { isAdmin } from '/@/enums/roleEnum';
  import { useWebSocket } from '@vueuse/core';
  import { getAuthCache } from '/@/utils/auth';
  import CustomerTrend from './CustomerTrend.vue';
  import TenantTrend from './TenantTrend.vue';
  import { JWT_TOKEN_KEY } from '/@/enums/cacheEnum';
  import { formatToDateTime } from '/@/utils/dateUtil';
  import { getEntitiesId } from '/@/api/dashboard/index';
  defineExpose({
    isAdmin,
  });
  const props = defineProps<{
    role: string;
  }>();
  const activeKey = ref('1');
  let entityId = null;
  // 图表tab切换选项卡
  const tabListTitle = [
    {
      key: '1',
      tab: '告警数统计',
    },
    {
      key: '2',
      tab: '消息量统计',
    },
  ];
  // 快速选择日期
  const activeIndex = ref(1);
  const dateList = ref([
    { label: '1小时', value: 3600000 },
    { label: '1天', value: 86400000 },
    { label: '7天', value: 604800000 },
    { label: '30天', value: 2592000000 },
  ]);
  // web Socket
  const token: string = getAuthCache(JWT_TOKEN_KEY);

  const state = reactive({
    server: `${import.meta.env.VITE_WEB_SOCKET}${token}`,
    alarmList: new Array<[number, string]>(),
    alarmItem: new Array<[number, string]>(),
    dataPointList: new Array<[number, string]>(),
    messageList: new Array<[number, string]>(),
    dataPoint: new Array<[number, string]>(),
    MsgCount: new Array<[number, string]>(),
  });
  const { send, close } = useWebSocket(state.server, {
    async onConnected() {
      if (isAdmin(props.role)) return;
      const res = await getEntitiesId();
      entityId = res.data[0].entityId;
      const sendValue = JSON.stringify({
        entityDataCmds: [
          {
            query: {
              entityFilter: {
                type: 'singleEntity',
                singleEntity: entityId,
              },
              pageLink: {
                pageSize: 1024,
                page: 0,
                sortOrder: {
                  key: {
                    type: 'ENTITY_FIELD',
                    key: 'createdTime',
                  },
                  direction: 'DESC',
                },
              },
              entityFields: [
                {
                  type: 'ENTITY_FIELD',
                  key: 'name',
                },
                {
                  type: 'ENTITY_FIELD',
                  key: 'label',
                },
                {
                  type: 'ENTITY_FIELD',
                  key: 'additionalInfo',
                },
              ],
              latestValues: [
                {
                  type: 'TIME_SERIES',
                  key: 'createdAlarmsCountHourly',
                },
              ],
            },
            cmdId: activeKey.value,
          },
        ],
      });
      send(sendValue);
      console.log('建立连接了');
    },
    onMessage(_, e) {
      const { data, update } = JSON.parse(e.data);
      console.log('来新消息了', data, update);
      if (activeKey.value === '1') {
        if (data) {
          const { createdAlarmsCountHourly } = data.data[0].latest.TIME_SERIES;
          state.alarmItem = [createdAlarmsCountHourly.ts, createdAlarmsCountHourly.value];
          state.alarmList.push([createdAlarmsCountHourly.ts, createdAlarmsCountHourly.value]);
        }
        if (update) {
          const { createdAlarmsCountHourly } = update[0].timeseries;
          const newArray: any = [];
          for (const item of createdAlarmsCountHourly) {
            newArray.push([item.ts, item.value]);
          }
          state.alarmList = [[...state.alarmItem], ...newArray];
        }
      } else {
        if (data) {
          const { transportDataPointsCountHourly, transportMsgCountHourly } =
            data.data[0].latest.TIME_SERIES;
          state.dataPoint = [
            transportDataPointsCountHourly.ts,
            transportDataPointsCountHourly.value,
          ];
          state.MsgCount = [
            transportDataPointsCountHourly.ts,
            transportDataPointsCountHourly.value,
          ];
          state.dataPointList.push([
            transportDataPointsCountHourly.ts,
            transportDataPointsCountHourly.value,
          ]);
          state.messageList.push([transportMsgCountHourly.ts, transportMsgCountHourly.value]);
        }
        if (update) {
          const { transportDataPointsCountHourly, transportMsgCountHourly } = update[0].timeseries;
          const newArray: any[] = [];
          const newArray1: any[] = [];
          for (const item of transportDataPointsCountHourly) {
            newArray.push([item.ts, item.value]);
          }
          for (const item of transportMsgCountHourly) {
            newArray1.push([item.ts, item.value]);
          }
          state.dataPointList = [[...state.dataPoint], ...newArray];
          state.messageList = [[...state.MsgCount], ...newArray1];
        }
      }
    },
    onDisconnected() {
      console.log('断开连接了');
      close();
    },
  });
  function onTabChange(key: string) {
    activeKey.value = key;
    if (key === '1') {
      const sendAlarmValue = JSON.stringify({
        entityDataCmds: [
          {
            cmdId: activeKey.value,
            historyCmd: {
              keys: ['createdAlarmsCountHourly'],
              startTs: Date.now() - 86400000,
              endTs: Date.now(),
              interval: 7200000,
              limit: 12,
              agg: 'COUNT',
            },
          },
        ],
      });
      send(sendAlarmValue);
    } else {
      const sendMessageValue = JSON.stringify({
        entityDataCmds: [
          {
            query: {
              entityFilter: {
                type: 'singleEntity',
                singleEntity: entityId,
              },
              pageLink: {
                pageSize: 1024,
                page: 0,
                sortOrder: {
                  key: {
                    type: 'ENTITY_FIELD',
                    key: 'createdTime',
                  },
                  direction: 'DESC',
                },
              },
              entityFields: [
                {
                  type: 'ENTITY_FIELD',
                  key: 'name',
                },
                {
                  type: 'ENTITY_FIELD',
                  key: 'label',
                },
                {
                  type: 'ENTITY_FIELD',
                  key: 'additionalInfo',
                },
              ],
              latestValues: [
                {
                  type: 'TIME_SERIES',
                  key: 'transportMsgCountHourly',
                },
                {
                  type: 'TIME_SERIES',
                  key: 'transportDataPointsCountHourly',
                },
              ],
            },
            cmdId: activeKey.value,
          },
        ],
      });
      const sendMessageValue2 = JSON.stringify({
        entityDataCmds: [
          {
            cmdId: activeKey.value,
            historyCmd: {
              keys: ['transportMsgCountHourly', 'transportDataPointsCountHourly'],
              startTs: Date.now() - 86400000,
              endTs: Date.now(),
              interval: 7200000,
              limit: 12,
              agg: 'COUNT',
            },
          },
        ],
      });
      send(sendMessageValue);
      send(sendMessageValue2);
    }
  }
  // 选择日期
  function onDateChange(_, dateString) {
    activeIndex.value = -1;
    const dateTime = Number(formatToDateTime(dateString, 'x'));
    // 动态发送ws数据
    const sendValue = JSON.stringify({
      entityDataCmds: [
        {
          cmdId: activeKey.value,
          historyCmd: {
            keys:
              activeKey.value === '1'
                ? ['createdAlarmsCountHourly']
                : ['transportMsgCountHourly', 'transportDataPointsCountHourly'],
            startTs: dateTime,
            endTs: dateTime + 86400000,
            interval: 7200000,
            limit: 12,
            agg: 'COUNT',
          },
        },
      ],
    });
    send(sendValue);
  }
  // 快速选择时间
  function quickQueryDate(index: number, value: number) {
    activeIndex.value = index;
    let limit = 12;
    if (value === 604800000) {
      limit = 7;
    } else if (value === 2592000000) {
      limit = 30;
    }
    // 动态发送ws数据
    const sendValue = JSON.stringify({
      entityDataCmds: [
        {
          cmdId: activeKey.value,
          historyCmd: {
            keys:
              activeKey.value === '1'
                ? ['createdAlarmsCountHourly']
                : ['transportMsgCountHourly', 'transportDataPointsCountHourly'],
            startTs: Date.now() - value,
            endTs: Date.now(),
            interval: value > 3600000 ? 7200000 : 300000,
            limit,
            agg: 'COUNT',
          },
        },
      ],
    });
    send(sendValue);

    console.log(value);
  }
</script>

<style scoped lang="less">
  .center {
    display: flex;
    justify-content: center;
    font-size: 16px;
  }
  .active {
    color: #0960bd;
    font-weight: 500;
  }
  .extra-date {
    display: flex;
    align-items: center;
    justify-content: space-between;
    span {
      margin-right: 20px;
      cursor: pointer;
    }
  }
</style>