<script setup>
import Table from "@/components/customUI/Table.vue";
import InventorySettingAddModal from "./InventorySettingAddModal.vue";
import {
  getSettingInventory,
  postSettingInventory,
  getSettingInventoryLog,
  getInventoryExportData,
} from "@/apis/productSetting";
import { ref, onMounted, inject, watch, computed } from "vue";
import useActiveBtn from "@/hooks/useActiveBtn";
const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();
import dayjs from "dayjs";

const { openToast } = inject("app_toast");

const settingColumns = [
  { title: "項目", key: "name" },
  { title: "總庫存量(噸)", key: "total_capacity" },
  // { title: "安全存量(噸)", key: "safety_stock" },
  { title: "每周盤點量(噸)", key: "current_stock" },
  { title: "更新時間", key: "updated_at" },
  { title: "功能", key: "operation" },
];

const recordColumns = [
  { title: "項目", key: "item_name", filter: true },
  { title: "總庫存量(噸)", key: "total_capacity" },
  // { title: "安全存量(噸)", key: "safety_stock" },
  { title: "每周盤點量(噸)", key: "current_stock" },
  { title: "操作類型", key: "type" },
  { title: "最後修改者", key: "user_name", filter: true },
  { title: "日期", key: "time", sort: true },
];

const dataSource = ref([]);
const itemData = ref([
  { full_name: "發酵槽", key: 1 },
  { full_name: "醋池", key: 2 },
  { full_name: "澄清醋", key: 3 },
]);

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_time: dayjs().subtract(30, "day").format("YYYY-MM-DD"),
  end_time: dayjs().format("YYYY-MM-DD"),
});

const formState = ref({});

const loading = ref(false);

const getDataSource = async () => {
  loading.value = true;
  const res = await getSettingInventory();
  if (!res.isSuccess) {
    dataSource.value = [];
  } else {
    dataSource.value = res.data.map((item) => ({
      ...item,
      updated_at: dayjs(item.updated_at).format("YYYY-MM-DD HH:mm:ss"),
    }));
  }
  loading.value = false;
};

const pushDataSource = async (value) => {
  const res = await postSettingInventory(value);
  if (res.isSuccess) {
    getDataSource();
  } else {
    openToast("error", res.msg, "#account_user_modal");
  }
};

const onSearch = async () => {
  // 搜尋邏輯
  searchState.value.start_time = dayjs(dateRange.value[0].value).format(
    "YYYY-MM-DD"
  );
  searchState.value.end_time = dayjs(dateRange.value[1].value).format(
    "YYYY-MM-DD"
  );

  const res = await getSettingInventoryLog(searchState.value);
  if (!res.isSuccess) {
    dataSource.value = [];
  } else {
    dataSource.value = res.data.map((item) => ({
      ...item,
      time: dayjs(item.time).format("YYYY-MM-DD HH:mm:ss"),
    }));
  }
};

const exportFile = async () => {
  const res = await getInventoryExportData({
    start_date: dayjs(dateRange.value[0].value).format("YYYY-MM-DD"),
    end_date: dayjs(dateRange.value[1].value).format("YYYY-MM-DD"),
  }).catch((err) => {
    console.error(err);
  });
};

const openModal = (type, item_id, record) => {
  if (type === 1) {
    formState.value = {
      type: 1,
      item_id: item_id,
      name: record.name,
      total_capacity: record.total_capacity,
      // safety_stock: record.safety_stock,
      current_stock: record.current_stock,
    };
  } else {
    formState.value = {
      type: 2,
      item_id: item_id,
      name: record.name,
      current_stock: 0,
    };
  }
  inventory_setting_modal.showModal();
};

const resetModalForm = () => {
  formState.value = {};
};

onMounted(() => {
  setItems([
    {
      title: "設定",
      key: "setting",
      active: true,
    },
    {
      title: "紀錄",
      key: "record",
      active: false,
    },
  ]);
});

const submitBtns = computed(() => [
  {
    title: "搜尋",
    key: "submit",
    active: false,
    onClick: onSearch,
  },
  {
    title: "匯出",
    key: "export",
    active: false,
    onClick: exportFile,
  },
]);

watch(
  () => selectedBtn.value?.key,
  (key) => {
    dataSource.value = [];
    if (key === "setting") {
      getDataSource();
    } else if (key === "record") {
      onSearch();
    }
  },
  {
    immediate: true,
  }
);
</script>

<template>
  <InventorySettingAddModal
    @pushData="pushDataSource"
    :formState="formState"
    :itemData="itemData"
    @resetModalForm="resetModalForm"
  />
  <div class="w-full custom-border p-4 mb-4">
    <div class="flex flex-wrap items-center justify-start">
      <ButtonGroup
        :items="items"
        :withLine="true"
        class="mr-5"
        :onclick="(e, item) => changeActiveBtn(item)"
      />
      <template v-if="selectedBtn?.key === 'record'">
        <DateGroup
          :items="dateRange"
          :withLine="true"
          :isTopLabelExist="false"
          :isBottomLabelExist="false"
          class="mr-5"
        />
        <ButtonGroup class="ml-5" :items="submitBtns" :withLine="false" />
      </template>
    </div>
  </div>
  <Table
    :columns="selectedBtn?.key === 'setting' ? settingColumns : recordColumns"
    :dataSource="dataSource"
    :loading="loading"
  >
    <template #bodyCell="{ record, column, index }">
      <template v-if="column.key === 'operation'">
        <button
          class="btn btn-sm btn-success text-white mr-2"
          @click.stop.prevent="() => openModal(1, record.item_id, record)"
        >
          設定
        </button>

        <button
          class="btn btn-sm btn-success text-white mr-2"
          @click.stop.prevent="() => openModal(2, record.item_id, record)"
          :disabled="record?.item_id == 2"
        >
          入庫
        </button>
      </template>
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
  <!-- <LineChart /> -->
</template>

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