<script setup lang="ts">
import { ref } from "vue";
import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";

const $q = useQuasar();
const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader } = mixin;
const props = defineProps({
  profileId: {
    type: String,
  },
  round: {
    type: String,
  },
  optionRound: {
    type: Object,
  },
});

const titleReport = ref<string>("");

const downloadDocument = async (type: string) => {
  let round = [];
  if (props.optionRound) {
    round = props.optionRound.find((e: any) => e.id === props.round);
  }
  titleReport.value = round.name;
  const download: boolean = true;
  if (props.profileId) {
    showLoader();
    await http
      .get(config.API.reportInsignia("46", type, props.profileId), {
        responseType: "blob",
      })
      .then(async (res) => {
        if (download) {
          downloadFile(
            res,
            `ประวัติสำหรับการเสนอขอพระราชทานเหรียญจักรพรรดิมาลา.${type}`
          );
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
};
const downloadFile = (response: any, filename: string) => {
  const link = document.createElement("a");
  var fileName = filename;
  link.href = window.URL.createObjectURL(new Blob([response.data]));
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>
<template>
  <q-btn
    dense
    size="12px"
    flat
    round
    color="primary"
    icon="mdi-download"
    @click.stop
  >
    <q-menu>
      <q-list style="min-width: 150px">
        <q-item clickable v-close-popup @click="downloadDocument('pdf')">
          <q-item-section avatar
            ><q-icon color="red" name="mdi-file-pdf"
          /></q-item-section>
          <q-item-section>ไฟล์ .PDF</q-item-section>
        </q-item>
        <q-item clickable v-close-popup @click="downloadDocument('docx')">
          <q-item-section avatar
            ><q-icon color="blue" name="mdi-file-word"
          /></q-item-section>
          <q-item-section>ไฟล์ .docx</q-item-section>
        </q-item>
        <q-item clickable v-close-popup @click="downloadDocument('xlsx')">
          <q-item-section avatar
            ><q-icon color="green" name="mdi-file-excel"
          /></q-item-section>
          <q-item-section>ไฟล์ .xlsx</q-item-section>
        </q-item>
      </q-list>
    </q-menu>
  </q-btn>
</template>
