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

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

import { useCounterMixin } from "@/stores/mixin";
import genReportXLSX from "@/plugins/genreportxlsx";

import type { DataDocument } from "@/modules/02_organization/interface/index/Main";

/** importComponents*/
import LoadView from "@/components/LoadView.vue";

const $q = useQuasar();
const { hideLoader, messageError } = useCounterMixin();

/** View*/
const numOfPages = ref<number>(0);
const page = ref<number>(1);
const pdfSrc = ref<any>();
const splitterModel = ref(14);

/** props */
const isLoadPDF = ref<boolean>(false);
const detailReport = ref<any>();

const orgRootId = defineModel<string>("orgRootId", { required: true });

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

const baseDocument = ref<DataDocument[]>([
  {
    name: "บัญชี 2",
    val: "report2",
  },

  {
    name: "รายงานสรุปจำนวนกรอบอัตรากำลังของข้าราชการกรุงเทพมหานครสามัญ",
    val: "report4",
  },
]);

/**
 * ฟังก์ชัน DownloadReport
 * @param list รายงานที่ต้องการดาวน์โหลด
 */
async function getReport(list: string) {
  const listFind = baseDocument.value.find(
    (item: DataDocument) => item.val == list
  )?.val;
  const newReport = listFind === "report2" ? "report2-history" : listFind;
  pdfSrc.value = undefined;
  page.value = 1;
  isLoadPDF.value = true;
  if (newReport) {
    await http
      .get(config.API.orgReport(newReport) + `/${orgRootId.value}`)
      .then(async (res) => {
        const data = res.data.result;
        detailReport.value = data;
        await fetchDocumentTemplate(data);
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        isLoadPDF.value = false;
        hideLoader();
      });
  }
}

/**
 * ฟังก์ชันเรียกไฟล์ PDF
 * @param data  ข้อมูลบัญชีวันลา
 */
async function fetchDocumentTemplate(data: any) {
  await axios
    .post(`${config.API.reportTemplate}/xlsx`, 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;
      }, 1500);
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    });
}

/** ไปหน้าต่อไปของรายงาน */
function nextPage() {
  if (page.value < numOfPages.value) {
    page.value++;
  }
}

/** กลับหน้าก่อนหน้าของรายงาน */
function backPage() {
  if (page.value !== 1) {
    page.value--;
  }
}

/** ติดตามการเปลี่ยนแปลงของ orgRootId */
watch(
  () => orgRootId.value,
  async () => {
    // เมื่อ orgRootId มีค่าและ title มีค่า เราจะเรียก getReport
    if (orgRootId.value && title.value) {
      await getReport(title.value);
    }
  }
);
</script>

<template>
  <!-- TOOLBAR -->
  <div class="col-12 q-mb-sm">
    <q-toolbar style="padding: 0">
      <!-- v-if="store.typeOrganizational === 'draft'" -->
      <q-select
        outlined
        dense
        :options="baseDocument"
        option-value="val"
        option-label="name"
        style="width: 500px"
        label="รายงาน"
        v-model="title"
        @update:model-value="(val:string) => getReport(val)"
        emit-value
        map-options
      >
      </q-select>

      <q-space />
      <q-btn
        :loading="isLoadPDF"
        flat
        round
        :disable="!title"
        color="primary"
        icon="download"
      >
        <q-menu>
          <q-list style="min-width: 150px">
            <q-item
              clickable
              v-close-popup
              @click.stop.prevent="
                genReportXLSX(
                  detailReport,
                  `${baseDocument.find((e) => e.val === title)?.name}`,
                  '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.stop.prevent="
                genReportXLSX(
                  detailReport,
                  `${baseDocument.find((e) => e.val === title)?.name}`
                )
              "
            >
              <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-toolbar>
  </div>

  <!-- TABLE -->
  <div class="col-12">
    <q-card>
      <q-splitter
        disable
        v-model="splitterModel"
        horizontal
        style="
          height: 65vh;
          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">
            <LoadView v-if="isLoadPDF" />
            <VuePDF
              v-else
              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>
    </q-card>
  </div>
</template>

<style lang="scss" scoped>
.custom-header-table-expand {
  height: auto;
  .q-table tr:nth-child(odd) td {
    background: white;
  }
  .q-table tr:nth-child(even) td {
    background: white;
  }

  .q-table thead tr {
    background: white;
  }

  .q-table thead tr th {
    position: sticky;
    z-index: 1;
  }
  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }
  .q-table thead tr:first-child th {
    top: 0;
    padding: 0px;
  }
}
</style>
