<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 { useRoute } from "vue-router";
import { useStructureTree } from "@/stores/structureTree";
import { useCounterMixin } from "@/stores/mixin";
import { calculateFiscalYear } from "@/utils/function";
import http from "@/plugins/http";
import config from "@/app.config";
import genReportXLSX from "@/plugins/genreportxlsx";

import type { DataStructureTree } from "@/interface/main";
import type {
  DataOption,
  DataDateMonthObject,
} from "@/modules/06_retirement/interface/index/Main";

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

const $q = useQuasar();
const route = useRoute();
const { fetchStructureTree } = useStructureTree();
const { date2Thai, dateToISO, messageError, monthYear2Thai } =
  useCounterMixin();

/** Filter*/
const reportType = ref<string>("");
const optionReport = ref<DataOption[]>([
  {
    id: "1",
    name: "จำนวนข้าราชการ กทม. สามัญ ที่พ้นจากราชการ",
  },
  {
    id: "2",
    name: "จำนวนลูกจ้างประจำ กทม. ที่พ้นจากราชการ",
  },
]);

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

const isLoadStructureTree = ref<boolean>(true);

const filterType = ref<string>("MONTH");
const filterTypeOption = ref<DataOption[]>([
  { id: "MONTH", name: "รายเดือน" },
  { id: "YEAR", name: "รายปี" },
]);
const year = ref<number>(calculateFiscalYear(new Date()));
const dateMonth = ref<DataDateMonthObject>({
  month: new Date().getMonth(),
  year: new Date().getFullYear(),
});

const dateStart = ref<Date>(
  new Date(dateMonth.value.year, dateMonth.value.month + 1 - 1, 1)
);
const dateEnd = ref<Date>(
  new Date(dateMonth.value.year, dateMonth.value.month + 1, 0)
);

const detailReport = ref<any>();

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

/** tree*/
const filterTree = ref<string>("");
const nodeId = ref<string>("");
const nodeLevel = ref<number>(0);
const node = ref<DataStructureTree[]>([]);
const expanded = ref<string[]>([]);

/** ฟังก์ชันเรียกข้อมูลโครงสร้างหน่วยงาน*/
async function fetchDataTree() {
  try {
    isLoadStructureTree.value = true;
    node.value = await fetchStructureTree(route.meta.Key as string, true);
  } catch (err) {
    messageError($q, err);
  } finally {
    isLoadStructureTree.value = false;
  }
}

function onUpdateFilter() {
  switch (filterType.value) {
    case "MONTH":
      const mount = dateMonth.value.month + 1;
      //  วันเริ่มต้นของเดือน
      dateStart.value = new Date(dateMonth.value.year, mount - 1, 1);
      // วันสิ้นสุดของเดือนถัดไป
      dateEnd.value = new Date(dateMonth.value.year, mount, 0);
      break;

    case "YEAR":
      dateStart.value = new Date(year.value - 1, 9, 1);
      dateEnd.value = new Date(year.value, 8, 30);
      break;
    default:
      break;
  }
}

function onSelectedNode(data: any) {
  nodeId.value = data.orgTreeId;
  nodeLevel.value = data.orgLevel;
  org.value = data.orgName;
  expandedModal.value = false;
}

function fetchDataReport() {
  if (!reportType.value || !nodeId.value) {
    return false;
  }

  isLoadPDF.value = true;
  const queryParams = {
    nodeId: nodeId.value,
    node: nodeLevel.value,
    startDate: dateToISO(dateStart.value),
    endDate: dateToISO(dateEnd.value),
  };

  http
    .get(config.API.retirementReport + `${reportType.value}`, {
      params: queryParams,
    })
    .then(async (res) => {
      const data = await res.data.result;
      detailReport.value = data;
      await fetchDocumentTemplate(data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoadPDF.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 nextPage() {
  if (page.value < numOfPages.value) {
    page.value++;
  }
}

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

function monthYearThai(val: DataDateMonthObject) {
  if (val == null) return "";
  else return monthYear2Thai(val.month, val.year);
}

function clearFilter() {
  nodeId.value = "";
  nodeLevel.value = 0;
  org.value = "";
  detailReport.value = undefined;
  pdfSrc.value = undefined;
  reportType.value = "";

  filterType.value = "MONTH";
  year.value = calculateFiscalYear(new Date());
  dateMonth.value = {
    month: new Date().getMonth(),
    year: new Date().getFullYear(),
  };
  dateStart.value = new Date(
    dateMonth.value.year,
    dateMonth.value.month + 1 - 1,
    1
  );
  dateEnd.value = new Date(dateMonth.value.year, dateMonth.value.month + 1, 0);
}

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

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายงานการพ้นจากราชการ
  </div>

  <q-form greedy @submit.prevent @validation-success="fetchDataReport">
    <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="isLoadPDF"
                flat
                round
                :disable="!reportType || !nodeId || !detailReport"
                color="primary"
                icon="download"
              >
                <q-menu>
                  <q-list style="min-width: 150px">
                    <q-item
                      clickable
                      v-close-popup
                      @click.stop.prevent="
                        genReportXLSX(
                          detailReport,
                          `${
                            optionReport.find((e) => e.id === reportType)?.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,
                          `${
                            optionReport.find((e) => e.id === reportType)?.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>
            </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.prevent="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="isLoadStructureTree">
                        <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="expanded"
                          :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">
                    <q-select
                      dense
                      v-model="reportType"
                      :options="optionReport"
                      label="รายงาน"
                      map-options
                      borderless
                      emit-value
                      option-label="name"
                      option-value="id"
                    >
                    </q-select>
                  </div>
                  <q-separator />
                  <div class="col-12 q-px-sm">
                    <q-select
                      class="bg-white"
                      dense
                      v-model="filterType"
                      :options="filterTypeOption"
                      emit-value
                      map-options
                      option-label="name"
                      option-value="id"
                      use-input
                      borderless
                      @update:model-value="onUpdateFilter"
                    >
                    </q-select>
                  </div>
                  <q-separator />
                  <div class="col-12 q-pa-sm">
                    <div class="row q-col-gutter-y-xs">
                      <div class="text-grey-8 text-caption">เลือกช่วงเวลา</div>
                      <div class="col-12">
                        <div v-if="filterType === 'YEAR'">
                          <datepicker
                            v-model="year"
                            :locale="'th'"
                            autoApply
                            year-picker
                            :enableTimePicker="false"
                            @update:model-value="onUpdateFilter"
                          >
                            <template #year="{ year }">{{
                              year + 543
                            }}</template>
                            <template #year-overlay-value="{ value }">{{
                              parseInt(value + 543)
                            }}</template>
                            <template #trigger>
                              <q-input
                                class="bg-white"
                                dense
                                :model-value="Number(year) + 543"
                                :label="`${'ปีงบประมาณ'}`"
                              >
                                <template v-slot:prepend>
                                  <q-icon
                                    size="18px"
                                    name="event"
                                    class="cursor-pointer"
                                    style="color: var(--q-primary)"
                                  >
                                  </q-icon>
                                </template>
                              </q-input>
                            </template>
                          </datepicker>
                        </div>

                        <div v-if="filterType === 'MONTH'">
                          <datepicker
                            v-model="dateMonth"
                            :locale="'th'"
                            autoApply
                            month-picker
                            :enableTimePicker="false"
                            @update:model-value="onUpdateFilter"
                          >
                            <template #year="{ year }">{{
                              year + 543
                            }}</template>
                            <template #year-overlay-value="{ value }">{{
                              parseInt(value + 543)
                            }}</template>
                            <template #trigger>
                              <q-input
                                class="bg-white"
                                dense
                                :label="`${'เดือน'}`"
                                :model-value="monthYearThai(dateMonth)"
                              >
                                <template v-slot:prepend>
                                  <q-icon
                                    size="18px"
                                    name="event"
                                    class="cursor-pointer"
                                    color="primary"
                                  ></q-icon>
                                </template>
                              </q-input>
                            </template>
                          </datepicker>
                        </div>
                      </div>
                      <div class="col-12">
                        <datepicker
                          v-model="dateStart"
                          :locale="'th'"
                          autoApply
                          :enableTimePicker="false"
                          week-start="0"
                          :max-date="dateEnd"
                        >
                          <template #year="{ year }">{{ year + 543 }}</template>
                          <template #year-overlay-value="{ value }">{{
                            parseInt(value + 543)
                          }}</template>
                          <template #trigger>
                            <q-input
                              class="bg-white"
                              dense
                              :model-value="
                                dateStart ? date2Thai(dateStart) : null
                              "
                              :label="`${'ตั้งเเต่วันที่'}`"
                            >
                              <template v-slot:prepend>
                                <q-icon
                                  size="18px"
                                  name="event"
                                  class="cursor-pointer"
                                  color="primary"
                                >
                                </q-icon>
                              </template>
                            </q-input>
                          </template>
                        </datepicker>
                      </div>
                      <div class="col-12">
                        <datepicker
                          v-model="dateEnd"
                          :locale="'th'"
                          autoApply
                          :enableTimePicker="false"
                          week-start="0"
                          :min-date="dateStart"
                        >
                          <template #year="{ year }">{{ year + 543 }}</template>
                          <template #year-overlay-value="{ value }">{{
                            parseInt(value + 543)
                          }}</template>
                          <template #trigger>
                            <q-input
                              class="bg-white"
                              dense
                              :model-value="dateEnd ? date2Thai(dateEnd) : null"
                              :label="`${'ถึงวันที่'}`"
                            >
                              <template v-slot:prepend>
                                <q-icon
                                  size="18px"
                                  name="event"
                                  class="cursor-pointer"
                                  color="primary"
                                >
                                </q-icon>
                              </template>
                            </q-input>
                          </template>
                        </datepicker>
                      </div>
                    </div>
                  </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 == '' || reportType == ''"
                  />
                </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
                disable
                v-model="splitterModel"
                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="isLoadPDF" />
                    <VuePDF
                      v-else-if="!isLoadPDF && 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>
.tree-container {
  overflow: auto;
  height: 60vh;
  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(.expansion-item .q-item__section) {
  padding-right: 3px;
}

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