<script setup lang="ts">
import { onMounted, ref, watch, computed } from "vue";
import { VuePDF, usePDF } from "@tato30/vue-pdf";
import { useQuasar } from "quasar";
import type { PDFDocumentLoadingTask } from "pdfjs-dist/types/src/display/api";
import axios from "axios";

import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import genReport from "@/plugins/genreport";
import genReportXLSX from "@/plugins/genreportxlsx";

import type { DataFileOrder } from "@/modules/18_command/interface/response/Main";

import { useCounterMixin } from "@/stores/mixin";

import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader } = mixin;

const commandId = ref<string>(route.params.id.toString());
const props = defineProps({
  formCommandList: { type: Object, required: true },
});

const isAttachment = defineModel<boolean>("isAttachment", { required: true });

const tab = ref<string>("main"); //tab
const page = ref<number>(1);
const numOfPages = ref<number>(0); //จำนวนหน้า pdf
const pdfSrc = ref<PDFDocumentLoadingTask | undefined>(); // ตัวแปรเก็บ เเสดง pdf

const dialog = ref<boolean>(false); // เปิด dialog
const isLoadView = ref<boolean>(false);
const dataCover = ref<DataFileOrder>(); //ข้อมูลไฟล์คำสั่ง
const dataAttachment = ref<DataFileOrder>(); //ข้อมูลไฟล์แบนท้าย

/**
 * ฟังก์ชันดึงข้อมูลโหลดไฟล์คำสั่ง
 * @param type ประเภท cover เป็นคำสั่ง attachment เป็น แบนท้าย
 */
async function fetchDataCommand(type: string) {
  await http
    .get(config.API.commandAction(commandId.value, `tab4/${type}`))
    .then(async (res) => {
      const dataMain = await res.data.result;
      if (type === "cover") {
        dataCover.value = dataMain;
        await fetchPDF(dataCover.value);
      } else {
        dataAttachment.value = dataMain;
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** ฟังชั่นกำหนดค่าของ PDF*/
async function fetchPDF(data: any, type: string = "docx?folder=command") {
  isLoadView.value = false;
  pdfSrc.value = undefined;
  page.value = 1;
  await axios
    .post(config.API.reportTemplate + `/${type}`, data, {
      headers: {
        accept: "application/pdf",
        "content-Type": "application/json",
      },
      responseType: "blob",
    })
    .then(async (res) => {
      const blob = new Blob([res.data]);
      const objectUrl = URL.createObjectURL(blob);
      const pdfData = usePDF(`${objectUrl}`);
      setTimeout(() => {
        pdfSrc.value = pdfData.pdf.value;
        numOfPages.value = pdfData.pages.value;
        isLoadView.value = true;
      }, 1500);
    })
    .catch(async (e) => {
      messageError($q, e);
      isLoadView.value = true;
    });
}

/**
 * ฟังชั่นดาวห์โหลดไฟล์
 * @param type pdf/docx
 */
async function downloadCover(type: string) {
  if (tab.value === "main") {
    genReport(
      dataCover.value,
      `คำสั่ง ${props.formCommandList.issue}`,
      type,
      "?folder=command"
    );
  } else {
    genReportXLSX(
      dataAttachment.value,
      `เอกสารแนบท้าย ${props.formCommandList.issue}`,
      type,
      "?folder=command"
    );
  }
}

/**
 * เปลี่ยน tab
 * @param val ชื่อ tab
 */
function setTab(val: string) {
  tab.value = val;
  page.value = 1;
}

/**
 * ดึง class ตามที่ set ไว้
 */
function getClass(val: boolean) {
  return {
    "card-header-active q-px-lg q-py-md cursor-pointer": val,
    "card-header q-px-lg q-py-md cursor-pointer": !val,
  };
}

/**
 * check tab เมื่อมีการเปลี่ยน tab
 */
watch(tab, () => {
  if (tab.value === "main") {
    fetchPDF(dataCover.value);
  }
  if (tab.value === "second") {
    fetchPDF(dataAttachment.value, "xlsx?folder=command");
  }
});

const canGoPrevious = computed(() => page.value > 1);
const canGoNext = computed(() => page.value < numOfPages.value);

function goToPreviousPage() {
  if (canGoPrevious.value) {
    page.value -= 1;
  }
}

function goToNextPage() {
  if (canGoNext.value) {
    page.value += 1;
  }
}

/** hook */
onMounted(async () => {
  showLoader();
  const promises = [fetchDataCommand("cover")];
  if (isAttachment.value) {
    promises.push(fetchDataCommand("attachment"));
  }
  await Promise.all(promises).finally(() => {
    hideLoader();
  });
});
</script>

<template>
  <div class="space">
    <div @click="setTab('main')" :class="getClass(tab == 'main')">
      <div class="q-pr-sm">คำสั่ง</div>
    </div>

    <div
      v-if="isAttachment"
      @click="setTab('second')"
      :class="getClass(tab == 'second')"
    >
      <div class="q-pr-sm">เอกสารแนบท้าย</div>
    </div>
    <q-space />
    <q-btn
      class="text-dark"
      flat
      dense
      icon="mdi-fullscreen"
      color="primary"
      @click="dialog = true"
    />
  </div>
  <q-separator style="margin-top: -1px; z-index: 1" />
  <div class="q-pa-sm">
    <div class="q-pa-sm row q-gutter-sm">
      <q-btn
        outline
        color="red"
        icon="mdi-file-pdf"
        label="ดาวน์โหลดไฟล์ PDF"
        @click="downloadCover('pdf')"
        class="q-px-sm"
      >
      </q-btn>

      <q-btn
        v-if="tab === 'main'"
        outline
        class="q-px-sm"
        color="blue"
        icon="mdi-file-word"
        label="ดาวน์โหลดไฟล์ docx"
        @click="downloadCover('docx')"
      />

      <q-btn
        v-else
        outline
        class="q-px-sm"
        color="green"
        icon="mdi-file-excel"
        label="ดาวน์โหลดไฟล์ xlsx"
        @click="downloadCover('xlsx')"
      />
    </div>
    <q-card bordered class="card-pdf q-mx-sm q-pa-md">
      <div class="justify-between items-center align-center q-pb-sm row">
        <q-btn
          class="text-dark bg-grey-4"
          flat
          dense
          @click="page = page > 1 ? page - 1 : page"
        >
          <q-icon name="mdi-chevron-left" />
        </q-btn>

        <span class="body-2 grey--text">
          หน้าที่ {{ page }} จาก {{ numOfPages }}
        </span>

        <q-btn
          class="text-dark bg-grey-4"
          flat
          dense
          @click="page = page < numOfPages ? page + 1 : page"
        >
          <q-icon name="mdi-chevron-right" />
        </q-btn>
      </div>
      <div class="pdfWidth" v-if="isLoadView">
        <VuePDF ref="vuePDFRef" :pdf="pdfSrc" :page="page" fit-parent />
      </div>
      <div class="full-width row flex-center text-accent q-gutter-sm" v-else>
        <span
          ><div
            style="
              height: 60vh;
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
            "
            class="text-grey-5"
          >
            <q-spinner color="primary" size="3em" :thickness="10" />
          </div>
        </span>
      </div>
    </q-card>
  </div>

  <q-dialog
    v-model="dialog"
    persistent
    :maximized="true"
    transition-show="slide-up"
    transition-hide="slide-down"
  >
    <q-card class="column full-height bg-grey-2">
      <DialogHeader
        :tittle="tab === 'main' ? 'คำสั่ง' : 'เอกสารแนบท้าย'"
        :close="() => (dialog = false)"
        class="bg-white"
      />
      <q-separator />
      <div
        class="bg-white q-py-xs q-px-md row justify-center items-center q-gutter-sm shadow-1"
      >
        <q-btn
          flat
          round
          icon="mdi-chevron-left"
          :disable="!canGoPrevious"
          @click="goToPreviousPage"
          color="primary"
        />

        <q-chip
          outline
          color="primary"
          label-color="grey-9"
          class="q-px-lg text-weight-bold"
        >
          หน้า {{ page }} / {{ numOfPages || "-" }}
        </q-chip>

        <q-btn
          flat
          round
          icon="mdi-chevron-right"
          :disable="!canGoNext"
          @click="goToNextPage"
          color="primary"
        />
      </div>

      <q-card-section class="col scroll q-pa-md flex flex-center">
        <div class="pdf-viewer-wrapper shadow-5">
          <VuePDF ref="vuePDFRef" :pdf="pdfSrc" :page="page" fit-parent />
        </div>
      </q-card-section>

      <q-page-sticky position="bottom-right" :offset="[20, 20]">
        <q-btn-dropdown color="primary" icon="download" fab>
          <q-list>
            <q-item clickable v-close-popup @click="downloadCover('pdf')">
              <q-item-section avatar>
                <q-icon name="mdi-file-pdf" color="red" />
              </q-item-section>
              <q-item-section>
                <q-item-label>ดาวน์โหลดไฟล์ PDF</q-item-label>
              </q-item-section>
            </q-item>

            <q-item
              v-if="tab === 'main'"
              clickable
              v-close-popup
              @click="downloadCover('docx')"
            >
              <q-item-section avatar>
                <q-icon name="mdi-file-word" color="blue" />
              </q-item-section>
              <q-item-section>
                <q-item-label>ดาวน์โหลดไฟล์ Word</q-item-label>
              </q-item-section>
            </q-item>

            <q-item
              v-else
              clickable
              v-close-popup
              @click="downloadCover('xlsx')"
            >
              <q-item-section avatar>
                <q-icon name="mdi-file-excel" color="green" />
              </q-item-section>
              <q-item-section>
                <q-item-label>ดาวน์โหลดไฟล์ xlsx</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>
        <!-- <q-btn fab size="xl" icon="mdi-download" color="primary">
          <q-menu>
            <q-list dense style="min-width: 180px">
              <q-item clickable v-close-popup>
                <q-item-section style="min-width: 0px" avatar>
                  <q-tooltip>ประวัติการแก้ไข</q-tooltip>
                  <q-icon
                    color="deep-purple"
                    flat
                    dense
                    round
                    name="mdi-history"
                    size="xs"
                  />
                </q-item-section>
                <q-item-section>ประวัติการแก้ไข</q-item-section>
              </q-item>
              <q-item clickable v-close-popup>
                <q-item-section style="min-width: 0px" avatar>
                  <q-tooltip>รายละเอียด</q-tooltip>
                  <q-icon
                    flat
                    dense
                    round
                    color="info"
                    name="mdi-eye"
                    size="xs"
                  />
                </q-item-section>
                <q-item-section>รายละเอียด</q-item-section>
              </q-item>
            </q-list>
          </q-menu>
          <q-tooltip>ดาวน์โหลดไฟล์ PDF</q-tooltip>
        </q-btn> -->
      </q-page-sticky>
    </q-card>
  </q-dialog>
</template>

<style scoped lang="scss">
.space {
  background-color: #e9eaec61;
  display: flex;
  z-index: 3;
  min-height: 40px;
}

.card-header-active {
  margin-top: 5px;
  margin-left: -1px;
  background-color: white;
  padding: 2px !important;
  border-radius: 10px 10px 0px 0px;
  border: 1px solid #e9eaec;
  width: 200px;
  display: flex;
  justify-content: center;
  border-bottom-style: none;
  font-weight: 600;
  align-items: center;
}

.card-header {
  margin-top: 5px;
  background-color: transparent;
  padding: 2px !important;
  border-radius: 10px 10px 0px 0px;
  width: 200px;
  display: flex;
  justify-content: center;
  font-weight: normal;
  align-items: center;
}

.card-pdf {
  border-radius: 10px;
  border: 1px solid #e9eaec;
  background-color: #e9eaec61;
}

/* สไตล์เพื่อให้ PDF ดูเหมือนวางบนโต๊ะ */
.pdf-viewer-wrapper {
  background-color: white;
  width: 100%;
  max-width: 900px; /* จำกัดความกว้างเพื่อความสวยงามบนจอใหญ่ */
  transition: all 0.3s ease;
}

/* ปรับแต่ง Scrollbar ให้ดูสะอาดตา */
.scroll::-webkit-scrollbar {
  width: 8px;
}
.scroll::-webkit-scrollbar-thumb {
  background: #bdbdbd;
  border-radius: 4px;
}
.scroll::-webkit-scrollbar-thumb:hover {
  background: #9e9e9e;
}

:deep(.q-btn-dropdown__arrow) {
  display: none !important;
}
</style>
