<script lang="ts" setup>
import { useSealStore } from '@/stores/sealStore'
import * as echarts from 'echarts'
import { onUnmounted, ref, watchEffect } from 'vue'

const sealStore = useSealStore()
const chartRef = ref<HTMLElement | null>(null)
const realTimePressure = ref(sealStore.sealInfo.pressure)
let myChart: echarts.ECharts | null = null

watchEffect(() => {
  realTimePressure.value = sealStore.sealInfo.pressure
  const pressure = sealStore.sealInfo?.pressure || 0
  if (!myChart && chartRef.value) {
    initChart() // 首次初始化图表
  }
  if (myChart) {
    myChart.setOption({
      series: [{
        data: [{ value: pressure }],
      }],
    })
  }
})
const initChart = () => {
  if (!chartRef.value) {
    return
  }
  myChart = echarts.init(chartRef.value)
  const option = {
    tooltip: {
      formatter: '{a} <br/>{b} : {c}%',
    },
    series: [
      {
        name: 'Pressure',
        type: 'gauge',
        max: 6,
        progress: {
          show: true,
          width: 5,
        },
        axisLine: {
          lineStyle: {
            width: 5,
          },
        },
        detail: {
          valueAnimation: true,
          formatter: '{value}Kp',
        },
        data: [
          {
            value: realTimePressure.value,
          },
        ],
      },
    ],
  }
  myChart.setOption(option)
}
// 组件卸载时释放资源
onUnmounted(() => {
  if (myChart) {
    myChart.dispose() // 销毁图表实例
    myChart = null
  }
})
</script>

<template>
  <div ref="chartRef" style="width: 40vw; height: 30vw" />
</template>

<style>
  canvas{
    width: 60vw !important;
    height: 70vh !important;
  }
</style>
