<script setup>
import BarChart from "@/components/chart/BarChart.vue";
import { ref, onMounted, computed, watch } from "vue";
import DashboardEmissionModal from "./DashboardEmissionModal.vue";
import { useI18n } from "vue-i18n";
import { getCarbonValue, getTaipower } from "@/apis/energy";
import useBuildingStore from "@/stores/useBuildingStore";
const store = useBuildingStore();
const { t, locale } = useI18n();
const taipower_data = ref([]);
const elecUseDayData = ref([]);
const carbonValue = ref(null);
const carbonData = ref(null);
const search_data = computed(() => {
  return {
    coefficient: carbonValue.value,
    building_guid: store.selectedBuilding?.building_guid || null,
    department_id_list: store.deptList.map((item) => item.key),
    floor_guid_list: store.floorList.map((item) => item.key),
  };
});
const defaultChartOption = ref({
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
  },
  legend: {
    data: [],
    textStyle: {
      color: "#ffffff",
      fontSize: 14,
    },
    orient: "horizontal",
    top: "0%",
  },
  grid: {
    top: "10%",
    left: "0%",
    right: "2%",
    bottom: "0%",
    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");
};

const getData = async (value) => {
  const res = await getTaipower(value);
  if (res.isSuccess) {
    taipower_data.value = res.data
      ? res.data.sort((a, b) => a.day.localeCompare(b.month))
      : [];
  }
};

const getCarbonData = 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) {
      getCarbonData();
    }
  },
  { immediate: true }
);

watch(
  search_data,
  (newValue, oldValue) => {
    if (
      newValue.building_guid &&
      newValue.coefficient &&
      JSON.stringify(newValue) !== JSON.stringify(oldValue)
    ) {
      getData(newValue);
      getElecUseDayData(newValue);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

// 監聽 taipower_data 的變化
watch(
  taipower_data,
  () => {
    // 日期排序（由舊到新）
    const sorted = [...taipower_data.value].sort(
      (a, b) => new Date(a.day) - new Date(b.day)
    );

    // 取最後 7 筆（若不足則全取）
    const recent = sorted.length > 7 ? sorted.slice(-7) : sorted;

    const days = recent.map((item) => item.day);
    const carbonTotal = recent.map((item) => item.carbon);

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

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

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

<template>
  <div class="mb-3 relative">
    <h3 class="font-bold text-xl text-center">
      <span class="text-info">
        {{ $t("energy.daily_carbon_emission_and_reduction") }}
      </span>
    </h3>
    <DashboardEmissionModal :carbonData="carbonData" :getData="getCarbonData" />
  </div>
  <BarChart
    id="electricity_bill_chart"
    class="min-h-[300px] max-h-fit"
    :option="defaultChartOption"
    ref="bill_chart"
  />
</template>
