<script setup lang="ts">
import { ref } from "vue";
import { useQuasar } from "quasar";

import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { Optionround } from "@/modules/07_insignia/interface/index/Main";

/** use*/
const $q = useQuasar();
const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader } = mixin;

/** props*/
const props = defineProps({
  profileId: {
    type: String,
  },
  round: {
    type: String,
  },
  optionRound: {
    type: Object,
  },
});

const titleReport = ref<string>(""); //ชื่อรายงาน

/**
 * function ดาวน์โหลดไฟล์
 * @param type ประเภท file
 */
async function downloadDocument(type: string) {
  let round = [];
  if (props.optionRound) {
    round = props.optionRound.find((e: Optionround) => 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(async (e) => {
        messageError($q, JSON.parse(await e.response.data.text()));
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/**
 * function โหลดเอกสาร
 * @param response ข้อมู
 * @param filename ชื่อไฟล์
 */
function 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>
