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

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

const { updateTableData } = inject("energy_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 {
    const res = await getHistoryData({
      ...searchParams.value,
      Type:
        route.params.type != 1
          ? 2
          : searchParams.value.Type
          ? searchParams.value.Type
          : 1,
      table_type: route.params.type,
    });
    updateTableData(res.data);
  }
};

const isSearchButtonDisabled = computed(() => {
  if (
    !searchParams.value.Points?.length ||
    !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_id &&
      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>
