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

import { useRoute } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useStructureTree } from "@/stores/structureTree";
import { calculateFiscalYear } from "@/utils/function";

import genReportXLSX from "@/plugins/genreportxlsx";
import http from "@/plugins/http";
import config from "@/app.config";
import type { DataStructureTree } from "@/interface/main";
import type {
  DataOption,
  DataOption2,
  DataDateMonthObject,
} from "@/modules/09_leave/interface/index/Main";

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

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

const isLoadStructureTree = ref<boolean>(true);

/** use*/
const $q = useQuasar();
const route = useRoute();

const { fetchStructureTree } = useStructureTree();
const {
  date2Thai,
  dateToISO,
  messageError,
  monthYear2Thai,
  showLoader,
  hideLoader,
} = useCounterMixin();

const year = ref<number>(calculateFiscalYear(new Date()));
const dateStart = ref<Date>(new Date(year.value - 1, 9, 1));
const dateEnd = ref<Date>(new Date(year.value + 1, 8, 30));

const dateMonth = ref<DataDateMonthObject>({
  month: new Date().getMonth(),
  year: new Date().getFullYear(),
});

const pageName = ref<string>(route.name as string);

const dateWeek = ref<Date[]>(getCurrentWeek());
const date = ref<Date>(new Date());

const typeReport = ref<number | null>(null);
const optionReport = ref<DataOption2[]>([
  {
    id: 3,
    name: "รายงานการเข้างาน",
  },
  {
    id: 4,
    name: "รายงานการเข้างานสาย",
  },
  { id: 1, name: "รายงานการลางานตามประเภทการลา" },
  {
    id: 2,
    name: "รายงานการลางาน จำแนกตามเพศ ประเภทการลา หน่วยงาน/ส่วนราชการ",
  },
]);
const optionReportMain = ref<DataOption2[]>(
  route.name?.toString() === "reportLeave"
    ? optionReport.value
    : route.name?.toString() === "leaveReport"
    ? optionReport.value.filter((item) => item.id === 1 || item.id === 2)
    : optionReport.value.filter((item) => item.id === 3 || item.id === 4)
);

const employeeClass = ref<string>("officer");
const yearType = ref<string>("FULL");
const leaveType = ref<string>("DAY");
const employeeClassMain = ref<DataOption[]>([
  { id: "officer", name: "ข้าราชการ กทม. สามัญ" },
  { id: "employee", name: "ลูกจ้างประจำ กทม." },
]);
const leaveTypeOptionMain = ref<DataOption[]>([
  { id: "DAY", name: "รายวัน" },
  { id: "WEEKLY", name: "รายสัปดาห์" },
  { id: "MONTH", name: "รายเดือน" },
]);
const yearTypeOptionMain = ref<DataOption[]>([
  { id: "FULL", name: "รายปี" },
  { id: "MONTH", name: "รายเดือน" },
  { id: "FIRSTHAFT", name: "ครึ่งปีแรก" },
  { id: "SECONDHAFT", name: "ครึ่งปีหลัง" },
]);
const employeeClassOption = ref<DataOption[]>(employeeClassMain.value);
const yearTypeOptionOption = ref<DataOption[]>(yearTypeOptionMain.value);
const leaveTypeOptionOption = ref<DataOption[]>(leaveTypeOptionMain.value);

const detailReport = ref<any>();
const isReport = ref<boolean>(false);
const isLoadPDF = ref<boolean>(false);
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[]>([]);
const orgTreeDnaId = 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;
  }
}

/**
 * ฟังก์ชันเลือกหน่วยงานที่ต้องการดูข้อมูล
 * @param id id หน่วยงาน
 * @param level node ของหน่วงงานที่เลือก
 */
function onSelectedNode(data: any) {
  org.value = data.orgName;
  nodeId.value = data.orgTreeDnaId;
  nodeLevel.value = data.orgLevel;
  expandedModal.value = false;
  orgTreeDnaId.value = data.orgTreeDnaId;
  updateLeaveday();
}

/**
 * ฟังก์ชันอัปเดทบัญชีแสดงวันลา
 * และเรียกข้อมูลรายงาน
 */
async function updateLeaveday() {
  const list =
    typeReport.value == 3 || typeReport.value == 4
      ? leaveType.value
      : yearType.value;
  switch (list) {
    case "FULL":
      dateStart.value = new Date(year.value - 1, 9, 1);
      dateEnd.value = new Date(year.value, 8, 30);
      dateMonth.value = {
        month: new Date().getMonth(),
        year: new Date().getFullYear(),
      };
      break;

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

      dateStart.value = startOfWeek;
      dateEnd.value = endOfWeek;
      break;

    case "FIRSTHAFT":
      dateStart.value = new Date(year.value - 1, 9, 1);
      dateEnd.value = new Date(year.value, 2, 31);
      dateMonth.value = {
        month: new Date().getMonth(),
        year: new Date().getFullYear(),
      };
      break;

    case "DAY":
      dateStart.value = new Date(date.value);
      dateEnd.value = new Date(date.value);

      break;

    case "SECONDHAFT":
      dateStart.value = new Date(year.value, 3, 1);
      dateEnd.value = new Date(year.value, 8, 30);
      dateMonth.value = {
        month: new Date().getMonth(),
        year: new Date().getFullYear(),
      };
      break;

    default:
      break;
  }

  if (!nodeId.value || !typeReport.value) {
    return false;
  }
}

/**
 * ฟังก์ชันเรียกข้อมูลรายงาน
 * @param type สถานภาพ
 * @param year ปั
 * @param startDate วันเริ่มต้น
 * @param endDate วันสิ้นสุด
 */
async function fetchLeaveday(
  type: string,
  year: string,
  startDate: Date,
  endDate: Date
) {
  const nodeIdVal = typeReport.value === 3 ? orgTreeDnaId.value : nodeId.value;
  const body = {
    type:
      year === "FULL"
        ? "FULL"
        : year === "MONTH"
        ? "MONTH"
        : year == "HAFT"
        ? "HAFT"
        : year == "DAY"
        ? "DAY"
        : "WEEKLY",
    startDate: dateToISO(startDate),
    endDate: dateToISO(endDate),
    nodeId: nodeIdVal,
    node: nodeLevel.value,
  };

  const pathAPI =
    typeReport.value === 1
      ? config.API.leaveReportLeaveday(type)
      : typeReport.value === 2
      ? config.API.leaveReportLeave2(type)
      : typeReport.value === 3
      ? config.API.leaveReportTimeRecords(type)
      : config.API.leaveReportTimeLate(type);

  await http
    .post(pathAPI, body)
    .then(async (res) => {
      const data = res.data.result;
      data && (await fetchDocumentTemplate(data));
      isReport.value = data ? true : false;
      detailReport.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoadPDF.value = false;
    });
}

/**
 * function เรียกไฟล์ PDF
 * @param data  ข้อมูลบัญชีวันลา
 */
async function fetchDocumentTemplate(data: any) {
  if (typeReport.value === 4) return;
  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}`);

      setTimeout(() => {
        pdfSrc.value = pdfData.pdf.value;
        numOfPages.value = pdfData.pages.value;
      }, 1500);
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    })
    .finally(() => {});
}

//ตัวแปร PDF
const numOfPages = ref<number>(0);
const page = ref<number>(1);
const pdfSrc = ref<any>();

/** ไปหน้าต่อไปของรายงาน */
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);
}

/**
 * ฟังก์ชั่นค้นหาข้อมูลของ Option Filter
 * @param val คำที่ค้นหา
 * @param update Function
 * @param typeOp ประเภทของ Select
 */
function filterOption(val: string, update: any, typeOp: string) {
  update(() => {
    const needle = val.toLowerCase();
    if (typeOp == "typeReport") {
      optionReport.value = optionReportMain.value.filter(
        (v: any) => v.name.toLowerCase().indexOf(needle) > -1
      );
    }
  });
}

function clearData() {
  nodeId.value = "";
  nodeLevel.value = 0;
  orgTreeDnaId.value = "";
  org.value = "";
  typeReport.value = null;
  yearType.value = "FULL";
  leaveType.value = "DAY";
  pdfSrc.value = undefined;
  detailReport.value = undefined;

  year.value = calculateFiscalYear(new Date());
  dateMonth.value = {
    month: new Date().getMonth(),
    year: new Date().getFullYear(),
  };
}

async function onSearch() {
  isReport.value = false;
  isLoadPDF.value = true;
  pdfSrc.value = undefined;
  page.value = 1;
  updateLeaveday();
  fetchLeaveday(
    employeeClass.value,
    typeReport.value == 3 || typeReport.value == 4
      ? leaveType.value
      : yearType.value,
    dateStart.value,
    dateEnd.value
  );
}

/** ฟังก์ชันคำนวณวันเริ่มต้นและวันสิ้นสุดของสัปดาห์นี้ */
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];
}

function updateValue(val: string) {
  if (typeReport.value == 3 || typeReport.value == 4) {
    leaveType.value = val;
  } else {
    yearType.value = val;
  }
}
function formatWeekDisplay(week: Date[]) {
  if (week) {
    if (!week[0] || !week[1]) return "";
    return `${date2Thai(week[0])} - ${date2Thai(week[1])}`;
  }
}

const isLoad = ref<boolean>(false);

/**
 *
 * @param isName ชื่อไฟล์
 * @param fileType pdf/xlsx
 */
function getReport() {
  showLoader();
  const body = {
    type:
      leaveType.value === "FULL"
        ? "FULL"
        : leaveType.value === "MONTH"
        ? "MONTH"
        : leaveType.value == "HAFT"
        ? "HAFT"
        : leaveType.value == "DAY"
        ? "DAY"
        : "WEEKLY",
    startDate: dateToISO(dateStart.value),
    endDate: dateToISO(dateEnd.value),
    nodeId: orgTreeDnaId.value,
    node: nodeLevel.value,
  };
  http
    .post(config.API.leaveReportAPI(employeeClass.value), body, {
      headers: {
        accept:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "content-Type": "application/json",
      },

      responseType: "blob",
    })
    .then((res) => {
      const data = res.data;
      if (data) {
        // สร้าง Blob จาก array buffer
        const blob = new Blob([data]);

        // สร้าง URL สำหรับไฟล์ Blob
        const url = URL.createObjectURL(blob);

        // สร้างลิงก์เพื่อดาวน์โหลดไฟล์
        const link = document.createElement("a");
        link.href = url;
        link.download = `${reportName()}.xlsx`; // กำหนดชื่อไฟล์ที่จะดาวน์โหลด
        document.body.appendChild(link);
        link.click();

        // ลบ URL ที่สร้างขึ้นหลังจากใช้งาน
        URL.revokeObjectURL(url);
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

const reportName = () => {
  const employeeClassName =
    employeeClass.value === "officer"
      ? " (ข้าราชการ กทม. สามัญ)"
      : " (ลูกจ้างประจำ กทม.)";

  const reportNameVal =
    optionReportMain.value.find((item) => item.id === typeReport.value)?.name ||
    "";
  return reportNameVal + employeeClassName;
};

async function handleDownload() {
  updateLeaveday();
  await fetchLeaveday(
    employeeClass.value,
    typeReport.value == 3 || typeReport.value == 4
      ? leaveType.value
      : yearType.value,
    dateStart.value,
    dateEnd.value
  );
  await genReportXLSX(detailReport.value, `${reportName()}`);
}

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

<template>
  <div class="toptitle text-dark col-12 row items-center">
    {{
      pageName === "reportLeave"
        ? "รายงานบันทึกเวลาและการลา"
        : pageName === "leaveReport"
        ? "รายงานสถิติการลา"
        : "รายงานสถิติการลงเวลา"
    }}
  </div>

  <q-form greedy @submit.prevent @validation-success="onSearch">
    <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">
            <div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">
              <q-select
                outlined
                dense
                v-model="employeeClass"
                :options="employeeClassOption"
                label="ประเภทตำแหน่ง"
                emit-value
                map-options
                option-label="name"
                option-value="id"
                @update:model-value="updateLeaveday"
              >
              </q-select>
            </div>
            <q-space />
            <div>
              <q-btn
                :disable="!isReport || !employeeClass || !detailReport"
                :loading="isLoadPDF"
                flat
                round
                color="primary"
                icon="download"
                v-if="
                  checkPermission($route)?.attrIsGet &&
                  typeReport !== 3 &&
                  typeReport !== 4
                "
              >
                <q-menu>
                  <q-list style="min-width: 150px">
                    <q-item
                      clickable
                      v-close-popup
                      @click="
                        genReportXLSX(detailReport, `${reportName()}`, '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="genReportXLSX(detailReport, `${reportName()}`)"
                    >
                      <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
                :disable="!nodeId"
                flat
                round
                color="primary"
                icon="download"
                v-if="
                  checkPermission($route)?.attrIsGet &&
                  (typeReport == 3 || typeReport == 4)
                "
                @click="typeReport == 3 ? getReport() : handleDownload()"
              >
              </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="clearData"
                  />
                </q-card-section>
                <q-separator />
                <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="orgTreeDnaId"
                          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.orgTreeDnaId"
                              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
                      class="bg-white select_ellipsis3"
                      hide-bottom-space
                      dense
                      lazy-rules
                      borderless
                      hide-selected
                      v-model="typeReport"
                      :label="`${'รายงาน'}`"
                      emit-value
                      map-options
                      :options="optionReport"
                      option-value="id"
                      use-input
                      fill-input
                      option-label="name"
                      @update:model-value="(value:any)=>(typeReport = value,updateLeaveday())"
                      @filter="(inputValue:any, doneFn:Function) =>
                    filterOption(inputValue, doneFn,'typeReport') "
                    >
                      <template v-slot:no-option>
                        <q-item>
                          <q-item-section class="text-grey">
                            ไม่มีข้อมูล
                          </q-item-section>
                        </q-item>
                      </template></q-select
                    >
                  </div>
                  <q-separator v-if="typeReport" />
                  <div class="col-12 q-pa-sm" v-if="typeReport">
                    <div class="row q-col-gutter-y-xs">
                      <div class="text-grey-8 text-caption">เลือกช่วงเวลา</div>
                      <div class="col-12">
                        <q-select
                          class="bg-white"
                          dense
                          :model-value="
                            typeReport == 3 || typeReport == 4
                              ? leaveType
                              : yearType
                          "
                          :options="
                            typeReport == 3 || typeReport == 4
                              ? leaveTypeOptionOption
                              : yearTypeOptionOption
                          "
                          emit-value
                          map-options
                          option-label="name"
                          option-value="id"
                          @update:model-value="(value:any)=>(updateValue(value),updateLeaveday())"
                        >
                        </q-select>
                      </div>
                      <div
                        class="col-12"
                        v-if="
                          yearType !== 'MONTH' &&
                          typeReport !== 3 &&
                          typeReport !== 4
                        "
                      >
                        <datepicker
                          v-model="year"
                          :locale="'th'"
                          autoApply
                          year-picker
                          :enableTimePicker="false"
                          @update:model-value="updateLeaveday"
                        >
                          <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
                                  name="event"
                                  class="cursor-pointer"
                                  size="18px"
                                  style="color: var(--q-primary)"
                                >
                                </q-icon>
                              </template>
                            </q-input>
                          </template>
                        </datepicker>
                      </div>
                      <div
                        class="col-12"
                        v-if="
                          yearType !== 'MONTH' &&
                          typeReport !== 3 &&
                          typeReport !== 4
                        "
                      >
                        <datepicker
                          v-model="dateStart"
                          :locale="'th'"
                          autoApply
                          :enableTimePicker="false"
                          week-start="0"
                          readonly
                        >
                          <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="`${'ตั้งเเต่วันที่'}`"
                              readonly
                            >
                              <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"
                        v-if="
                          yearType !== 'MONTH' &&
                          typeReport !== 3 &&
                          typeReport !== 4
                        "
                      >
                        <datepicker
                          v-model="dateEnd"
                          :locale="'th'"
                          autoApply
                          :enableTimePicker="false"
                          week-start="0"
                          readonly
                        >
                          <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="`${'ถึงวันที่'}`"
                              readonly
                            >
                              <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"
                        v-if="yearType == 'MONTH' || leaveType == 'MONTH'"
                      >
                        <datepicker
                          v-model="dateMonth"
                          :locale="'th'"
                          autoApply
                          month-picker
                          :enableTimePicker="false"
                          @update:model-value="updateLeaveday"
                        >
                          <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 class="col-12" v-if="leaveType == 'WEEKLY'">
                        <datepicker
                          v-model="dateWeek"
                          :locale="'th'"
                          autoApply
                          :enableTimePicker="false"
                          @update:model-value="updateLeaveday"
                          week-picker
                        >
                          <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="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="col-12"
                        v-if="
                          (leaveType == 'DAY' && typeReport == 3) ||
                          (leaveType == 'DAY' && typeReport == 4)
                        "
                      >
                        <datepicker
                          v-model="date"
                          :locale="'th'"
                          autoApply
                          :enableTimePicker="false"
                          week-start="0"
                          @update:model-value="updateLeaveday"
                        >
                          <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="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>
                  </div>
                </q-card-section>
                <q-separator />
                <q-card-actions align="right">
                  <q-btn
                    v-if="typeReport !== 3 && typeReport !== 4"
                    dense
                    class="q-px-md"
                    label="ค้นหา"
                    unelevated
                    color="public"
                    type="submit"
                    :disable="!typeReport || !org"
                  />
                  <!-- :disable="
                      typeReport &&
                      (typeReport == 2 || typeReport == 3 || typeReport == 4) &&
                      org
                    " -->
                </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
                v-if="typeReport !== 3 && typeReport !== 4"
                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>

              <q-banner class="q-pa-lg text-center full-width" v-else>
                <q-icon name="info" size="lg" color="info" />
                <p class="text-grey-9 q-pt-sm">
                  รายงานการเข้างานไม่มีพรีวิวกรุณาคลิกดาวน์โหลด
                </p>
              </q-banner>
            </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>
