<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import { VuePDF, usePDF } from "@tato30/vue-pdf";
import config from "@/app.config";
import http from "@/plugins/http";
import axios from "axios";

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

import type { DataOption } from "@/modules/14_KPI/interface/index/Main";
const $q = useQuasar();

const { showLoader, hideLoader, messageError, date2Thai, dialogConfirm } =
  useCounterMixin();

const year = ref<number | null>(new Date().getFullYear());
const round = ref<string>("");
const organization = ref<string>("");
const roundOp = ref<DataOption[]>([]);
const organizationOpsMain = ref<DataOption[]>([]);
const organizationOps = ref<DataOption[]>([]);

function fetchRoundOption() {
  http
    .get(
      config.API.kpiPeriod +
        `?page=${1}&pageSize=${10}&keyword=${""}&year=${year.value}`
    )
    .then(async (res) => {
      const data = await res.data.result.data;
      if (res.data.result.data.length > 0) {
        const list = await data.map((e: any) => ({
          id: e.id,
          name:
            e.durationKPI === "OCT"
              ? "รอบตุลาคม"
              : e.durationKPI === "APR"
              ? "รอบเมษายน"
              : "",
        }));
        roundOp.value = list;
      } else {
        roundOp.value = [];
        round.value = "";
        organization.value = "";
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}

function fetchActiveId() {
  showLoader();
  http
    .get(config.API.activeOrganization)
    .then((res) => {
      const data = res.data.result;
      fetchListOrg(data.activeId);
    })
    .catch((err) => {
      messageError($q, err);
      hideLoader();
    });
}

function fetchListOrg(id: string) {
  showLoader();
  http
    .get(config.API.orgByid(id))
    .then(async (res) => {
      const data = await res.data.result.map((item: any) => ({
        id: item.orgTreeId,
        name: item.orgName,
      }));
      organizationOpsMain.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function fetchReport() {
  if (round.value !== "" && organization.value !== "") {
    showLoader();
    const body = {
      periodId: round.value,
      root: organization.value,
    };
    http
      .post(config.API.kpiReport(), body)
      .then((res) => {})
      .catch((err) => {})
      .finally(() => {
        hideLoader();
      });
  }
}

function changOption() {
  fetchReport();
}

function filterSelector(val: string, update: Function) {
  update(() => {
    organizationOps.value = organizationOpsMain.value.filter(
      (v: DataOption) => v.name.toLowerCase().indexOf(val) > -1
    );
  });
}

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

async function downloadReport(data: any, type: string) {
  const link = document.createElement("a");
  var fileName = "ประกาศผู้มีผลการปฏิบัติราชการระดับดีเด่นและดีมาก";
  link.href = window.URL.createObjectURL(new Blob([data]));
  link.setAttribute("download", `${fileName}.${type}`);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

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

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

onMounted(() => {
  fetchRoundOption();
  fetchActiveId();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    จัดทำประกาศผู้มีผลการปฏิบัติราชการระดับดีเด่นและดีมาก
  </div>
  <q-card flat bordered>
    <q-card-section>
      <q-toolbar style="padding: 0">
        <div class="row q-gutter-sm">
          <datepicker
            menu-class-name="modalfix"
            v-model="year"
            style="width: 150px"
            :locale="'th'"
            autoApply
            year-picker
            :enableTimePicker="false"
            @update:model-value="fetchRoundOption()"
          >
            <template #year="{ year }">{{ year + 543 }}</template>
            <template #year-overlay-value="{ value }">{{
              parseInt(value + 543)
            }}</template>
            <template #trigger>
              <q-input
                dense
                outlined
                hide-bottom-space
                :model-value="!!year ? year + 543 : null"
                :label="`${'ปีงบประมาณ'}`"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="event"
                    class="cursor-pointer"
                    style="color: var(--q-primary)"
                  >
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>
          <q-select
            v-model="round"
            outlined
            label="รอบการประเมิน"
            dense
            option-label="name"
            option-value="id"
            :options="roundOp"
            style="min-width: 150px"
            emit-value
            map-options
            :disable="roundOp.length === 0"
            @update:model-value="changOption"
          />
          <q-select
            :disable="roundOp.length === 0"
            style="min-width: 100px"
            dense
            hide-bottom-space
            outlined
            option-label="name"
            option-value="id"
            emit-value
            map-options
            v-model="organization"
            :options="organizationOps"
            label="หน่วยงาน"
            use-input
            @update:model-value="changOption"
            @filter="(inputValue: string,
            
            doneFn: Function) => filterSelector(inputValue, doneFn )"
          />
        </div>

        <q-space />

        <q-btn flat round color="primary" icon="download">
          <q-menu>
            <q-list style="min-width: 150px">
              <q-item
                clickable
                v-close-popup
                @click="downloadReport(fileBlob, '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="downloadReport(fileBlob, '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-list>
          </q-menu>
        </q-btn>
      </q-toolbar>

      <q-splitter
        v-model="splitterModel"
        horizontal
        style="
          height: 75vh;
          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>
    </q-card-section>
  </q-card>
</template>

<style scoped></style>
