<script setup>
import { computed, defineProps, inject, ref, watch } from "vue";
import { getHistoryData, getHistoryExportData } from "@/apis/history";
import useSearchParam from "@/hooks/useSearchParam";
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const { searchParams } = useSearchParam();

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

const { updateTableData, updateLoading } = 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({
      type: searchParams.value.selectedType,
      ...params,
      ...searchParams.value,
    }).catch((err) => {
      isToastOpen.value = {
        open: true,
        content: err.msg,
      };
    });
  } else {
    updateLoading();
    const res = await getHistoryData({
      type: searchParams.value.selectedType,
      table_type:1,
      ...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: t("button.search"),
    key: "submit",
    active: false,
    onClick: submit,
    icon: "search",
    btn: "btn-search",
    disabled: isSearchButtonDisabled.value,
  },
  // {
  //   title:  t("button.export"),
  //   key: "export",
  //   icon: "download",
  //   btn: "btn-export",
  //   active: false,
  //   onClick: (e) => submit(e, "export"),
  //   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="lg:ml-5"
    :items="submitBtns"
    :withLine="false"
    :withBtnClass="true"
  />
</template>

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