<script setup lang="ts">
import { ref, onMounted } from "vue";
import { VuePDF, usePDF } from "@tato30/vue-pdf";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";

import type { QForm } from "quasar";

const mixin = useCounterMixin();
const {
  date2Thai,
  messageError,
  showLoader,
  hideLoader,
  dialogConfirm,
  success,
} = mixin;
const $q = useQuasar();

const myForm = ref<QForm>();
const pdfSrc = ref<any>();
const numOfPages = ref<number>(0);
const page = ref<number>(1);
const dialog = ref<boolean>(false);
onMounted(async () => {
  await fecthlistRound();
  //   const pdfData = usePDF(
  //     "https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf"
  //   );

  //   setTimeout(() => {
  //     pdfSrc.value = pdfData.pdf.value;
  //     numOfPages.value = pdfData.pages.value;
  //   }, 1000);
  //   console.log(pdfData);
});

const splitterModel = ref(14);
const fileId = ref<string>("");
const selectReport = ref<any>({ id: 39, name: "รายงานขร.1" });
const optionsReport = ref<any>([
  { id: 39, name: "รายงานขร.1" },
  { id: 40, name: "รายงานขร.2" },
  { id: 41, name: "รายงานขร.3" },
  { id: 42, name: "รายงานขร.4" },
]);
const selectList = ref<any>();
const optionsList = ref<any>([{ id: 0, name: "เลือกกรอบการยื่นขอ" }]);

const nextPage = () => {
  if (page.value < numOfPages.value) {
    page.value++;
  }
};
const backPage = () => {
  if (page.value !== 1) {
    page.value--;
  }
};

const backHistory = () => {
  window.history.back();
};

const fecthlistRound = async () => {
  await http
    .get(config.API.listRoundInsignia())
    .then((res: any) => {
      optionsList.value = res.data.result.map((e: any) => ({
        id: e.period_id,
        year: e.period_year,
        name: e.period_name,
      }));
    })
    .catch((err) => {
      console.log(err);
      messageError($q, err);
    });
};

const updateSelect = () => {
  conditionDocument("show");
};

const conditionDocument = (type: string) => {
  myForm.value?.validate().then(async (success: boolean) => {
    if (success) {
      if (type == "show") {
        await downloadReport("pdf", false);
      } else {
        // await downloadReport("pdf", false);
        await downloadReport(type, true);
      }
    }
  });
};

const showDocument = (url: any) => {
  const pdfData = usePDF(url);

  setTimeout(() => {
    pdfSrc.value = pdfData.pdf.value;
    numOfPages.value = pdfData.pages.value;
  }, 1000);
};

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);
};

const downloadReport = async (
  type: string = "pdf",
  download: boolean = true
) => {
  showLoader();
  await http
    .get(
      config.API.reportInsignia(
        selectReport.value.id.toString(),
        type,
        selectList.value.id
      ),
      {
        responseType: "blob",
      }
    )
    .then(async (res) => {
      if (download) {
        downloadFile(
          res,
          `${selectReport.value.name} ${selectList.value.name}.${type}`
        );
      } else {
        const url = URL.createObjectURL(new Blob([res.data]));
        // pdfSrc.value = "";
        // numOfPages.value = 0;
        showDocument(url);
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
</script>

<template>
  <div class="toptitle">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="backHistory"
    />
    รายงาน ขร.1 - ขร.4
  </div>
  <div>
    <q-card flat bordered class="col-12 q-mt-sm">
      <div class="q-pa-md q-gutter-y-sm">
        <q-toolbar style="padding: 0">
          <q-form ref="myForm" class="row items-center">
            <q-select
              use-input
              fill-input
              hide-selected
              class="q-mr-sm"
              dense
              outlined
              v-model="selectReport"
              :options="optionsReport"
              :label="optionsReport.name"
              option-value="id"
              option-label="name"
              style="width: 150px"
              @update:model-value="updateSelect"
            />
            <q-select
              class="q-pa-none"
              use-input
              fill-input
              hide-selected
              dense
              outlined
              v-model="selectList"
              :options="optionsList"
              label="เลือกรอบ"
              option-value="id"
              option-label="name"
              :rules="[(val) => !!val || 'กรุณาเลือกรอบ']"
              @update:model-value="updateSelect"
            />
          </q-form>
          <!-- style="width: 200px" -->
          <q-space />
          <div class="q-pa-ms q-gutter-sm" style="padding: 0">
            <q-btn outline color="primary" icon="download" label="ดาวน์โหลด">
              <q-menu>
                <q-list style="min-width: 150px">
                  <q-item
                    clickable
                    v-close-popup
                    @click="conditionDocument('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="conditionDocument('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="conditionDocument('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>
            <q-btn
              unelevated
              icon="mdi-eye"
              color="primary"
              label="แสดงรายงาน"
              @click="conditionDocument('show')"
            />
            <q-btn
              unelevated
              color="blue"
              icon="mdi-fullscreen"
              @click="dialog = true"
              dense
            />
          </div>
        </q-toolbar>
        <q-splitter
          v-model="splitterModel"
          horizontal
          style="
            height: 70vh;
            border: 1px solid rgb(210, 210, 210);
            border-radius: 5px;
          "
          before-class="overflow-hidden disable"
          separator-class="bg-white disabled"
        >
          <template v-slot:before>
            <div class="q-px-sm">
              <div class="row items-start items-center">
                <div class="col">
                  <q-btn
                    padding="xs"
                    icon="mdi-chevron-left"
                    color="grey-2"
                    text-color="grey-5"
                    size="md"
                    class="my-auto"
                    @click="backPage"
                    :disable="page == 1"
                  />
                </div>
                <div class="col-12 col-md-auto">
                  <div class="q-pa-md flex">
                    หน้าที่ {{ page }} จาก {{ numOfPages }}
                  </div>
                </div>
                <div class="col text-right">
                  <q-btn
                    padding="xs"
                    icon="mdi-chevron-right"
                    color="grey-2"
                    text-color="grey-5"
                    size="md"
                    @click="nextPage"
                    :disable="page === numOfPages"
                  />
                </div>
              </div>
            </div>
          </template>
          <template v-slot:after>
            <div class="q-pa-md">
              <VuePDF ref="vuePDFRef" :pdf="pdfSrc" :page="page" fit-parent />
            </div>
          </template>
          <template v-slot:default>
            <div class="q-pa-md">
              <div class="row items-start items-center">
                <div class="col">
                  <q-btn
                    padding="xs"
                    icon="mdi-chevron-left"
                    color="grey-2"
                    text-color="grey-5"
                    size="md"
                    class="my-auto"
                    @click="backPage"
                    :disable="page == 1"
                  />
                </div>
                <div class="col-12 col-md-auto">
                  <div class="q-pa-md flex">
                    หน้าที่ {{ page }} จาก {{ numOfPages }}
                  </div>
                </div>
                <div class="col text-right">
                  <q-btn
                    padding="xs"
                    icon="mdi-chevron-right"
                    color="grey-2"
                    text-color="grey-5"
                    size="md"
                    @click="nextPage"
                    :disable="page === numOfPages"
                  />
                </div>
              </div>
            </div>
          </template>
        </q-splitter>
      </div>
    </q-card>
  </div>

  <!-- Dialog Full Screen -->
  <q-dialog
    v-model="dialog"
    persistent
    :maximized="true"
    transition-show="slide-up"
    transition-hide="slide-down"
  >
    <q-card class="bg-white">
      <div class="flex justify-end items-center align-center q-mr-md q-mt-sm">
        <q-btn
          icon="close"
          unelevated
          round
          dense
          style="color: #ff8080; background-color: #ffdede"
          size="12px"
          v-close-popup
        />
      </div>
      <div class="q-pa-md">
        <div class="row items-start items-center">
          <div class="col">
            <q-btn
              padding="xs"
              icon="mdi-chevron-left"
              color="grey-2"
              text-color="grey-5"
              size="md"
              class="my-auto"
              @click="backPage"
              :disable="page == 1"
            />
          </div>
          <div class="col-12 col-md-auto">
            <div class="q-pa-md flex">
              หน้าที่ {{ page }} จาก {{ numOfPages }}
            </div>
          </div>
          <div class="col text-right">
            <q-btn
              padding="xs"
              icon="mdi-chevron-right"
              color="grey-2"
              text-color="grey-5"
              size="md"
              @click="nextPage"
              :disable="page === numOfPages"
            />
          </div>
        </div>
        <div class="row items- items-center">
          <VuePDF ref="vuePDFRef" :pdf="pdfSrc" :page="page" fit-parent />
        </div>
        <div class="row items- items-end">
          <div class="col">
            <q-btn
              padding="xs"
              icon="mdi-chevron-left"
              color="grey-2"
              text-color="grey-5"
              size="md"
              class="my-auto"
              @click="backPage"
              :disable="page == 1"
            />
          </div>
          <div class="col-12 col-md-auto">
            <div class="q-pa-md flex">
              หน้าที่ {{ page }} จาก {{ numOfPages }}
            </div>
          </div>
          <div class="col text-right">
            <q-btn
              padding="xs"
              icon="mdi-chevron-right"
              color="grey-2"
              text-color="grey-5"
              size="md"
              @click="nextPage"
              :disable="page === numOfPages"
            />
          </div>
        </div>
      </div>
    </q-card>
  </q-dialog>
</template>

<style lang="scss" scope>
.disabled {
  pointer-events: none;
}
</style>
