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

import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useSalaryListSDataStore } from "@/modules/13_salary/store/SalaryListsStore";
import { useSalaryEmployeeListSDataStore } from "@/modules/13_salary/store/SalaryEmployeeListsStore";
import genReportXLSX from "@/plugins/genreportxlsx";
import { calculateFiscalYear } from "@/utils/function";
import config from "@/app.config";
import http from "@/plugins/http";

import type { DataStructureTree } from "@/interface/main";
import type { DataOption } from "@/modules/13_salary/interface/index/Main";

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

const $q = useQuasar();
const store = useSalaryListSDataStore();
const storeEmp = useSalaryEmployeeListSDataStore();

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

const checkId = ref<string>("");
const isLoadStructureTree = ref<boolean>(true);
// const expandedModal = ref<boolean>(false);
// const org = ref<string>("");
const year = ref<number>(calculateFiscalYear(new Date())); //ปีงบประมาณ
const isLoadFilePdf = ref<boolean>(false);
const employeeClass = ref<string>("officer");
const employeeClassOption = ref<DataOption[]>([
  { id: "officer", name: "ข้าราชการ กทม. สามัญ" },
  { id: "employee", name: "ลูกจ้างประจำ กทม." },
]);

const isRound = ref<boolean>(false);

const round = ref<any>("");
const roundOptions = ref<any[]>([]);

const group = ref<string>("GROUP1");
const groupOptions = ref<DataOption[]>([
  { id: "GROUP1", name: "กลุ่ม 1" },
  { id: "GROUP2", name: "กลุ่ม 2" },
]);

const report = ref<DataOption | null>(null);
const reportOption = computed(() => {
  const storeData = employeeClass.value === "officer" ? store : storeEmp;

  // ตรวจสอบว่า round.value มีค่าและมี shortCode
  if (!round.value?.shortCode) {
    return [];
  }

  // เลือก data source ตาม shortCode
  let dataSource: DataOption[] = [];
  switch (round.value.shortCode) {
    case "APR":
      dataSource = storeData.itemDownloadApr || [];
      break;
    case "OCT":
      dataSource = storeData.itemDownloadOct || [];
      break;
    default:
      dataSource = [];
  }

  // กรองข้อมูลที่ไม่ใช่ PDF Map keyId
  return dataSource
    .filter((e) => e.type !== "pdf")
    .map((e) => ({
      ...e,
      keyId: `${e.id}${e?.typeName ? `-${e.typeName}` : ""}`,
    }));
});

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

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

const detailReport = ref<any>();
const splitterModel = ref(14);

const organizationOpsMain = ref<DataStructureTree[]>([]);
const organizationOps = ref<DataStructureTree[]>([]);
const organizationName = computed(() => {
  return (
    organizationOpsMain.value.find(
      (e: DataStructureTree) => e.id === nodeId.value
    )?.orgRootName || ""
  );
});

/** ฟังก์ชันเรียกข้อมูลรอบการขึ้นเงินเดือน*/
async function fetchDataRound() {
  isRound.value = false;
  showLoader();
  await http
    .get(
      config.API.salaryPeriodActive(year.value.toString()) +
        `?page=${1}&pageSize=${50}&keyword=&year=0`
    )
    .then(async (res) => {
      const data = await res.data.result.data;
      if (data.length > 0) {
        isRound.value = true;
        roundOptions.value = await data.map((e: any) => ({
          ...e,
          shortCode: e.period,
          name:
            e.period === "OCT"
              ? "รอบตุลาคม "
              : e.period === "SPECIAL"
              ? "รอบพิเศษ "
              : "รอบเมษายน ",
        }));
        round.value = roundOptions.value[0];
        await fetchDataOrg(roundOptions.value[0].revisionId);
      } else {
        isRound.value = false;
        round.value = "";
        roundOptions.value = [];
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

async function fetchDataOrg(revisionId: string) {
  if (!revisionId)
    return (isLoadStructureTree.value = false), (checkId.value = revisionId);

  try {
    isLoadStructureTree.value = true;
    const res = await http.get(
      config.API.activeOrganizationRootById(revisionId)
    );
    const data = res.data.result.map((item: DataStructureTree) => ({
      ...item,
      children: null,
      labelName: `${item.orgRootName} ${item.orgRootCode} ${item.orgRootShortName}`,
    }));
    // node.value = data;
    organizationOps.value = data;
    organizationOpsMain.value = data;
  } catch (err) {
    messageError($q, err);
  } finally {
    isLoadStructureTree.value = false;
  }
}

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

function onChangeYear() {
  fetchDataRound();
}

function fetchReportPDF() {
  if (employeeClass.value && round.value && report.value?.id && nodeId.value) {
    fetchDataReportUnified(report.value?.id, employeeClass.value);
  }
}

async function fetchDataReportUnified(
  reportCode: string,
  employeeClass: string
) {
  isLoadFilePdf.value = true;
  pdfSrc.value = undefined;
  page.value = 1;
  const isHalfYearReport = (id: string) =>
    ["go1", "go2", "go2-01", "emp-08", "emp2-08"].includes(id);

  if (isHalfYearReport(reportCode)) {
    const formData: any = {
      type: "HAFT",
      startDate:
        reportCode === "go1" || reportCode === "emp-08"
          ? `${round.value?.year - 1}-10-01`
          : `${round.value?.year}-04-01`,
      endDate:
        reportCode === "go1" || reportCode === "emp-08"
          ? `${round.value?.year}-03-31`
          : `${round.value?.year}-09-30`,
      nodeId: nodeId.value,
      revisionId: round.value?.revisionId,
    };

    if (reportCode === "go2-01") {
      formData.isRetirement = true;
    }

    const pathApi =
      employeeClass === "officer"
        ? reportCode === "go2-01"
          ? config.API.leaveReportLeavedayRetire()
          : config.API.leaveReportLeaveday("officer")
        : config.API.leaveReportLeaveday("employee");

    try {
      const res = await http.post(pathApi, formData);
      const dataList = res.data.result;
      await fetchDocumentTemplate(dataList);
      // await genReportXLSX(dataList, data.name);
    } catch (e) {
      messageError($q, e);
    } finally {
      hideLoader();
      isLoadFilePdf.value = false;
    }
  } else if (nodeId.value && round.value) {
    const url = config.API.salaryReportListsByid(
      reportCode,
      nodeId.value,
      round.value.id
    );
    const isGovernmentId = [
      "gov-01",
      "gov-03",
      "gov-04",
      "gov-04-01",
      "gov-05",
      "gov-05-01",
      "gov-07",
      "gov-07-01",
      "gov-08",
      "gov-10",
    ].includes(reportCode);

    const finalUrl = isGovernmentId
      ? `${url}/${group.value}${
          report.value?.id === "gov-04" ? `/${report.value?.typeName}` : ""
        }`
      : `${url}${
          report.value?.id === "emp2-04" || report.value?.id === "emp-04"
            ? `/${report.value?.typeName}`
            : ""
        }`;

    try {
      const res = await http.get(finalUrl);
      const dataList = res.data.result;
      dataList && (await fetchDocumentTemplate(dataList));
    } catch (e) {
      messageError($q, e);
    } finally {
      hideLoader();
      isLoadFilePdf.value = false;
    }
  }
}

/**
 * function เรียกไฟล์ PDF
 * @param data  ข้อมูลบัญชีวันลา
 */
async function fetchDocumentTemplate(data: any) {
  detailReport.value = data;
  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) {
  const name = reportOption.value.find(
    (e) => e.keyId === report.value?.keyId
  )?.name;
  genReportXLSX(detailReport.value, `${name}_${organizationName.value}`, type);
}

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

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

function clearFilter() {
  checkId.value = "";
  year.value = calculateFiscalYear(new Date());
  round.value = "";
  group.value = "GROUP1";
  report.value = null;

  detailReport.value = undefined;
  pdfSrc.value = undefined;
  // org.value = "";
  nodeId.value = "";
  // nodeName.value = "";
}

/**
 * function ค้นหาคำใน select
 * @param val คำค้นหา
 * @param update function
 * @param type ประเภท select
 */
function filterSelector(val: string, update: Function, type: string) {
  switch (type) {
    case "organization":
      update(() => {
        organizationOps.value = organizationOpsMain.value.filter(
          (v: DataStructureTree) => v.labelName.toLowerCase().indexOf(val) > -1
        );
      });
      break;

    default:
      break;
  }
}

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

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายงานระบบเงินเดือน
  </div>

  <q-form greedy @submit.prevent @validation-success="fetchReportPDF">
    <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"
                bg-color="white"
                @update:model-value="(report = null), fetchReportPDF"
              >
              </q-select>
            </div>
            <q-space />
            <div>
              <q-btn
                :loading="isLoadFilePdf"
                flat
                round
                color="primary"
                icon="download"
                :disable="!detailReport"
                v-if="checkPermission($route)?.attrIsGet"
              >
                <q-menu>
                  <q-list style="min-width: 150px">
                    <q-item
                      clickable
                      v-close-popup
                      @click.stop.prevent="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.prevent="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.prevent="clearFilter"
                  />
                </q-card-section>
                <q-card-section class="q-pa-none">
                  <div class="col-12 q-px-sm">
                    <datepicker
                      v-model="year"
                      :locale="'th'"
                      autoApply
                      year-picker
                      :enableTimePicker="false"
                      @update:model-value="onChangeYear"
                    >
                      <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
                              size="18px"
                              name="event"
                              class="cursor-pointer"
                              style="color: var(--q-primary)"
                            >
                            </q-icon>
                          </template>
                        </q-input>
                      </template>
                    </datepicker>
                  </div>
                  <q-separator />
                  <div class="col-12 q-px-sm">
                    <q-select
                      v-model="round"
                      label="รอบการขึ้นเงินเดือน"
                      dense
                      borderless
                      map-options
                      option-label="name"
                      option-value="id"
                      :options="roundOptions"
                      lazy-rules
                      hide-bottom-space
                      bg-color="white"
                      @update:model-value="report = null"
                    >
                    </q-select>
                  </div>
                  <q-separator />
                  <div
                    class="col-12 q-px-sm"
                    v-if="employeeClass === 'officer'"
                  >
                    <q-select
                      v-model="group"
                      label="กลุ่ม"
                      dense
                      borderless
                      emit-value
                      map-options
                      option-label="name"
                      option-value="id"
                      :options="groupOptions"
                      lazy-rules
                      hide-bottom-space
                      bg-color="white"
                    >
                      <template #append>
                        <q-icon
                          name="help_outline"
                          color="info"
                          size="20px"
                          class="cursor-pointer"
                          v-if="group"
                        >
                          <q-tooltip>
                            <div v-if="group === 'GROUP1'">
                              <div>ทั่วไป: ปฏิบัติงาน, ชำนาญงาน, อาวุโส</div>
                              <div>
                                วิชาการ: ปฏิบัติการ, ชำนาญการ, ชำนาญการพิเศษ
                              </div>
                              <div>อำนวยการ: ต้น</div>
                            </div>
                            <div v-else>
                              <div>ทั่วไป: ทักษะพิเศษ</div>
                              <div>วิชาการ: เชี่ยวชาญ, ทรงคุณวุฒิ</div>
                              <div>อำนวยการ: สูง</div>
                              <div>บริหาร: ต้น, สูง</div>
                            </div>
                          </q-tooltip>
                        </q-icon>
                      </template>
                    </q-select>
                  </div>
                  <q-separator v-if="employeeClass === 'officer'" />
                  <div class="col-12 q-px-sm">
                    <q-select
                      borderless
                      dense
                      v-model="report"
                      :options="reportOption"
                      label="รายงาน"
                      option-label="name"
                      option-value="keyId"
                      class="bg-white"
                    />
                  </div>
                  <q-separator />
                  <div class="col-12 q-pb-xs q-px-sm">
                    <q-select
                      menu-anchor="top left"
                      menu-self="bottom left"
                      class="bg-white"
                      dense
                      borderless
                      hide-selected
                      fill-input
                      hide-bottom-space
                      option-label="orgRootName"
                      option-value="id"
                      emit-value
                      map-options
                      v-model="nodeId"
                      :options="organizationOps"
                      label="หน่วยงาน"
                      use-input
                      @filter="(inputValue: string,
            doneFn: Function) => filterSelector(inputValue, doneFn,'organization' )"
                    >
                      <template v-slot:no-option>
                        <q-item>
                          <q-item-section class="text-grey">
                            ไม่มีข้อมูล
                          </q-item-section>
                        </q-item>
                      </template>
                    </q-select>
                    <!-- <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>
                      </template>
                      <q-separator />

                      <q-card-section v-if="isLoadStructureTree && checkId">
                        <LoadView />
                      </q-card-section>
                      <q-card-section
                        v-else-if="isLoadStructureTree && !checkId"
                        class="q-pa-sm"
                      >
                        <div class="bg-grey-3 q-pa-sm rounded-borders">
                          ไม่พบข้อมูลสังกัด
                        </div>
                      </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.id"
                              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.orgRootName }}
                                </div>
                                <div class="text-weight-light text-grey-8">
                                  {{
                                    prop.node.orgRootCode == null
                                      ? null
                                      : prop.node.orgRootCode
                                  }}
                                  {{
                                    prop.node.orgRootShortName == null
                                      ? null
                                      : prop.node.orgRootShortName
                                  }}
                                </div>
                              </div>
                            </q-item>
                          </template>
                        </q-tree>
                      </q-card-section>
                    </q-expansion-item> -->
                  </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 == '' || round == '' || report == null"
                  />
                </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-model="splitterModel"
                disable
                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="isLoadFilePdf" />
                    <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>
            </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-container {
  overflow: auto;
  height: 58vh;
  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>
