<script setup>
import { defineProps, ref, watch, inject, computed } from "vue";
import { getOperationExportRecord } from "@/apis/operation";
import useSearchParam from "@/hooks/useSearchParam";
import useUserInfoStore from "@/stores/useUserInfoStore";
import { downloadExcelByHref } from "@/util/downloadExcel";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { searchParams } = useSearchParam();
const store = useUserInfoStore();

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

const { openModal, search } = inject("operation_modal");

const isSearchDisabled = ref(true);

const exportFile = async () => {
  const res = await getOperationExportRecord(searchParams.value);
  console.log(res);
  const url = `/api/df?path=${res.split("/")[0]}&fileName=${
    res.split("/")[1]
  }&token=${store.user.token}`;

  await downloadExcelByHref(url, res.split("/")[1]);
};

const submitBtns = computed(() => [
  {
    title: t("button.search"),
    key: "submit",
    icon: "search",
    btn: "btn-search",
    active: false,
    onClick: search,
    disabled: isSearchDisabled.value,
  },
  // {
  //   title: t("button.export"),
  //   key: "export",
  //   icon: "download",
  //   btn: "btn-export",
  //   active: false,
  //   onClick: exportFile,
  //   disabled: isSearchDisabled.value,
  // },
]);

const once = ref(true);
const initSubmit = (firstExec) => {
  if (firstExec && once.value) {
    search();
    once.value = false;
  }
};

watch(
  [searchParams, () => props.selectedWorkType],
  ([newValue, newSelected]) => {
    const keys = Object.keys(newValue).filter((v) => v !== "search_type");

    if (newSelected) {
      isSearchDisabled.value = !searchParams.value.sub_system_tag;
      initSubmit(searchParams.value.sub_system_tag);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
</script>

<template>
  <ButtonGroup
    :items="submitBtns"
    :withLine="false"
    :withBtnClass="true"
  />

  <button class="btn btn-add" @click.stop.prevent="() => openModal()">
    <font-awesome-icon :icon="['fas', 'plus']" />{{ $t("button.add") }}
  </button>
</template>

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