<script setup>
import ButtonGroup from "@/components/customUI/ButtonGroup.vue";
import DateGroup from "@/components/customUI/DateGroup.vue";
import { computed, ref, onBeforeMount, watch } from "vue";
import useActiveBtn from "@/hooks/useActiveBtn";
import {
  getElectricMeterLog,
  getRefrigerationRoomTemperatureLog,
  getSipLog,
  getCipLog,
  exportElectricMeterLog,
  exportRefrigerationRoomTemperatureLog,
  exportSipLog,
  exportCipLog,
} from "@/apis/report";
import dayjs from "dayjs";

const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();

const dateRange = ref([
  {
    key: "start_at",
    value: dayjs().subtract(30, "day").valueOf(),
    dateFormat: "yyyy-MM-dd",
    placeholder: "起始日期",
  },
  {
    key: "end_at",
    value: dayjs().valueOf(),
    dateFormat: "yyyy-MM-dd",
    placeholder: "結束日期",
  },
]);

const searchState = ref({
  start_date: dayjs().subtract(30, "day").format("YYYY-MM-DD"),
  end_date: dayjs().format("YYYY-MM-DD"),
});

// Table 相關變數
const tableLoading = ref(false);

const columns = ref([]);
const dataSource = ref([]);

const tableColumnsMap = {
  elec: [
    { title: "日期 / 時間", dataIndex: "time", key: "time" },
    { title: "耗電度數", dataIndex: "cumulant", key: "cumulant" },
    { title: "電錶顯示值", dataIndex: "max_value", key: "max_value" },
  ],
  fridge: [
    { title: "年", dataIndex: "year", key: "year" },
    { title: "月", dataIndex: "month", key: "month" },
    { title: "日", dataIndex: "day", key: "day" },
    { title: "星期", dataIndex: "weekday", key: "weekday" },
    { title: "上午溫度℃", dataIndex: "morning_temp", key: "morning_temp" },
    { title: "下午溫度℃", dataIndex: "afternoon_temp", key: "afternoon_temp" },
  ],
  sip: [
    { title: "設備", dataIndex: "full_name", key: "full_name" },
    { title: "日期", dataIndex: "date", key: "date" },
    { title: "開始時間", dataIndex: "start_time", key: "start_time" },
    { title: "結束時間", dataIndex: "end_time", key: "end_time" },
  ],
  cip: [
    { title: "設備", dataIndex: "full_name", key: "full_name" },
    { title: "日期", dataIndex: "date", key: "date" },
    { title: "開始時間", dataIndex: "start_time", key: "start_time" },
    { title: "結束時間", dataIndex: "end_time", key: "end_time" },
  ],
};

const apiFetchMap = {
  elec: getElectricMeterLog,
  fridge: getRefrigerationRoomTemperatureLog,
  sip: getSipLog,
  cip: getCipLog,
};

const apiExportMap = {
  elec: exportElectricMeterLog,
  fridge: exportRefrigerationRoomTemperatureLog,
  sip: exportSipLog,
  cip: exportCipLog,
};

watch(
  selectedBtn,
  (newItems) => {
    columns.value = (newItems && tableColumnsMap[newItems.key]) || [];
    dataSource.value = [];
  },
  { immediate: true }
);

const submit = async (e, type = "") => {
  e?.preventDefault?.();
  e?.stopPropagation?.();

  const key = selectedBtn.value?.key;
  if (!key) return;

  try {
    if (type === "export") {
      const exporter = apiExportMap[key];
      if (exporter) {
        await exporter(searchState.value);
      }
    } else {
      tableLoading.value = true;
      const fetcher = apiFetchMap[key];
      if (fetcher) {
        const res = await fetcher(searchState.value);
        dataSource.value =
          res?.data.map((d) => ({
            ...d,
            time: d?.time ? dayjs(d?.time).format("YYYY-MM-DD HH:mm:ss") : "",
          })) || [];
      } else {
        dataSource.value = [];
      }
    }
  } catch (err) {
    console.error(err);
    dataSource.value = [];
  } finally {
    tableLoading.value = false;
  }
};

const submitBtns = computed(() => [
  {
    title: "查詢",
    key: "submit",
    active: false,
    onClick: submit,
  },
  {
    title: "匯出",
    key: "export",
    active: false,
    onClick: (e) => submit(e, "export"),
  },
]);

onBeforeMount(() => {
  setItems([
    { title: "電表", key: "elec", active: true },
    { title: "冷藏室", key: "fridge", active: false },
    { title: "SIP", key: "sip", active: false },
    { title: "CIP", key: "cip", active: false },
  ]);
});
</script>

<template>
  <h1 class="text-2xl font-extrabold mb-2">報表管理</h1>
  <div class="w-full flex flex-wrap flex-col custom-border p-4 mb-4">
    <ButtonGroup
      :items="items"
      :withLine="true"
      class=""
      :onclick="
        (e, item) => {
          changeActiveBtn(item);
        }
      "
    />
    <div class="flex flex-wrap items-center mt-2">
      <DateGroup
        :items="dateRange"
        :withLine="true"
        :isTopLabelExist="false"
        :isBottomLabelExist="false"
      />
      <ButtonGroup class="ml-5" :items="submitBtns" :withLine="false" />
    </div>
  </div>
  <Table :loading="tableLoading" :columns="columns" :dataSource="dataSource">
  </Table>
</template>

<style lang="scss" scoped></style>
