<script setup>
import useSendEmail from '@/components/debt/useSendEmail';
import Template1 from '@/lib/email/templates/Template1.vue';

const props = defineProps({
  id: Number,
  code: String,
  mode: String // Due/Overdue
});
const { $download, $generateDocument, $getpath, $insertapi, $store } = useNuxtApp();
$store.commit(`selectedPaymentSchedulesForEmailIn${props.mode}`, [props.id]);

const filter = ref({ id: props.id });
const isDownloading = ref({
  docx: false,
  pdf: false,
});
const { contents, send, isSending } = useSendEmail(filter, props.mode === 'Due' ? 13 : 14);

async function downloadEmail(ext) {
  isDownloading.value[ext] = true;
  const doc_code = props.mode === 'Due' ? 'TB_NO_TIEN' : 'TB_NO'
  const genDoc = await $generateDocument({
    doc_code,
    output_filename: `${doc_code}-${props.code}`,
    payment_schedule_id: props.id,
    investor_id: 1,
  });

  const inserted = await $insertapi('file', {
    name: genDoc.data[ext === 'docx' ? 'file' : 'pdf'],
    user: $store.login.id,
    type: 4,
    size: 1000,
    file: genDoc.data[ext === 'docx' ? 'file' : 'pdf']
  });

  const url = `${$getpath()}download/?name=${inserted.file}&type=contract`;
  $download(url, inserted.file);
  isDownloading.value[ext] = false;
}
</script>
<template>
  <Template1 v-if="contents" :content="contents[0]" previewMode />
  <div class="is-flex is-justify-content-center is-gap-1 mt-4">
    <button
      class="button is-primary"
      :class="{ 'is-loading': isSending }"
      @click="send()"
    >
      Gửi thông báo
    </button>
    <button
      class="button"
      :class="{ 'is-loading': isDownloading.docx }"
      @click="downloadEmail('docx')"
    >
      Tải .docx
    </button>
    <button
      class="button"
      :class="{ 'is-loading': isDownloading.pdf }"
      @click="downloadEmail('pdf')"
    >
      Tải .pdf
    </button>
  </div>
</template>
