<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: "line",
      data: [],
      itemStyle: {
        color: "#62E39A",
      },
      lineStyle: { width: 3 },
    },
  ],
});

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

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

    // 更新圖表數據
    defaultChartOption.value.xAxis.data = months;
    defaultChartOption.value.series[0].data = costBase;
    defaultChartOption.value.series[1].data = costChange;
    defaultChartOption.value.series[2].data = costTotal;
  },
  { 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_elec_consumption") }}
    </div>
    <div class="bar-box">
      <BarChart
        id="electricity_bill_chart"
        class="min-h-[200px] w-full h-full"
        :option="defaultChartOption"
        ref="bill_chart"
      />
    </div>
  </div>
</template>
