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

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

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

  useComponentScale(props, async () => {
    await nextTick();
    unref(chartInstance)?.resize();
  });

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

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

  const getDesign = computed(() => {
    const { option, persetOption } = props.config;
    const { componentInfo, attributeRename, attribute } = option;

    const {
      fontColor: presetFontColor,
      unit: presetUnit,
      gradientInfo: presetGradientInfo,
    } = persetOption || {};

    const { unit, fontColor, gradientInfo } = componentInfo || {};
    return {
      unit: unit ?? presetUnit,
      fontColor: fontColor ?? presetFontColor,
      gradientInfo: gradientInfo ?? presetGradientInfo,
      attribute: attributeRename || attribute,
    };
  });

  const getGradient = (key: Gradient, record: ComponentInfoGradientInfoType[] = []) => {
    if (!isArray(record)) return;
    return record.find((item) => item.key === key);
  };

  const options = (): EChartsOption => {
    const { gradientInfo, unit, fontColor } = unref(getDesign);
    const firstRecord = getGradient(Gradient.FIRST, gradientInfo);
    const secondRecord = getGradient(Gradient.SECOND, gradientInfo);
    const thirdRecord = getGradient(Gradient.THIRD, gradientInfo);

    let max = thirdRecord?.value || secondRecord?.value || firstRecord?.value || 100;

    max = Number(
      1 +
        Array(String(max).length - 1)
          .fill(0)
          .join('')
    );

    const firstGradient = firstRecord?.value ? firstRecord.value / max : 0.3;
    const secondGradient = secondRecord?.value ? secondRecord.value / max : 0.7;

    return {
      series: [
        {
          type: 'gauge',
          min: 0,
          max,
          axisLine: {
            lineStyle: {
              width: 20,
              color: [
                [firstGradient, firstRecord?.color || GradientColor.FIRST],
                [secondGradient, secondRecord?.color || GradientColor.SECOND],
                [1, thirdRecord?.color || GradientColor.THIRD],
              ],
            },
          },
          pointer: {
            itemStyle: {
              color: 'inherit',
            },
          },
          axisTick: {
            distance: -30,
            length: 8,
            splitNumber: max / 100,
            lineStyle: {
              color: '#fff',
              width: 2,
            },
          },
          splitLine: {
            distance: -10,
            length: 30,
            lineStyle: {
              color: '#fff',
              width: 4,
            },
          },
          axisLabel: {
            color: 'inherit',
            distance: 5,
            fontSize: 6,
          },
          detail: {
            valueAnimation: true,
            formatter: `{value} ${unit ?? ''}`,
            color: fontColor || 'inherit',
            offsetCenter: [0, '70%'],
            fontSize: 14,
          },
          data: [
            {
              value: 20,
            },
          ],
        },
      ],
    };
  };

  const updateChartFn = (value: number) => {
    unref(chartInstance)?.setOption({
      series: [{ data: [{ value: value.toFixed(2) }] }],
    } as EChartsOption);
  };

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

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

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

  useDataFetch(props, updateFn);

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

<template>
  <main class="w-full h-full flex flex-col justify-center items-center">
    <div ref="chartRefEl" class="flex-1 w-full h-full"> </div>
    <div class="text-center text-gray-500 text-xs truncate">
      {{ getDesign.attribute || '速度' }}
    </div>
    <UpdateTime :time="time" />
  </main>
</template>
