<script setup>
import BarChart from "@/components/chart/BarChart.vue";
import { ref, onMounted, inject, watch } from "vue";
import CarbonEmissionModal from "./CarbonEmissionModal.vue";
import { useI18n } from "vue-i18n";
import { getCarbonValue } from "@/apis/energy";
import useBuildingStore from "@/stores/useBuildingStore";
const store = useBuildingStore();
const { t, locale } = useI18n();
const { taipower_data, carbonValue } = inject("energy_data");
const carbonData = ref(null);
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",
      data: [],
      itemStyle: {
        color: "#17CEE3",
      },
    },
  ],
});

const updateChartNames = () => {
  defaultChartOption.value.legend.data = [t("energy.carbon_equivalent")];
  defaultChartOption.value.series[0].name = t("energy.carbon_equivalent");
};

// 監聽 taipower_data 的變化
watch(
  taipower_data,
  () => {
    // 提取月份和碳排放數據
    const months = taipower_data.value.map((item) => item.month);
    const carbonTotal = taipower_data.value.map((item) => item.carbon);

    // 更新圖表的 xAxis 和 series
    defaultChartOption.value.xAxis.data = months;
    defaultChartOption.value.series[0].data = carbonTotal;
  },
  { deep: true }
);

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

const getData = async () => {
  if (store.selectedBuilding.building_guid) {
    const res = await getCarbonValue(store.selectedBuilding.building_guid);
    carbonData.value = res.data[0];
    carbonValue.value = res.data[0].coefficient;
  }
};

watch(
  () => store.selectedBuilding,
  (newBuilding) => {
    if (newBuilding) {
      getData();
    }
  },
  { immediate: true }
);

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

<template>
  <div class="bg-slate-800 p-3">
    <div class="flex items-center">
      <div class="text-white mb-3 text-base">
        {{ $t("energy.daily_carbon_emission_and_reduction") }}
      </div>
      <CarbonEmissionModal
        :carbonData="carbonData"
        :getData="getData"
      />
    </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>
