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

const { locale, t } = useI18n();
const props = defineProps({
  energyCostData: {
    type: Object,
    required: true,
  },
});

const chartData = ref([]); // 初始化為空陣列

const labels = computed(() => [
  t("dashboard.today"),
  t("dashboard.yesterday"),
  t("dashboard.this_week"),
  t("dashboard.last_week"),
  t("dashboard.this_month"),
  t("dashboard.last_month"),
  t("dashboard.this_year"),
  t("dashboard.last_year"),
]);
const barWidth = 30; // Set barWidth

const barChartOptions = ref({
  xAxis: {
    type: "category",
    data: chartData.value.map((item) => item.category),
    axisLine: { lineStyle: { color: "#fff" } },
  },
  yAxis: { type: "value", show: false },
  series: [], // 初始化為空陣列
  tooltip: {
    trigger: "axis",
    axisPointer: { type: "shadow" },
    formatter: function (params) {
      let tooltipText = `<div>${params[0].axisValueLabel}</div>`;
      const filteredParams = params.filter((item) => item.seriesType === "bar");
      filteredParams.forEach((item) => {
        tooltipText += `<div>${item.marker} ${
          item.value ? item.value : "-"
        }</div>`;
      });

      return tooltipText;
    },
  },
});

function updateChartData(newEnergyCostData) {
  if (newEnergyCostData && newEnergyCostData.compare) {
    // 從 props.energyCostData.compare 中提取資料
    const compareData = newEnergyCostData.compare;

    // 轉換資料格式
    chartData.value = [
      {
        category: t("dashboard.daily_relative_change"),
        this: compareData.day.current,
        last: compareData.day.last,
        change: compareData.day.percentage,
      },
      {
        category: t("dashboard.weekly_relative_change"),
        this: compareData.week.current,
        last: compareData.week.last,
        change: compareData.week.percentage,
      },
      {
        category: t("dashboard.monthly_relative_change"),
        this: compareData.month.current,
        last: compareData.month.last,
        change: compareData.month.percentage,
      },
      {
        category: t("dashboard.yearly_relative_change"),
        this: compareData.year.current,
        last: compareData.year.last,
        change: compareData.year.percentage,
      },
    ];

    // 更新 barChartOptions
    barChartOptions.value = {
      xAxis: {
        type: "category",
        data: chartData.value.map((item) => item.category),
        axisLine: { lineStyle: { color: "#fff" } },
      },
      yAxis: { type: "value", show: false },
      grid: {
        left: "-10%",
        right: "1%",
        bottom: "3%",
        top: "4%",
        containLabel: true,
      },
      series: [
        {
          name: "當前週期",
          data: chartData.value.map((item) => item.this),
          type: "bar",
          barWidth: barWidth,
          barGap: "-10%",
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#186B80" },
              { offset: 1, color: "#50C3E3" },
            ]),
            shadowBlur: 5,
            shadowColor: "rgba(0, 0, 0, 0.3)",
            shadowOffsetY: 2,
            shadowOffsetX: 5,
          },
          z: 3,
        },
        {
          name: "對比週期",
          data: chartData.value.map((item) => item.last),
          type: "bar",
          barWidth: barWidth,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#988F2C" },
              { offset: 1, color: "#FFF26D" },
            ]),
            shadowBlur: 5,
            shadowColor: "rgba(0, 0, 0, 0.3)",
            shadowOffsetY: 2,
            shadowOffsetX: 5,
          },
        },
        {
          // this top
          z: 6,
          type: "pictorialBar",
          symbolPosition: "end",
          data: chartData.value.map((item) => item.this),
          symbol: "diamond",
          symbolOffset: ["-45%", "-50%"],
          symbolSize: [barWidth, barWidth * 0.5],
          itemStyle: {
            borderWidth: 0,
            color: "#50C3E3",
          },
        },
        {
          // this bot
          z: 6,
          type: "pictorialBar",
          symbolPosition: "start",
          data: chartData.value.map((item) => item.this),
          symbol: "diamond",
          symbolOffset: ["-45%", "50%"],
          symbolSize: [barWidth, barWidth * 0.5],
          itemStyle: {
            borderWidth: 0,
            color: "#50C3E3",
          },
        },
        {
          // last top
          z: 3,
          type: "pictorialBar",
          symbolPosition: "end",
          data: chartData.value.map((item) => item.last),
          symbol: "diamond",
          symbolOffset: ["45%", "-50%"],
          symbolSize: [barWidth, barWidth * 0.5],
          itemStyle: {
            borderWidth: 0,
            color: "#FFF26D",
          },
        },
        {
          // last bot
          z: 3,
          type: "pictorialBar",
          symbolPosition: "start",
          data: chartData.value.map((item) => item.last),
          symbol: "diamond",
          symbolOffset: ["45%", "50%"],
          symbolSize: [barWidth, barWidth * 0.5],
          itemStyle: {
            borderWidth: 0,
            color: "#FFF26D",
          },
        },
      ],
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
        formatter: function (params) {
          let tooltipText = `<div>${params[0].axisValueLabel}</div>`;
          const filteredParams = params.filter(
            (item) => item.seriesType === "bar"
          );
          filteredParams.forEach((item) => {
            tooltipText += `<div>${item.marker} ${
              item.value ? item.value : "-"
            }</div>`;
          });

          return tooltipText;
        },
      },
    };
  }
}
// 使用 watch 監聽 energyCostData 的變化
watch(
  () => props.energyCostData,
  (newEnergyCostData) => {
    updateChartData(newEnergyCostData);
  },
  { immediate: true } // 立即執行一次，確保初始資料載入
);

watch(locale, () => {
  updateChartData(props.energyCostData);
});
</script>

<template>
  <div class="flex flex-wrap">
    <div class="w-full chart-data relative px-8 py-3">
      <div class="flex flex-wrap items-center justify-between">
        <h2 class="font-light">
          {{ $t("dashboard.relative_energy_consumption") }}
        </h2>
      </div>
      <div class="h-[180px]">
        <BarChart
          id="dashboard_chart_compare"
          class="h-full"
          :option="barChartOptions"
        />
      </div>

      <!-- 表格數據展示 -->
      <div class="flex justify-between">
        <div
          v-for="(data, index) in chartData"
          :key="index"
          class="w-1/4 text-center mx-1"
        >
          <div
            class="text-sm bg-cyan-900 p-1 border border-cyan-100 border-opacity-20"
          >
            {{ labels[index * 2] }}
          </div>
          <div
            class="text-sm bg-cyan-900 p-1 border border-cyan-100 border-opacity-20"
          >
            {{ data.this ?? "-" }}
          </div>
          <div
            class="text-sm bg-cyan-900 p-1 border border-cyan-100 border-opacity-20"
          >
            {{ labels[index * 2 + 1] }}
          </div>
          <div
            class="text-sm bg-cyan-900 p-1 border border-cyan-100 border-opacity-20"
          >
            {{ data.last ?? "-" }}
          </div>
          <div
            class="text-sm bg-cyan-900 p-1 border border-cyan-100 border-opacity-20"
          >
            <span
              :class="{
                'text-red-500': data.change > 0,
                'text-green-500': data.change < 0,
              }"
            >
              {{
                data.change
                  ? (data.change > 0 ? "+" : "") + data.change + "%"
                  : "-"
              }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chart-data:before {
  @apply absolute right-0 left-2 top-0 h-10 w-10 bg-no-repeat z-10;
  content: "";
  background: url(@ASSET/img/chart-data-background01.svg) center center;
}

.chart-data::after {
  @apply absolute right-0 bottom-0 h-10 w-10 bg-no-repeat z-10;
  content: "";
  background: url(@ASSET/img/chart-data-background02.svg) center center;
}
</style>
