<script setup>
import BarChart from "@/components/chart/BarChart.vue";
import { ref, onMounted, inject, watch } from "vue";
import { useI18n } from "vue-i18n";

const { t, locale } = useI18n();
const { taipower_data } = inject("energy_data");

const defaultChartOption = ref({
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
  },
  legend: {
    data: [],
    textStyle: {
      color: "#ffffff",
      fontSize: 14,
    },
    orient: "horizontal",
    bottom: "0%",
  },
  grid: {
    top: "5%",
    left: "0%",
    right: "2%",
    bottom: "15%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: [],
    axisLabel: {
      color: "#ffffff",
    },
  },
  yAxis: {
    type: "value",
    axisLabel: {
      color: "#ffffff",
    },
  },
  series: [
    {
      name: "",
      type: "bar",
      stack: "total",
      data: [],
      itemStyle: {
        color: "#17CEE3",
      },
    },
    {
      name: "",
      type: "bar",
      stack: "total",
      data: [],
      itemStyle: {
        color: "#E4EA00",
      },
    },
    {
      name: "",
      type: "bar",
      stack: "total",
      data: [],
      itemStyle: {
        color: "#62E39A",
      },
    },
  ],
});

const updateChartNames = () => {
  defaultChartOption.value.legend.data = [
    t("energy.peak"),
    t("energy.semi_peak"),
    t("energy.off_peak"),
  ];
  defaultChartOption.value.series[0].name = t("energy.peak");
  defaultChartOption.value.series[1].name = t("energy.semi_peak");
  defaultChartOption.value.series[2].name = t("energy.off_peak");
};

// 監聽 taipower_data，並更新圖表數據
watch(
  taipower_data,
  () => {
    // 提取資料並更新圖表
    const months = taipower_data.value.map((item) => item.month);
    const kWhPeak = taipower_data.value.map((item) => item.kWhPeak);
    const kWhHalfPeak = taipower_data.value.map((item) => item.kWhHalfPeak);
    const kWhOffPeak = taipower_data.value.map((item) => item.kWhOffPeak);

    // 更新圖表數據
    defaultChartOption.value.xAxis.data = months;
    defaultChartOption.value.series[0].data = kWhPeak;
    defaultChartOption.value.series[1].data = kWhHalfPeak;
    defaultChartOption.value.series[2].data = kWhOffPeak;
  },
  { deep: true }
);

// 監聽 locale 變化
watch(locale, () => {
  updateChartNames();
});

onMounted(() => {
  updateChartNames();
});
</script>

<template>
  <div class="bg-slate-800 p-3">
    <div class="text-white mb-3 text-base">
      {{ $t("energy.monthly_bill_power") }}
    </div>
    <div class="bar-box">
      <BarChart
        id="billing_degree_chart"
        class="min-h-[200px] w-full h-full"
        :option="defaultChartOption"
        ref="degree_chart"
      />
    </div>
  </div>
</template>

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