<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 { checkPermission } from "@/utils/permissions";
import http from "@/plugins/http";
import config from "@/app.config";
import genReportXLSX from "@/plugins/genreportxlsx";

import type { DataStructureTree } from "@/interface/main";
import type {
  DataOption,
  DataDateWeeklyObject,
  DataDateMonthObject,
} from "@/modules/09_leave/interface/index/Main";

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

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

const { fetchStructureTree } = useStructureTree();
const splitterModel = ref<number>(14);

/** filter*/
const typeReport = ref<string>("");
const optionReport = ref<DataOption[]>([
  { id: "1", name: "รายงานการเข้างาน" },
  { id: "2", name: "รายงานการเข้างานสาย" },
]);
const filterType = ref<string>("DAY");
const filterTypeMain = ref<DataOption[]>([
  { id: "DAY", name: "รายวัน" },
  { id: "WEEKLY", name: "รายสัปดาห์" },
  { id: "MONTH", name: "รายเดือน" },
]);
const filterTypeOption = ref<DataOption[]>(filterTypeMain.value);
const date = ref<Date>(new Date());
const dateWeek = ref<Date[]>(getCurrentWeek());
const dateMonth = ref<DataDateMonthObject>({
  month: new Date().getMonth(),
  year: new Date().getFullYear(),
});
const isLoadPDF = ref<boolean>(false);

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

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

const detailReport = ref<any>();
const isReport = ref<boolean>(false);

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

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

async function fetchDataTree() {
  node.value = await fetchStructureTree(route.meta.Key as string, true);
}

function onSelectedNode(id: string, level: number) {
  nodeId.value = id;
  nodeLevel.value = level;
}

/** function อัปเดทรายงานสถิติการลา*/
async function updateFilterType(type: string) {
  let body = {};
  isReport.value = false;
  isLoadPDF.value = true;
  pdfSrc.value = undefined;
  switch (type) {
    case "DAY":
      body = {
        startDate: dateToISO(date.value),
        endDate: dateToISO(date.value),
        type: filterType.value,
      };
      break;

    case "WEEKLY":
      const startOfWeek = new Date(dateWeek.value[0]); // ใช้ค่า index 0 เป็นวันเริ่มต้น
      const endOfWeek = new Date(dateWeek.value[1]);

      body = {
        startDate: dateToISO(startOfWeek),
        endDate: dateToISO(endOfWeek),
        type: filterType.value,
      };
      break;

    case "MONTH":
      const mount = dateMonth.value.month + 1;
      //  วันเริ่มต้นของเดือน
      const firstDay = new Date(dateMonth.value.year, mount - 1, 1);
      // วันสิ้นสุดของเดือนถัดไป
      const lastDay = new Date(dateMonth.value.year, mount, 0);
      body = {
        startDate: dateToISO(firstDay),
        endDate: dateToISO(lastDay),
        type: filterType.value,
      };
      break;
    default:
      break;
  }

  typeReport.value === "1"
    ? fetchReportTimeRecords(body)
    : fetchReportTimeLate(body);
}

/**
 * function เรียกข้อมูลรายงานการเข้างาน
 * @param body วันเรื่มต้นและสิ้นสุด
 */
async function fetchReportTimeRecords(body: any) {
  await http
    .post(config.API.leaveReportTimeRecords(), body)
    .then(async (res) => {
      const data = res.data.result;
      detailReport.value = data;
      isReport.value = data ? true : false;
      await fetchDocumentTemplate(data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoadPDF.value = false;
    });
}

/**
 * function เรียกข้อมูลรายงานการเข้างานสาย
 * @param body วันเรื่มต้นและสิ้นสุด
 */
async function fetchReportTimeLate(body: any) {
  await http
    .post(config.API.leaveReportTimeRecords(), body)
    .then(async (res) => {
      const data = res.data.result;
      detailReport.value = data;
      isReport.value = data ? true : false;
      await fetchDocumentTemplate(data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoadPDF.value = false;
    });
}

/**
 * function เรียกไฟล์ XLSX
 * @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 = await usePDF(`${objectUrl}`);

      // แสดง PDF หลังจากโหลดเสร็จ
      setTimeout(async () => {
        pdfSrc.value = pdfData.pdf.value;
        numOfPages.value = pdfData.pages.value;
      }, 1500);
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    });
}

/**
 *  function filterOption
 * @param val  คำค้นหา
 * @param update functoin
 */
function filterFnOptions(val: string, update: Function) {
  update(() => {
    filterTypeOption.value = filterTypeMain.value.filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

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

function formatWeekDisplay(week: any) {
  if (week) {
    if (!week[0] || !week[1]) return "";
    return `${date2Thai(week[0])} - ${date2Thai(week[1])}`;
  }
}

/** ฟังก์ชันคำนวณวันเริ่มต้นและวันสิ้นสุดของสัปดาห์นี้ */
function getCurrentWeek() {
  const today = new Date();
  const firstDayOfWeek = new Date(today);
  firstDayOfWeek.setDate(today.getDate() - today.getDay() + 1); // วันจันทร์
  const lastDayOfWeek = new Date(today);
  lastDayOfWeek.setDate(today.getDate() - today.getDay() + 7); // วันอาทิตย์
  return [firstDayOfWeek, lastDayOfWeek];
}

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

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายงานสถิติการลงเวลา
  </div>

  <div class="q-pa-sm">
    <q-card flat bordered class="col-12">
      <div class="row q-col-gutter-sm q-pa-md">
        <div class="row col-12">
          <div class="col-2">
            <q-select
              hide-bottom-space
              outlined
              dense
              lazy-rules
              borderless
              v-model="typeReport"
              :label="`${'รายงาน'}`"
              emit-value
              map-options
              :options="optionReport"
              option-value="id"
              option-label="name"
              @update:model-value="updateFilterType(filterType)"
            />
          </div>

          <q-space />

          <q-btn
            v-if="checkPermission($route)?.attrIsGet"
            flat
            :disable="!isReport || !nodeId"
            round
            color="primary"
            icon="download"
            @click.stop.pervent="
              genReportXLSX(
                detailReport,
                `${
                  typeReport === '1'
                    ? 'รายงานการเข้างาน'
                    : 'รายงานการเข้างานสาย'
                }`
              )
            "
          >
          </q-btn>
        </div>

        <div class="col-12 row">
          <q-card bordered class="col-12 filter-card q-pa-sm">
            <div class="row col-12 q-col-gutter-sm">
              <div class="q-pr-xs col-2">
                <q-select
                  class="bg-white"
                  outlined
                  dense
                  v-model="filterType"
                  :options="filterTypeOption"
                  emit-value
                  map-options
                  option-label="name"
                  option-value="id"
                  @update:model-value="updateFilterType"
                  @filter="(inputValue: string,
          doneFn: Function) => filterFnOptions(inputValue, doneFn,)"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        ไม่มีข้อมูล
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </div>

              <div class="q-pr-xs col-3" v-if="filterType === 'DAY'">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="date"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  week-start="0"
                  @update:model-value="updateFilterType('DAY')"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      class="bg-white"
                      outlined
                      dense
                      borderless
                      :model-value="date ? date2Thai(date) : null"
                      :label="`${'วันที่'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="q-pr-xs col-3" v-if="filterType === 'WEEKLY'">
                <datepicker
                  v-model="dateWeek"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  @update:model-value="updateFilterType('WEEKLY')"
                  week-picker
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      class="bg-white"
                      outlined
                      dense
                      borderless
                      :label="`${'รายสัปดาห์'}`"
                      :model-value="formatWeekDisplay(dateWeek)"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        ></q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="q-pr-xs col-3" v-if="filterType === 'MONTH'">
                <datepicker
                  v-model="dateMonth"
                  :locale="'th'"
                  autoApply
                  month-picker
                  :enableTimePicker="false"
                  @update:model-value="updateFilterType('MONTH')"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      class="bg-white"
                      outlined
                      dense
                      borderless
                      :label="`${'เดือน'}`"
                      :model-value="monthYearThai(dateMonth)"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        ></q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
            </div>
          </q-card>
        </div>
      </div>
    </q-card>

    <q-card class="q-mt-sm">
      <div class="col-12">
        <q-card-section :horizontal="$q.screen.gt.sm">
          <q-card-section class="col-lg-3 col-md-4 col-xs-12 q-gutter-sm">
            <div class="col">
              <q-input dense outlined v-model="filterTree" label="ค้นหา">
                <template v-slot:append>
                  <q-icon name="search" />
                </template>
              </q-input>
            </div>

            <div class="bg-white tree-container q-pa-xs">
              <q-tree
                dense
                :nodes="node"
                node-key="orgTreeId"
                label-key="labelName"
                v-model:expanded="expanded"
                :filter="filterTree.trim()"
                no-results-label="ไม่พบข้อมูลที่ค้นหา"
                no-nodes-label="ไม่มีข้อมูล"
              >
                <template v-slot:default-header="prop">
                  <q-item
                    @click.stop="
                      onSelectedNode(prop.node.orgTreeId, prop.node.nodeLevel)
                    "
                    :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>
            </div>
          </q-card-section>
          <q-separator :vertical="$q.screen.gt.xs" />

          <q-card-section class="col-lg-9 col-md-8 col-xs-12 scroll">
            <q-splitter
              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-section>
        </q-card-section>
      </div>
    </q-card>
  </div>
</template>

<style 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);
}
</style>
