HistoryTrendModal.vue 9.43 KB
<script lang="ts" setup>
  import { nextTick, Ref, ref, unref } from 'vue';
  import { getDeviceHistoryInfo } from '/@/api/alarm/position';
  import { Empty, Tooltip, Button } from 'ant-design-vue';
  import { useECharts } from '/@/hooks/web/useECharts';
  import { AggregateDataEnum } from '/@/views/device/localtion/config.data';
  import { useGridLayout } from '/@/hooks/component/useGridLayout';
  import { ColEx } from '/@/components/Form/src/types';
  import { DataSource } from '/@/api/dataBoard/model';
  import { useForm, BasicForm } from '/@/components/Form';
  import { formSchema, SchemaFiled } from '../config/historyTrend.config';
  import { Loading } from '/@/components/Loading';
  import BasicModal from '/@/components/Modal/src/BasicModal.vue';
  import { useModalInner } from '/@/components/Modal';
  import { getAllDeviceByOrg } from '/@/api/dataBoard';
  import { useHistoryData } from '/@/views/device/list/hook/useHistoryData';
  import { BasicTable, useTable } from '/@/components/Table';
  import { LineChartOutlined, BarsOutlined } from '@ant-design/icons-vue';
  import { formatToDateTime } from '/@/utils/dateUtil';

  type DeviceOption = Record<'label' | 'value' | 'organizationId', string>;

  defineEmits(['register']);

  enum Mode {
    TABLE = 'table',
    CHART = 'chart',
  }

  const mode = ref<Mode>(Mode.CHART);

  const chartRef = ref();

  const loading = ref(false);

  const isNull = ref(false);

  const historyData = ref<{ ts: number; value: string; name: string }[]>([]);

  const { deviceAttrs, getDeviceKeys, getSearchParams, setChartOptions, getDeviceAttribute } =
    useHistoryData();

  const { setOptions, destory } = useECharts(chartRef as Ref<HTMLDivElement>);

  function hasDeviceAttr() {
    if (!unref(deviceAttrs).length) {
      return false;
    } else {
      return true;
    }
  }

  const [register, method] = useForm({
    schemas: formSchema(),
    baseColProps: useGridLayout(2, 3, 4) as unknown as ColEx,
    rowProps: {
      gutter: 10,
    },
    labelWidth: 120,
    fieldMapToTime: [
      [SchemaFiled.DATE_RANGE, [SchemaFiled.START_TS, SchemaFiled.END_TS], 'YYYY-MM-DD HH:ss'],
    ],
    submitButtonOptions: {
      loading: loading as unknown as boolean,
    },
    async submitFunc() {
      search();
    },
  });

  const search = async () => {
    // 表单验证
    await method.validate();
    const value = method.getFieldsValue();
    const searchParams = getSearchParams(value);
    if (!hasDeviceAttr()) return;
    // 发送请求
    loading.value = true;
    const res = await getDeviceHistoryInfo(searchParams);
    historyData.value = getTableHistoryData(res);
    loading.value = false;
    // 判断数据对象是否为空
    if (!Object.keys(res).length) {
      isNull.value = false;
      return;
    } else {
      isNull.value = true;
    }

    const selectedKeys = unref(deviceAttrs).find(
      (item) => item.identifier === value[SchemaFiled.KEYS]
    );
    setOptions(setChartOptions(res, selectedKeys));
  };

  const getTableHistoryData = (record: Recordable<{ ts: number; value: string }[]>) => {
    const keys = Object.keys(record);
    const list = keys.reduce((prev, next) => {
      const list = record[next].map((item) => {
        return {
          ...item,
          name: next,
        };
      });
      return [...prev, ...list];
    }, []);
    return list;
  };

  const [registerTable] = useTable({
    showIndexColumn: false,
    showTableSetting: false,
    dataSource: historyData,
    maxHeight: 300,
    size: 'small',
    columns: [
      {
        title: '属性',
        dataIndex: 'name',
      },
      {
        title: '值',
        dataIndex: 'value',
      },
      {
        title: '更新时间',
        dataIndex: 'ts',
        format: (val) => {
          return formatToDateTime(val, 'YYYY-MM-DD HH:mm:ss');
        },
      },
    ],
  });

  const getDeviceDataKey = async (record: DeviceOption) => {
    const { organizationId, value } = record;
    try {
      const options = await getAllDeviceByOrg(organizationId);
      const record = options.find((item) => item.tbDeviceId === value);
      await getDeviceAttribute(record!);
      await nextTick();
      method.updateSchema({
        field: SchemaFiled.KEYS,
        componentProps: {
          options: unref(deviceAttrs).map((item) => ({ label: item.name, value: item.identifier })),
        },
      });
    } catch (error) {
      throw error;
    }
  };

  const handleModalOpen = async () => {
    await nextTick();

    method.setFieldsValue({
      [SchemaFiled.START_TS]: 1 * 24 * 60 * 60 * 1000,
      [SchemaFiled.LIMIT]: 7,
      [SchemaFiled.AGG]: AggregateDataEnum.NONE,
    });

    if (!hasDeviceAttr()) return;

    const { deviceId } = method.getFieldsValue();

    const res = await getDeviceHistoryInfo({
      entityId: deviceId,
      keys: unref(getDeviceKeys).join(),
      startTs: Date.now() - 1 * 24 * 60 * 60 * 1000,
      endTs: Date.now(),
      agg: AggregateDataEnum.NONE,
      limit: 7,
    });
    historyData.value = getTableHistoryData(res);
    // 判断对象是否为空
    if (!Object.keys(unref(historyData)).length) {
      isNull.value = false;
      return;
    } else {
      isNull.value = true;
    }
    setOptions(setChartOptions(res));
  };

  const generateDeviceOptions = (dataSource: DataSource[]) => {
    const record: { [key: string]: boolean } = {};

    const options: DeviceOption[] = [];
    for (const item of dataSource) {
      const { deviceName, gatewayDevice, slaveDeviceId, organizationId } = item;
      let { deviceId } = item;
      if (gatewayDevice && slaveDeviceId) {
        deviceId = slaveDeviceId;
      }
      if (record[deviceId]) continue;
      options.push({
        label: deviceName,
        value: deviceId,
        organizationId,
      });
      record[deviceId] = true;
    }

    return options;
  };

  const [registerModal] = useModalInner(async (dataSource: DataSource[]) => {
    deviceAttrs.value = [];
    loading.value = false;
    const options = generateDeviceOptions(dataSource);
    await nextTick();
    method.updateSchema({
      field: SchemaFiled.DEVICE_ID,
      componentProps({ formActionType }) {
        const { setFieldsValue } = formActionType;
        return {
          options,
          onChange(_, record: DeviceOption) {
            getDeviceDataKey(record);
            setFieldsValue({ [SchemaFiled.KEYS]: null });
          },
        };
      },
    });

    if (options.length && options.at(0)?.value) {
      const record = options.at(0)!;
      await getDeviceDataKey(record);
      try {
        await method.setFieldsValue({ [SchemaFiled.DEVICE_ID]: record.value });
      } catch (error) {}
    }

    await handleModalOpen();
  });

  const handleCancel = () => {
    destory();
  };

  const switchMode = (flag: Mode) => {
    mode.value = flag;
  };
</script>

<template>
  <BasicModal
    @register="registerModal"
    @cancel="handleCancel"
    :destroy-on-close="true"
    :show-ok-btn="false"
    cancel-text="关闭"
    width="70%"
    title="历史趋势"
  >
    <section
      class="flex flex-col p-4 h-full w-full min-w-7/10"
      style="color: #f0f2f5; background-color: #f0f2f5"
    >
      <section class="bg-white my-3 p-2">
        <BasicForm @register="register" />
      </section>
      <section class="bg-white p-3" style="min-height: 350px">
        <div v-show="mode === Mode.CHART" class="flex h-70px items-center justify-end p-2">
          <Tooltip title="图表模式">
            <Button
              :class="[mode === Mode.CHART && '!bg-blue-500 svg:text-light-50']"
              class="!p-2 !children:flex flex justify-center items-center border-r-0"
              @click="switchMode(Mode.CHART)"
            >
              <LineChartOutlined />
            </Button>
          </Tooltip>

          <Tooltip title="列表模式">
            <Button
              class="!p-2 !children:flex flex justify-center items-center"
              @click="switchMode(Mode.TABLE)"
            >
              <BarsOutlined />
            </Button>
          </Tooltip>
        </div>

        <div
          v-show="isNull && mode === Mode.CHART"
          ref="chartRef"
          :style="{ height: '350px', width: '100%' }"
        >
          <Loading :loading="loading" :absolute="true" />
        </div>
        <Empty
          v-if="mode === Mode.CHART"
          class="h-350px flex flex-col justify-center items-center"
          description="暂无数据,请选择设备查询"
          v-show="!isNull"
        />

        <BasicTable v-show="mode === Mode.TABLE" @register="registerTable">
          <template #toolbar>
            <div v-show="mode === Mode.TABLE" class="flex h-70px items-center justify-end p-2">
              <Tooltip title="图表模式">
                <Button
                  class="!p-2 !children:flex flex justify-center items-center border-r-0"
                  @click="switchMode(Mode.CHART)"
                >
                  <LineChartOutlined />
                </Button>
              </Tooltip>

              <Tooltip title="列表模式">
                <Button
                  :class="[mode === Mode.TABLE && '!bg-blue-500 svg:text-light-50']"
                  class="!p-2 !children:flex flex justify-center items-center"
                  @click="switchMode(Mode.TABLE)"
                >
                  <BarsOutlined />
                </Button>
              </Tooltip>
            </div>
          </template>
        </BasicTable>
      </section>
    </section>
  </BasicModal>
</template>

<style scoped></style>