<script setup>
import * as echarts from "echarts";
import "echarts-liquidfill";
import { onMounted, ref, watch, markRaw } from "vue";

const props = defineProps({
  id: {
    type: String,
    required: true,
  },
  value: {
    type: Number,
    default: 0,
  },
  title: {
    type: String,
    default: "",
  },
  color: {
    type: String,
  },
});

const dom = ref(null);
const chart = ref(null);

const chartOption = ref({
  title: {
    text: props.title,
    textStyle: {
      color: "#fff",
      fontSize: 16,
      align: "center",
    },
    left: "center",
    top: "5%",
  },
  series: [
    {
      type: "liquidFill",
      radius: "85%",
      waveAnimation: true,
      data: [
        {
          value: props.value / 100, // value 從 props 傳入，並轉換為百分比
          direction: "right",
        },
      ],
      color:[props.color],
      outline: {
        show: true,
        borderDistance: 5,
        itemStyle: {
          opacity: 0.9,
          borderWidth: 2,
          shadowBlur: 14,
          shadowColor: "#fff",
          borderColor: props.color,
        },
      },
      backgroundStyle: {
        color: "rgba(0, 0, 0, 0.1)",
      },
      animationDuration: 1000,
      label: {
        show: true,
        color: "#888",
        insideColor: "#fff",
        fontSize: 24,
        fontWeight: 400,
      },
    },
  ],
});

const initChart = () => {
  chart.value = markRaw(echarts.init(dom.value));
  chart.value.setOption(chartOption.value);
};

onMounted(() => {
  initChart();
});

watch(
  () => props.value,
  (newValue) => {
    if (chart.value) {
      chartOption.value.series[0].data = [newValue / 100];
      chart.value.setOption(chartOption.value);
    }
  },
  { immediate: true
   }
);

watch(
  () => props.color, 
  (newColor) => {
    if (chart.value) {
      chartOption.value.series[0].data.itemStyle.normal.color = newColor;
      chart.value.setOption(chartOption.value);
    }
  },
  { immediate: true } 
);

// 新增監聽 title 變化
watch(
  () => props.title,
  (newTitle) => {
    if (chart.value) {
      chartOption.value.title.text = newTitle;
      chart.value.setOption(chartOption.value);
    }
  },
  { immediate: true }
);

defineExpose({
  chart,
});
</script>

<template>
  <div>
    <div :id="id" ref="dom" style="width: 100%; height: 200px"></div>
  </div>
</template>

<style lang="scss" scoped></style>
