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

const { t } = useI18n();
const { elecDay_data } = inject("energy_data");
const todayUsage = ref(0);
const demand_chart = ref(null);
const defaultChartOption = ref({
  tooltip: {
    trigger: "axis",
  },
  legend: {
    data: [t("energy.daily_elec")],
    textStyle: {
      color: "#ffffff",
      fontSize: 16,
    },
    orient: "horizontal",
    bottom: "0%",
  },
  grid: {
    top: "10%",
    left: "0%",
    right: "0%",
    bottom: "15%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    splitLine: {
      show: false,
    },
    axisLabel: {
      color: "#ffffff",
    },
    data: [],
  },
  yAxis: {
    type: "value",
    splitLine: {
      show: false,
    },
    axisLabel: {
      color: "#ffffff",
    },
  },
  series: [
    {
      name: t("energy.daily_elec"),
      type: "line",
      data: [],
      smooth: true,
      lineStyle: {
        width: 3,
      },
      itemStyle: {
        color: "#34b7f1",
      },
    },
  ],
});

watch(
  () => elecDay_data.value,
  (newData) => {
    if (newData.length > 0) {
      // 將資料依時間排序（假設 time 欄位格式為 YYYY-MM-DD HH:mm:ss）
      const sortedData = [...newData].sort(
        (a, b) => new Date(a.time) - new Date(b.time)
      );

      // 取出最近 7 筆（假設資料為每天一筆）
      const recent7Data = sortedData.slice(-7);

      const categories = [];
      const seriesData = [];

      recent7Data.forEach((item) => {
        categories.push(item.time.split(" ")[0]); // 取日期部分當 x 軸刻度
        const dailyUsage = (
          item.degreePeak +
          item.degreeHalfPeak +
          item.degreeOffPeak
        ).toFixed(1);
        seriesData.push(dailyUsage);
      });

      // 更新圖表資料
      demand_chart.value.chart.setOption({
        xAxis: {
          data: categories,
        },
        series: {
          data: seriesData,
        },
      });

      todayUsage.value = seriesData[seriesData.length - 1];
    }
  },
  {
    deep: true,
  }
);
</script>

<template>
  <div
    class="card bg-normal relative w-full h-full border border-cyan-300 rounded-sm"
  >
    <div class="card-body">
      <h2 class="card-title">
        {{ $t("energy.latest_elec_consumption") }}
        <p>{{ todayUsage }} kWh</p>
      </h2>
      <LineChart
        id="immediate_demand_chart"
        class="min-h-[250px] max-h-fit w-full"
        :option="defaultChartOption"
        ref="demand_chart"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.bg-normal::after {
  @apply absolute bottom-1 right-1 h-5 w-5 bg-no-repeat z-10 bg-[url('@/assets/img/table/content-box-background05.svg')] bg-center;
  content: "";
}

.bg-normal::before {
  @apply absolute -top-[9px] -left-[11px] -rotate-90 h-8 w-8 bg-no-repeat z-10 bg-[url('@/assets/img/table/content-box-background02.svg')] bg-center;
  content: "";
}
</style>
