<script setup>
import { ref, computed, onMounted } from "vue";
import dayjs from "dayjs";
import useActiveBtn from "@/hooks/useActiveBtn";
import {
  getDashboardProductRecord,
} from "@/apis/dashboard";

const tableLoading = ref(false);
const dataSource = ref([]);

const {
  items: dateRange,
  setItems: setDateItems,
} = useActiveBtn();

const columns = [
  {
    key: "date",
    title: "日期",
  },
  {
    key: "full_name",
    title: "項目",
    width: 80,
  },
  {
    key: "device_value",
    title: "實際生產量(L)",
  },
  {
    key: "target_value",
    title: "目標生產量(L)",
  },
  {
    key: "f2_value",
    title: "二廠實際包裝數",
  },
  {
    key: "f3_value",
    title: "三廠實際包裝數",
  },
  {
    key: "target",
    title: "目標包裝數",
  },
];

const submitBtns = computed(() => [
  {
    title: "查詢",
    key: "search",
    active: true,
    onClick: getRecord,
    disabled: tableLoading.value,
  },
]);

const getRecord = async () => {
  tableLoading.value = true;
  try {
    const res = await getDashboardProductRecord({
      start_time: dayjs(dateRange.value[0].value).format("YYYY-MM-DD"),
      end_time: dayjs(dateRange.value[1].value).format("YYYY-MM-DD"),
    });
    dataSource.value = res.data;
  } catch (error) {
    console.error("Error fetching data:", error);
  } finally {
    tableLoading.value = false;
  }
};

onMounted(() => {
  setDateItems([
    {
      key: "start_time",
      value: dayjs(),
      dateFormat: "yyyy-MM-dd",
      placeholder: "起始日期",
    },
    {
      key: "end_time",
      value: dayjs(),
      dateFormat: "yyyy-MM-dd",
      placeholder: "結束時間",
    },
  ]);
});
</script>

<template>
  <div class="flex flex-row items-end">
    <DateGroup :items="dateRange" :withLine="true" width="500">
      <template #topLeft>日期</template>
    </DateGroup>
    <ButtonGroup :items="submitBtns" :withLine="false" class="ml-8 mr-8 mb-4" />
  </div>

  <Table :loading="tableLoading" :columns="columns" :dataSource="dataSource">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'f2_value'">
        <div v-for="(item, index) in record.data" :key="index">
          <p class="text-start">{{ item.pac }} : {{ item.f2_value }}</p>
        </div>
      </template>
      <template v-else-if="column.key === 'f3_value'">
        <div v-for="(item, index) in record.data" :key="index">
          <p class="text-start">{{ item.pac }} : {{ item.f3_value }}</p>
        </div>
      </template>
      <template v-else-if="column.key === 'target'">
        <div v-for="(item, index) in record.data" :key="index">
          <p class="text-start">{{ item.pac }} : {{ item.target }}</p>
        </div>
      </template>
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
</template>

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

