index.vue 2.49 KB
<script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref, unref } from 'vue'
import type { ECharts, EChartsOption } from 'echarts'
import { init } from 'echarts'
import { getDefaultOption, getShowValue } from './index.config'
import type { CreateComponentType, RenderComponentExposeType } from '@/core/Library/types'
import type { NodeDataDataSourceJsonType } from '@/api/node/model'
import { useLatestMessageValue } from '@/core/Library/hook/useLatestMessageValue'
import { useOnMessage } from '@/core/Library/hook/useOnMessage'
import { useProductsStore } from '@/store/modules/products'

const props = defineProps<{
  config: CreateComponentType
}>()

const getCellBounds = computed(() => props.config.cellBounds || { width: 300, height: 400, x: 0, y: 0 })

const chartElRef = ref<Nullable<HTMLDivElement>>()

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

const productsStore = useProductsStore()

function initChartInstance() {
  chartInstance.value = init(unref(chartElRef))
  chartInstance.value.setOption(getDefaultOption)
}

const { onMessage } = useOnMessage({
  onReceiveDataSourceMessage(commandSource, message) {
    const { data } = commandSource
    const { attr, deviceName, deviceProfileId } = data as NodeDataDataSourceJsonType
    const { functionName } = productsStore.getObjectModelByIdWithIdentifier(deviceProfileId, (attr as string)) || {}
    const { latestValue } = useLatestMessageValue(message.data, (attr as string))
    unref(chartInstance)?.setOption({
      title: {
        text: `${deviceName || ''} - ${functionName || ''}`,
      },
      series: [{
        data: [{
          value: getShowValue(Number(latestValue)),
          label: {
            show: true,
            position: [20, '40%'],
            width: 100,
            height: 30,
            color: '#000',
            padding: 5,
            fontSize: 20,
            formatter: `${Number(latestValue)} {unit|℃}`,
            rich: {
              unit: {
                fontSize: 14,
              },
            },
          },
        }],
      }],
    } as EChartsOption)
  },
})

onMounted(() => {
  initChartInstance()
})

onUnmounted(() => {
  chartInstance.value?.dispose()
  chartInstance.value = null
})

defineExpose<RenderComponentExposeType>({ onMessage })
</script>

<template>
  <div class="w-full h-full justify-center flex items-center">
    <div
      ref="chartElRef"
      :style="{ width: `${getCellBounds.width}px`, height: `${getCellBounds.height}px` }"
      class="w-full h-full"
    />
  </div>
</template>