index.vue 9.04 KB
<template>
  <div>
    <n-space vertical>
      <div class="form">
        <n-date-picker size="small" :to="true" clearable v-model:value="queryCondition.timeRange" type="datetimerange"
          :shortcuts="rangeShortcuts" format="yyyy-MM-dd" @change="queryCondition.interval = null" />
        <n-select v-model:value="queryCondition.agg" size="small" :options="aggOptions" clearable
          @change="handleAggChange" />
        <n-input-number :min="7" :max="50000" size="small" v-if="queryCondition.agg === 'NONE'"
          v-model:value="queryCondition.limit" clearable />
        <n-select v-if="queryCondition.agg !== 'NONE'" size="small" v-model:value="queryCondition.interval"
          :options="getPacketIntervalByRange(queryCondition.timeRange)" />
      </div>
    </n-space>
    <v-chart ref="vChartRef" :init-options="initOptions" :theme="themeColor" :option="option" :manual-update="isPreview()"
      :update-options="{
        replaceMerge: replaceMergeArr
      }" autoresize @mouseover="handleHighlight" @mouseout="handleDownplay">
    </v-chart>
  </div>
</template>

<script setup lang="ts">
import { PropType, computed, watch, ref, nextTick, onMounted, toRefs } from 'vue'
import VChart from 'vue-echarts'
import { useCanvasInitOptions } from '@/hooks/useCanvasInitOptions.hook'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import config, { includes, seriesItem } from './config'
import { mergeTheme } from '@/packages/public/chart'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { useChartDataFetch } from '@/hooks'
import { isPreview } from '@/utils'
import { DatasetComponent, GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import isObject from 'lodash/isObject'
import cloneDeep from 'lodash/cloneDeep'
import dataJson from './data.json'
import { useFullScreen } from '../../utls/fullScreen'
import { useAssembleDataHooks } from '@/hooks/external/useAssembleData.hook'
import { SocketReceiveMessageType } from '@/store/external/modules/socketStore.d'
import { useChartInteract } from '@/hooks/external/useChartSelectDeviceInteract.hook'
import { getPacketIntervalByRange } from './helper'

const props = defineProps({
  themeSetting: {
    type: Object,
    required: true
  },
  themeColor: {
    type: Object,
    required: true
  },
  chartConfig: {
    type: Object as PropType<config>,
    required: true
  }
})

const initOptions = useCanvasInitOptions(props.chartConfig.option, props.themeSetting)

const { queryCondition } = toRefs(props.chartConfig.option)

use([DatasetComponent, CanvasRenderer, LineChart, GridComponent, TooltipComponent, LegendComponent])

const chartEditStore = useChartEditStore()

const replaceMergeArr = ref<string[]>()

const aggOptions = [
  { label: '最小值', value: 'MIN' },
  { label: '最大值', value: 'MAX' },
  { label: '平均值', value: 'AVG' },
  { label: '求和', value: 'SUM' },
  { label: '计数', value: 'COUNT' },
  { label: '空', value: 'NONE' }
]

const rangeShortcuts = {
  昨天: () => {
    const cur = new Date().getTime()
    return [cur - 86400000, cur] as const
  },
  最近7天: () => {
    const cur = new Date().getTime()
    return [cur - 604800000, cur] as const
  },
  最近30天: () => {
    const cur = new Date().getTime()
    return [cur - 2592000000, cur] as const
  }
}

const option = computed(() => {
  return mergeTheme(props.chartConfig.option, props.themeSetting, includes)
})

// dataset 无法变更条数的补丁
watch(
  () => props.chartConfig.option.dataset,
  (newData: { dimensions: any }, oldData) => {
    try {
      if (!isObject(newData) || !('dimensions' in newData)) return
      if (Array.isArray(newData?.dimensions)) {
        const seriesArr = []
        // 对oldData进行判断,防止传入错误数据之后对旧维度判断产生干扰
        // 此处计算的是dimensions的Y轴维度,若是dimensions.length为0或1,则默认为1,排除X轴维度干扰
        const oldDimensions =
          Array.isArray(oldData?.dimensions) && oldData.dimensions.length >= 1 ? oldData.dimensions.length : 1
        const newDimensions = newData.dimensions.length >= 1 ? newData.dimensions.length : 1
        const dimensionsGap = newDimensions - oldDimensions
        if (dimensionsGap < 0) {
          props.chartConfig.option.series.splice(newDimensions - 1)
        } else if (dimensionsGap > 0) {
          if (!oldData || !oldData?.dimensions || !Array.isArray(oldData?.dimensions) || !oldData?.dimensions.length) {
            props.chartConfig.option.series = []
          }
          for (let i = 0; i < dimensionsGap; i++) {
            seriesArr.push(cloneDeep(seriesItem))
          }
          props.chartConfig.option.series.push(...seriesArr)
        }
        replaceMergeArr.value = ['series']
        nextTick(() => {
          replaceMergeArr.value = []
        })
      }
    } catch (error) {
      console.log(error)
    }
  },
  {
    deep: false
  }
)

let seriesDataNum = -1
let seriesDataMaxLength = 0
let intervalInstance: any = null
const duration = 1500

// 会重新选择需要选中和展示的数据
const handleSeriesData = () => {
  if (seriesDataNum > -1) {
    vChartRef.value?.dispatchAction({
      type: 'downplay',
      dataIndex: seriesDataNum
    })
  }
  seriesDataNum = seriesDataNum >= seriesDataMaxLength - 1 ? 0 : seriesDataNum + 1
  vChartRef.value?.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: seriesDataNum
  })
}

// 新增轮播
const addPieInterval = (newData?: typeof dataJson, skipPre = false) => {
  if (!skipPre && !Array.isArray(newData?.source)) return
  if (!skipPre) seriesDataMaxLength = newData?.source.length || 0
  clearInterval(intervalInstance)
  intervalInstance = setInterval(() => {
    handleSeriesData()
  }, duration)
}

// 取消轮播
const clearPieInterval = () => {
  vChartRef.value?.dispatchAction({
    type: 'hideTip',
    seriesIndex: 0,
    dataIndex: seriesDataNum
  })
  vChartRef.value?.dispatchAction({
    type: 'downplay',
    dataIndex: seriesDataNum
  })
  clearInterval(intervalInstance)
  intervalInstance = null
}

// 处理鼠标聚焦高亮内容
const handleHighlight = () => {
  clearPieInterval()
}

// 处理鼠标取消悬浮
const handleDownplay = () => {
  if (props.chartConfig.option.isCarousel && !intervalInstance) {
    // 恢复轮播
    addPieInterval(undefined, true)
  }
}

watch(
  () => props.chartConfig.option.isCarousel,
  newData => {
    if (newData) {
      addPieInterval(undefined, true)
      props.chartConfig.option.legend.show = false
    } else {
      props.chartConfig.option.legend.show = true
      clearPieInterval()
    }
  }
)

//fix 修复v-chart图表绑定联动组件视图不更新问题
const updateVChart = async (newData: SocketReceiveMessageType) => {
  //区分是普通请求还是ws请求
  if (!isObject(newData) || !('dimensions' in newData)) {
    const { data } = newData
    const { keys, record } = useAssembleDataHooks(data)
    vChartRef.value?.setOption({
      dataset: {
        dimensions: ['ts', ...keys],
        source: [record]
      }
    })
  } else {
    //异步更新,同步更新会造成联动组件控制,图表不及时更新
    await nextTick().then(() => {
      vChartRef.value?.setOption(
        {
          ...option.value,
          dataset: newData
        },
        {
          notMerge: true
        }
      )
    })
  }
}

const { vChartRef } = useChartDataFetch(props.chartConfig, useChartEditStore, (newData: any, targetComponent: any) => {
  props.chartConfig.option.queryCondition.timeRange=[targetComponent.requestParams.Params.startTs,targetComponent.requestParams.Params.endTs]
  //联动支持分组
  /**
   * 修复多个分组,然后下拉框联动,会影响另一个组件
   */
  chartEditStore.getComponentList.forEach(targetItem => {
    if (targetItem.isGroup) {
      targetItem.groupList?.forEach(groupItem => {
        if (groupItem.id === props.chartConfig.id) {
          groupItem.option.dataset = newData
        }
      })
    } else {
      if (targetItem.id === props.chartConfig.id) {
        targetItem.option.dataset = newData
      }
    }
  })
  //
  updateVChart(newData)
})

const handleAggChange = (value: string) => {
  if (value === 'NONE') queryCondition.value.interval = null
}

onMounted(() => {
  seriesDataMaxLength = dataJson.source.length
  if (props.chartConfig.option.isCarousel) {
    addPieInterval(undefined, true)
  }
})

watch(
  () => queryCondition.value,
  newValue => {
    const obj = {
      startTs: newValue.timeRange.at(-2),
      endTs: newValue.timeRange.at(-1),
      limit: newValue.limit,
      agg: newValue.agg,
      interval: newValue.interval
    }
    if (newValue.agg !== 'NONE') {
      Reflect.deleteProperty(obj, 'limit')
    }
    onChange(obj)
  },
  {
    deep: true
  }
)

// 监听事件改变
const onChange = (v: object) => {
  // 存储到联动数据
  useChartInteract(props.chartConfig, useChartEditStore, { data: v })
}

</script>

<style lang="scss" scoped>
.form {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr;
  gap: 8px;
}
</style>