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

import type { OptionData } from "@/modules/07_insignia/interface/index/Main";
import type { ResponsePeriod } from "@/modules/07_insignia/interface/response/Main";

import { useInsigniaDataStore } from "@/modules/07_insignia/store";

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

import type { QForm } from "quasar";

const route = useRoute();
const typeReport = route.params.type.toString();
const store = useInsigniaDataStore();
const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader } = mixin;
const { optionReport } = store;
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);
const titleReport = ref<string>("");
interface OptionReport {
  id: string;
  title: string;
}

const splitterModel = ref(14);
const selectList = ref<any>();
const optionsList = ref<OptionData[]>([{ id: 0, name: "เลือกกรอบการยื่นขอ" }]);
const filterOtion = ref<OptionData[]>([]);

/**
 * ฟังก์ชันไปหน้าถัดไป
 */
function nextPage() {
  if (page.value < numOfPages.value) {
    page.value++;
  }
}

/**
 * ฟังก์ชันย้อนกลับ
 */
function backPage() {
  if (page.value !== 1) {
    page.value--;
  }
}

/**
 * ฟังก์ชัน Redirect ไปหน้า รายงานเครื่องราชอิสริยาภรณ์
 */
function backHistory() {
  window.history.back();
}

/**
 * ฟังก์ชันคึงข้อมูลรอบการเสนอขอ
 */
async function fecthlistRound() {
  showLoader();
  await http
    .get(config.API.listRoundInsignia(), { params: { path: "REPORT" } })
    .then((res: any) => {
      optionsList.value = res.data.result.map((e: ResponsePeriod) => ({
        id: e.period_id,
        year: e.period_year,
        name: e.period_name,
      }));
      filterOtion.value = optionsList.value;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันเลือกรอบการเสนอขอ
 */
function updateSelect() {
  conditionDocument("show");
}

/**
 * ฟังก์ชันโหลไฟล์รายงาน
 * @param type นามสกุลไฟล์ที่ต้องการ
 */
function conditionDocument(type: string) {
  myForm.value?.validate().then(async (success: boolean) => {
    if (success) {
      if (type == "show") {
        await downloadReport("pdf", false);
      } else {
        await downloadReport(type, true);
      }
    }
  });
}

/**
 * ฟังก์แสดงรายงาน
 * @param url
 */
function showDocument(url: any) {
  const pdfData = usePDF(url);
  setTimeout(() => {
    pdfSrc.value = pdfData.pdf.value;
    numOfPages.value = pdfData.pages.value;
  }, 1000);
}

/**
 * ฟังก์ชันโหลดไฟล์
 * @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);
}

/**
 * ฟังก์ชันโหลดไฟล์
 * @param type  ประเภทไฟล์
 * @param download
 */
async function downloadReport(type: string = "pdf", download: boolean = true) {
  showLoader();
  await http
    .get(config.API.reportInsignia(typeReport, type, selectList.value.id), {
      responseType: "blob",
    })
    .then(async (res) => {
      if (download) {
        downloadFile(
          res,
          `${titleReport.value} ${selectList.value.name}.${type}`
        );
      } else {
        const url = URL.createObjectURL(new Blob([res.data]));
        showDocument(url);
      }
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 * @param name ชื่อ Selec
 */
function filterSelector(val: string, update: Function, name: string) {
  update(() => {
    const needle = val.toLowerCase();
    if (name === "selectList") {
      filterOtion.value = optionsList.value.filter(
        (v: OptionData) => v.name.toLowerCase().indexOf(needle) > -1
      );
    }
  });
}

onMounted(async () => {
  await fecthlistRound();
  let report = optionReport.find((e: OptionReport) => e.id == typeReport);
  report && (titleReport.value = report.title);
});
</script>

<template>
  <div class="toptitle">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="backHistory"
    />
    {{ titleReport }}
  </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
              style="width: 400px"
              class="q-pa-none"
              use-input
              fill-input
              hide-selected
              dense
              lazy-rules
              clearable
              outlined
              v-model="selectList"
              :options="filterOtion"
              label="เลือกรอบ"
              option-value="id"
              option-label="name"
              :rules="[(val:string) => !!val || 'กรุณาเลือกรอบ']"
              @update:model-value="updateSelect"
              @filter="(inputValue:string,doneFn:Function) => 
                filterSelector(inputValue, doneFn,'selectList') "
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </q-form>
          <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-refresh"
              color="primary"
              @click="conditionDocument('show')"
              outline
            />
            <q-btn
              unelevated
              color="blue"
              icon="mdi-fullscreen"
              @click="dialog = true"
            />
          </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>
