index.vue 6.65 KB
<script lang="ts" setup>
  import { EChartsOption, ECharts, init } from 'echarts';
  import { unref, ref, onMounted, computed, nextTick } from 'vue';
  import { ComponentPropsConfigType } from '../../../index.type';
  import { option } from './config';
  import { UpdateTime } from '/@/views/visual/commonComponents/UpdateTime';
  import { useIntervalFn } from '@vueuse/core';
  import { DeviceName } from '/@/views/visual/commonComponents/DeviceName';
  import { isArray } from '/@/utils/is';
  import { useComponentScale } from '/@/views/visual/packages/hook/useComponentScale';
  import { useDataFetch } from '../../../hook/socket/useSocket';
  import { DataFetchUpdateFn } from '../../../hook/socket/useSocket.type';

  const props = defineProps<{
    config: ComponentPropsConfigType<typeof option>;
  }>();

  const chartRefEl = ref<Nullable<HTMLElement>>(null);

  const chartInstance = ref<Nullable<ECharts>>(null);

  const time = ref<Nullable<number>>(null);

  const getDesign = computed(() => {
    const { option, persetOption } = props.config;
    const { componentInfo, attribute, attributeRename, attributeName } = option;
    const {
      fontColor: presetFontColor,
      unit: presetUnit,
      pointerColor: presetPointerColor,
      instrumentPanelColor: presetInstrumentPanelColor,
      progressBarCircle: presetProgressBarCircle,
      gradientInfo: presetGradientInfo,
      showTime: persetShowTime,
      maxNumber: persetMaxNumber,
    } = persetOption || {};
    const {
      unit,
      fontColor,
      pointerColor,
      gradientInfo,
      progressBarCircle,
      instrumentPanelColor,
      showTime,
      maxNumber,
    } = componentInfo || {};
    return {
      unit: unit ?? presetUnit,
      fontColor: fontColor ?? presetFontColor,
      attribute: attributeRename || attributeName || attribute,
      pointerColor: pointerColor ?? presetPointerColor,
      instrumentPanelColor: instrumentPanelColor ?? presetInstrumentPanelColor,
      progressBarCircle: progressBarCircle ?? presetProgressBarCircle,
      gradientInfo: gradientInfo ?? presetGradientInfo,
      showTime: showTime ?? persetShowTime,
      maxNumber: maxNumber || persetMaxNumber,
    };
  });

  const getStageColor = (array) => {
    if (!isArray(array)) {
      return;
    }
    const colorList = array.map((item) => ({
      offset: item.value,
      color: item.color,
    }));
    return colorList as any;
  };

  const titleValue = ref<number>(20);

  const options = (): EChartsOption => {
    const { unit, fontColor, progressBarCircle, gradientInfo, maxNumber } = unref(getDesign);
    const instrumentPanelColor = getStageColor(gradientInfo);
    return {
      title: {
        text: `${titleValue.value} ${unit ?? ''}`,
        top: 'center',
        left: 'center',
        textStyle: {
          fontSize: unref(getRatio) ? 14 * unref(getRatio) : 14,
          color: fontColor || '#65d3ff',
          valueAnimation: true,
        },
      },
      series: [
        {
          type: 'gauge',
          center: ['50%', '50%'],
          min: 0,
          max: maxNumber,
          startAngle: '90',
          endAngle: '-270',
          progress: {
            // 进度条
            show: true,
            roundCap: progressBarCircle,
            width: unref(getRatio) ? 12 * unref(getRatio) : 12,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: instrumentPanelColor,
              },
            },
          },
          axisLine: {
            // 仪表盘
            lineStyle: {
              width: unref(getRatio) ? 12 * unref(getRatio) : 12,
            },
          },
          itemStyle: {
            color: instrumentPanelColor,
          },
          axisTick: {
            show: false,
          },
          pointer: {
            //指针
            show: false,
          },
          splitLine: {
            show: false,
          },
          axisLabel: {
            show: false,
          },
          anchor: {
            show: false,
          },
          title: {
            show: false,
          },
          detail: {
            show: false,
            // valueAnimation: true,
          },
          data: [
            {
              value: 20,
            },
          ],
        },
      ] as any,
    };
  };

  const updateChart = (value: number) => {
    const { unit } = unref(getDesign);
    unref(chartInstance)?.setOption({
      series: [{ data: [{ value: value.toFixed(2) }] }, { data: [{ value: value.toFixed(2) }] }],
      title: [{ text: value + unit }],
    } as EChartsOption);
  };

  const initial = () => {
    chartInstance.value = init(unref(chartRefEl)! as HTMLElement);
    chartInstance.value.setOption(options());
  };

  const randomFn = () => {
    const { unit } = unref(getDesign);
    useIntervalFn(() => {
      const value = (Math.random() * 100).toFixed(0);
      unref(chartInstance)?.setOption({
        series: [{ data: [{ value }] }, { data: [{ value }] }],
        title: [{ text: value + unit }],
      });
    }, 3000);
  };

  const updateFn: DataFetchUpdateFn = (message, attribute) => {
    const { data = {} } = message;
    const [latest] = data[attribute] || [];
    if (!latest.length) return;
    const [timespan, value] = latest;
    time.value = timespan;
    updateChart(isNaN(value as unknown as number) ? 0 : Number(value));
  };

  useDataFetch(props, updateFn);

  onMounted(() => {
    initial();
    !props.config.option.uuid && randomFn();
  });

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

    // 修改echarts大小
    unref(chartInstance)?.setOption({
      series: [
        {
          axisLine: {
            // 仪表盘
            lineStyle: {
              width: 12 * unref(getRatio),
            },
          },
          progress: {
            width: 12 * unref(getRatio),
          },
        },
      ],
      title: {
        textStyle: {
          fontSize: 14 * unref(getRatio),
        },
      },
    });
    unref(chartInstance)?.resize();
  };

  const { getRatio } = useComponentScale(props, resize);
</script>

<template>
  <main
    class="w-full h-full flex flex-col justify-center items-center"
    :class="!getDesign.showTime && 'p-5'"
  >
    <DeviceName :config="config" />
    <div class="flex w-full h-full flex-col justify-center items-center flex-1">
      <div ref="chartRefEl" class="flex-1 w-full h-6/7 flex-col justify-center items-center flex">
      </div>
      <div class="text-gray-500 text-xs text-center truncate">{{
        getDesign.attribute || '湿度'
      }}</div>
    </div>
    <UpdateTime v-if="getDesign.showTime" :time="time" />
  </main>
</template>