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

import http from "@/plugins/http";
import config from "@/app.config";
import genReportXLSX from "@/plugins/genreportxlsx";
import { useStructureTree } from "@/stores/structureTree";
import { checkPermission } from "@/utils/permissions";

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

import type { DataStructureTree } from "@/interface/main";

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

const $q = useQuasar();
const { fetchStructureTree } = useStructureTree();
const { messageError } = useCounterMixin();

const loadingBtn = ref<boolean>(false);
const isReport = ref<boolean>(false);
const isLoadPDF = ref<boolean>(false);
const expandedModal = ref<boolean>(false);
const org = ref<string>("");

const isLoadStructureTree = ref<boolean>(true);
const filterTree = ref<string>("");
const nodeId = ref<string>("");
const nodeName = ref<string>("");
const node = ref<DataStructureTree[]>([]);

const year = ref<number>(new Date().getFullYear());

const detailReport = ref<any>();

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

/** ฟังก์ชันเรียกข้อมูลโครงสร้างหน่วยงาน*/
async function fetchDataTree() {
  try {
    isLoadStructureTree.value = true;
    const dataTree = await fetchStructureTree("SYS_EVA_REQ", true);
    if (dataTree) {
      const data = dataTree.map((item: DataStructureTree) => ({
        ...item,
        children: null,
      }));
      node.value = data;
    }
  } catch (err) {
    messageError($q, err);
  } finally {
    isLoadStructureTree.value = false;
  }
}

async function fetchReport() {
  loadingBtn.value = true;
  await http
    .get(
      config.API.evaluationReport + `?year=${year.value}&rootId=${nodeId.value}`
    )
    .then(async (res) => {
      const data = await res.data.result;
      await fetchDocumentTemplate(data);
      detailReport.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      loadingBtn.value = false;
    });
}

/**
 * function เรียกไฟล์ PDF
 * @param data  ข้อมูลบัญชีวันลา
 */
async function fetchDocumentTemplate(data: any) {
  pdfSrc.value = undefined;
  page.value = 1;
  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 onDownloadFile(type: string) {
  genReportXLSX(
    detailReport.value,
    `รายงานสรุปจำนวนผลงานการประเมิน_${nodeName.value}`,
    type
  );
}

/**
 * function เลือกหน่วยงาน
 * @param id id หน่วยงาน
 * @param level ระดับหน่วยงาน
 */
function onSelectedNode(data: any) {
  if (data.orgTreeId !== nodeId.value) {
    nodeId.value = data.orgTreeDnaId;
    nodeName.value = data.orgTreeName;
    org.value = data.orgName;
    expandedModal.value = false;
  }
}

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

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

function clearFilter() {
  pdfSrc.value = undefined;
  detailReport.value = undefined;
  year.value = new Date().getFullYear();
  org.value = "";
  nodeId.value = "";
  nodeName.value = "";
}

onMounted(() => {
  fetchDataTree();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายงานระบบประเมินบุคคล
  </div>
  <q-form greedy @submit.prevent @validation-success="fetchReport">
    <div class="row q-col-gutter-sm">
      <div class="col-12">
        <q-card class="q-pa-sm">
          <div class="row q-col-gutter-sm no-wrap">
            <q-space />
            <div>
              <q-btn
                :loading="loadingBtn"
                :disable="!detailReport"
                flat
                round
                color="primary"
                icon="download"
                v-if="checkPermission($route)?.attrIsGet"
              >
                <q-menu>
                  <q-list style="min-width: 150px">
                    <q-item
                      clickable
                      v-close-popup
                      @click.stop.pervent="onDownloadFile('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.pervent="onDownloadFile('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>
            </div>
          </div>
        </q-card>
      </div>
      <div class="col-12">
        <q-card class="q-pa-sm">
          <div class="row q-col-gutter-sm">
            <div class="col">
              <q-card flat bordered>
                <q-card-section
                  bordered
                  class="bg-primary text-subtitle2 text-white q-pa-sm row items-center"
                >
                  <q-icon name="mdi-filter" class="q-mr-xs" />
                  ตัวกรอง
                  <q-space />
                  <q-btn
                    dense
                    size="12px"
                    class="q-px-sm"
                    rounded
                    flat
                    label="ล้างทั้งหมด"
                    @click.stop.pervent="clearFilter"
                  />
                </q-card-section>
                <q-card-section class="q-pa-none">
                  <div class="col-12">
                    <q-expansion-item
                      v-model="expandedModal"
                      dense
                      dense-toggle
                      expand-separator
                      class="expansion-item"
                    >
                      <template #header>
                        <div class="full-width flex items-stretch">
                          <q-input
                            dense
                            :model-value="org"
                            autogrow
                            borderless
                            label="สังกัด"
                            class="bg-white full-width"
                          >
                          </q-input>
                        </div>
                        <!-- @click="onOpenOrg" -->
                      </template>
                      <q-separator />

                      <q-card-section v-if="loadingBtn">
                        <LoadView />
                      </q-card-section>
                      <q-card-section v-else>
                        <q-input
                          dense
                          outlined
                          v-model="filterTree"
                          label="ค้นหา"
                        >
                          <template v-slot:append>
                            <q-icon
                              v-if="filterTree !== ''"
                              name="clear"
                              class="cursor-pointer"
                              @click="filterTree = ''"
                            />
                            <q-icon v-else name="search" color="grey-5" />
                          </template>
                        </q-input>
                        <q-tree
                          dense
                          :nodes="node"
                          node-key="orgTreeId"
                          label-key="labelName"
                          v-model:expanded="node"
                          :filter="filterTree.trim()"
                          no-results-label="ไม่พบข้อมูลที่ค้นหา"
                          no-nodes-label="ไม่มีข้อมูล"
                          class="tree-container-report q-mt-sm"
                        >
                          <template v-slot:default-header="prop">
                            <q-item
                              @click.stop="onSelectedNode(prop.node)"
                              :active="nodeId === prop.node.orgTreeId"
                              clickable
                              active-class="my-list-link text-primary text-weight-medium"
                              class="row col-12 items-center text-dark q-py-xs q-pl-sm rounded-borders my-list"
                            >
                              <div>
                                <div class="text-weight-medium">
                                  {{ prop.node.orgTreeName }}
                                </div>
                                <div class="text-weight-light text-grey-8">
                                  {{
                                    prop.node.orgCode == null
                                      ? null
                                      : prop.node.orgCode
                                  }}
                                  {{
                                    prop.node.orgTreeShortName == null
                                      ? null
                                      : prop.node.orgTreeShortName
                                  }}
                                </div>
                              </div>
                            </q-item>
                          </template>
                        </q-tree>
                      </q-card-section>
                    </q-expansion-item>
                  </div>
                  <q-separator />
                  <div class="col-12 q-px-sm">
                    <datepicker
                      v-model="year"
                      :locale="'th'"
                      autoApply
                      year-picker
                      :enableTimePicker="false"
                    >
                      <template #year="{ year }">{{ year + 543 }}</template>
                      <template #year-overlay-value="{ value }">{{
                        parseInt(value + 543)
                      }}</template>
                      <template #trigger>
                        <q-input
                          dense
                          borderless
                          :model-value="
                            year === 0 ? 'ทั้งหมด' : Number(year) + 543
                          "
                          :label="`${'ปีงบประมาณ'}`"
                          bg-color="white"
                        >
                          <template v-slot:prepend>
                            <q-icon
                              name="event"
                              class="cursor-pointer"
                              style="color: var(--q-primary)"
                            >
                            </q-icon>
                          </template>
                        </q-input>
                      </template>
                    </datepicker>
                  </div>
                </q-card-section>
                <q-separator />
                <q-card-actions align="right">
                  <q-btn
                    dense
                    class="q-px-md"
                    label="ค้นหา"
                    unelevated
                    color="public"
                    type="submit"
                    :disable="nodeId == ''"
                  />
                </q-card-actions>
              </q-card>
            </div>
            <div class="col-lg-9 col-md-9 col-sm-9 col-xs-12 col-xs-12 flex">
              <q-splitter
                horizontal
                style="
                  height: 75vh;
                  border: 1px solid rgb(210, 210, 210);
                  border-radius: 5px;
                  width: 100%;
                "
                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="loadingBtn" />
                    <VuePDF
                      v-else-if="!loadingBtn && pdfSrc"
                      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>
          </div>
        </q-card>
      </div>
    </div>
  </q-form>
</template>

<style lang="scss" scoped>
.q-item.hover-green:hover {
  background-color: #d5f1ee57;
  border-radius: 2px;
}
.q-item.hover-green {
  padding: 10px;
}

.tree-containerevaluate {
  overflow: auto;
  height: 70vh;
  border: 1px solid #e6e6e7;
  border-radius: 10px;
}
.my-list-link {
  color: rgb(118, 168, 222);
  border-radius: 5px;
  background: #a3d3fb48 !important;
  font-weight: 600;
  border: 1px solid rgba(175, 185, 196, 0.217);
}

.tree-container-report {
  overflow: auto;
  max-height: 50vh;
}

:deep(.tree-container-report div) {
  padding: 0;
}

:deep(.expansion-item .q-item__section) {
  padding-right: 3px;
}

:deep(.expansion-item .q-item) {
  min-height: 32px;
  padding: 2px 9px;
}
</style>
