<script setup>
import { computed, defineProps, inject, ref, watch } from "vue";
import { getHistoryData, getHistoryExportData } from "@/apis/history";
import useSearchParam from "@/hooks/useSearchParam";

const { searchParams } = useSearchParam();

const props = defineProps({
  form: Object
});

const { updateTableData, updateLoading, openModal } = inject("history_table_data");

let isToastOpen = ref({
  open: false,
  content: "",
});

const cancelToastOpen = () => {
  isToastOpen.value = {
    open: false,
    content: "",
  };
};


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

  const formData = new FormData(props.form);

  let params = {};
  for (const pair of formData.entries()) {
    console.log(pair[0], pair[1]);
    params = { ...params, [pair[0]]: pair[1] };
  }

  if (type === "export") {
    const res = await getHistoryExportData({
      ...params,
      ...searchParams.value,
    }).catch((err) => {
      isToastOpen.value = {
        open: true,
        content: err.msg,
      };
    });
  }else if(type === "chart"){
    updateLoading();
    const res = await getHistoryData({
      ...params,
      ...searchParams.value,
    });
    await updateTableData(res.data);
    updateLoading();
    openModal();
  } else {
    updateLoading();
    const res = await getHistoryData({
      ...params,
      ...searchParams.value,
    });
    updateTableData(res.data);
    updateLoading();
  }
};

const isSearchButtonDisabled = computed(() => {
  if (
    !searchParams.value.Type ||
    !searchParams.value.Points?.length ||
    !searchParams.value.sub_system_tag ||
    !searchParams.value.Device_list?.length
  ) {
    return true;
  } else {
    return false;
  }
});

const submitBtns = computed(() => [
  {
    title: "查詢",
    key: "submit",
    active: false,
    onClick: submit,
    disabled: isSearchButtonDisabled.value,
  },
  {
    title: "匯出",
    key: "export",
    active: false,
    onClick: (e) => submit(e, "export"),
    disabled: isSearchButtonDisabled.value,
  },
  {
    title: "統計圖表",
    key: "chart",
    active: false,
    onClick: (e) => submit(e, "chart"),
    disabled: isSearchButtonDisabled.value,
  },
]);

const once = ref(false);
watch(
  searchParams,
  (newVal) => {
    if (
      newVal.Type &&
      newVal.Points?.length &&
      newVal.sub_system_tag &&
      newVal.Device_list?.length
    ) {
      if (!once.value) {
        once.value = true;
        submit();
      }
    }
  },
  {
    deep: true,
  }
);
</script>

<template>
    <Toast
    :content="isToastOpen.content"
    :open="isToastOpen.open"
    status="info"
    :cancel="cancelToastOpen"
  />
  <ButtonGroup class="ml-5" :items="submitBtns" :withLine="false" />
</template>

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