<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";

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: "查詢",
    key: "submit",
    active: false,
    onClick: search,
    disabled: isSearchDisabled.value,
  },
  // {
  //   title: "匯出",
  //   key: "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 (newValue.work_type === "3") {
      isSearchDisabled.value = false;
    } else if (newSelected) {
      if (newValue.search_type === "date") {
        isSearchDisabled.value = !(
          keys.length ===
          newSelected?.params.length + 2
        );

        initSubmit(keys.length === newSelected?.params.length + 2);
      } else if (newValue.search_type === "serial") {
        isSearchDisabled.value = !(keys.length === newSelected?.params.length);
        initSubmit(keys.length === newSelected?.params.length);
      }
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
</script>

<template>
  <ButtonGroup
    :items="submitBtns"
    :withLine="false"
    v-if="selectedWorkType?.work_type !== 3"
  />

  <button class="btn btn-info" @click.stop.prevent="() => openModal()">
    <font-awesome-icon :icon="['fas', 'plus']" />新增
  </button>
</template>

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