<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import { VuePDF, usePDF } from "@tato30/vue-pdf";
import axios from "axios";
import genReportXLSX from "@/plugins/genreportxlsx";
import genReport from "@/plugins/genreport";

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

import type { DataStructureTree } from "@/interface/main";
import type { OptionData } from "@/modules/07_insignia/interface/index/Main";
import type {
  DataOption,
  DataOptioGroup,
  PosLevel,
  PosType,
} from "@/modules/11_discipline/interface/index/Main";

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

const $q = useQuasar();
const route = useRoute();
const { fetchStructureTree } = useStructureTree();
const { messageError, showLoader, hideLoader } = useCounterMixin();

const year = ref<number>(new Date().getFullYear());
const employeeClass = ref<string>("officer");
const employeeClassOption = ref<OptionData[]>([
  { id: "officer", name: "ข้าราชการ กทม. สามัญ" },
  { id: "employee", name: "ลูกจ้างประจำ กทม." },
]);

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

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

const isLoadPDF = ref<boolean>(false);

const posType = ref<string>("");
const posTypeMainOp = ref<PosType[]>([]);
const posTypeOp = ref<PosType[]>(posTypeMainOp.value);

const posLevel = ref<string>("");
const posLevelMainOp = ref<PosLevel[]>([]);
const posLevelOp = ref<PosLevel[]>(posLevelMainOp.value);

const offenseDetail = ref<string>("");
const offenseDetailOp = ref<DataOption[]>([
  { id: "", name: "ทั้งหมด" },
  { id: "NOT_SPECIFIED", name: "ยังไม่ระบุ" },
  { id: "NOT_DEADLY", name: "ไม่ร้ายแรง" },
  { id: "DEADLY", name: "ร้ายแรง" },
]);

const disciplinaryFaultLevel = ref<string>("");
const disciplinaryFaultLevelOp = ref<DataOptioGroup[]>([
  { id: "0", name: "ไม่ร้ายแรง", disable: true },
  { id: "ภาคทัณฑ์", name: "ภาคทัณฑ์", disable: false },
  {
    id: "ตัดเงินเดือน",
    name: "ตัดเงินเดือน",
    disable: false,
  },
  {
    id: "ลดขั้นเงินเดือน",
    name: "ลดขั้นเงินเดือน",
    disable: false,
  },
  { id: "4", name: "ร้ายแรง", disable: true },
  { id: "ปลดออก", name: "ปลดออก", disable: false },
  { id: "ไล่ออก", name: "ไล่ออก", disable: false },
  { id: "อื่นๆ", name: "อื่นๆ", disable: false },
]);

const status = ref<string>("");
const statusOp = ref<DataOption[]>([
  { id: "", name: "ทั้งหมด" },
  { id: "NEW", name: "ใหม่" },
  { id: "SEND_INVESTIGATE", name: "มีมูลส่งไปสืบสวนแล้ว" },
  { id: "INVESTIGATE", name: "กำลังสืบสวน" },
  { id: "SEND_DISCIPLINARY", name: "ส่งไปสอบสวนแล้ว" },
  { id: "DISCIPLINARY", name: "กำลังสอบสวน" },
  { id: "SEND_RESULT", name: "ส่งไปสรุปผลการพิจารณาแล้ว" },
  { id: "DONE", name: "สรุปผลการพิจารณาแล้ว" },
  { id: "STOP", name: "ยุติเรื่อง" },
]);

const detailReport = ref<any>();
const fileBlob = ref<any>();

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;
  onUpdateFilter();
}

/**
 * ฟังก์ชันโหลดไฟล์
 * @param type  ประเภทไฟล์
 * @param download
 */
async function onUpdateFilter() {
  if (nodeId.value && posType.value && posLevel.value) {
    isLoadPDF.value = true;
    pdfSrc.value = undefined;

    const body = {
      nodeId: nodeId.value,
      node: nodeLevel.value,
      year: year.value,
      offenseDetail: offenseDetail.value,
      disciplinaryFaultLevel: disciplinaryFaultLevel.value,
      status: status.value,
      posType: posType.value,
      posLevel: posLevel.value,
    };
    await http
      .post(config.API.disciplineReportByType(employeeClass.value), body)
      .then(async (res) => {
        const data = res.data.result;
        detailReport.value = data;
        data && (await genReportPreview(data));
      })
      .catch(async (e) => {
        messageError($q, JSON.parse(await e.response.data.text()));
      })
      .finally(() => {
        isLoadPDF.value = false;
      });
  }
}

/**
 * function เรียกไฟล์ PDF
 * @param data  ข้อมูลบัญชีวันลา
 */
async function genReportPreview(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);
      fileBlob.value = 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(() => {
      setTimeout(() => {
        hideLoader();
      }, 2000);
    });
}

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

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

function downloadReport(type: string) {}

/**
 * ฟังก์เรียกข้อมูลรายการประเภทตำแหน่ง
 */
async function getType() {
  await http
    .get(config.API.orgPosType)
    .then(async (res) => {
      posTypeMainOp.value = await res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

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

function updateLevel(val: string) {
  if (val) {
    const listData = posTypeMainOp.value.find(
      (item: PosType) => item.id == val
    );
    posLevelMainOp.value = listData ? listData.posLevels : [];
  }
}
onMounted(async () => {
  await Promise.all([fetchDataTree(), getType()]);
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">รายงานวินัย</div>

  <div class="q-pa-sm q-gutter-sm">
    <q-card flat bordered class="col-12">
      <div class="row q-col-gutter-sm q-pa-sm">
        <div class="row col-12">
          <q-select
            outlined
            dense
            v-model="employeeClass"
            :options="employeeClassOption"
            label="ประเภท"
            emit-value
            map-options
            option-label="name"
            option-value="id"
            style="width: 230px"
            @update:model-value="onUpdateFilter"
          >
          </q-select>

          <q-space />
          <q-btn
            flat
            round
            :disable="!nodeId || !employeeClass || !posType || !posLevel"
            color="primary"
            icon="download"
            v-if="checkPermission($route)?.attrIsGet"
          >
            <q-menu>
              <q-list style="min-width: 150px">
                <q-item
                  clickable
                  v-close-popup
                  @click="
                    genReportXLSX(
                      detailReport,
                      `รายชื่อที่กระทำความผิดทางวินัย_${
                        employeeClass == 'officer'
                          ? 'ข้าราชการ กทม. สามัญ'
                          : 'ลูกจ้างประจำ กทม.'
                      }_${year + 543}`,
                      '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="
                    genReport(
                      detailReport,
                      `รายชื่อที่กระทำความผิดทางวินัย_${
                        employeeClass == 'officer'
                          ? 'ข้าราชการ กทม. สามัญ'
                          : 'ลูกจ้างประจำ กทม.'
                      }_${year + 543}`,
                      'docx'
                    )
                  "
                >
                  <q-item-section avatar
                    ><q-icon color="blue" name="mdi-file-word"
                  /></q-item-section>
                  <q-item-section>ไฟล์ .docx</q-item-section>
                </q-item>
                <q-item
                  clickable
                  v-close-popup
                  @click="
                    genReportXLSX(
                      detailReport,
                      `รายชื่อที่กระทำความผิดทางวินัย_${
                        employeeClass == 'officer'
                          ? 'ข้าราชการ กทม. สามัญ'
                          : 'ลูกจ้างประจำ กทม.'
                      }_${year + 543}`,
                      '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 class="row col-12">
          <q-card bordered class="col-12 filter-card q-pa-sm">
            <div class="row col-12 q-col-gutter-sm">
              <div class="col-md-4 col-xs-12">
                <datepicker
                  v-model="year"
                  :locale="'th'"
                  autoApply
                  year-picker
                  :enableTimePicker="false"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      class="bg-white"
                      dense
                      outlined
                      :model-value="Number(year) + 543"
                      :label="`${'ปีพ.ศ.'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
              <div class="col-md-4 col-xs-12">
                <q-select
                  class="bg-white"
                  hide-bottom-space
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="offenseDetail"
                  :label="`${'ลักษณะความผิด'}`"
                  emit-value
                  map-options
                  :options="offenseDetailOp"
                  option-value="id"
                  option-label="name"
                  @update:model-value="onUpdateFilter"
                />
              </div>
              <div class="col-md-4 col-xs-12">
                <q-select
                  class="bg-white"
                  hide-bottom-space
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="disciplinaryFaultLevel"
                  :label="`${'ระดับความผิด'}`"
                  emit-value
                  map-options
                  :options="disciplinaryFaultLevelOp"
                  option-value="id"
                  option-label="name"
                  @update:model-value="onUpdateFilter"
                />
              </div>
              <div class="col-md-4 col-xs-12">
                <q-select
                  class="bg-white"
                  hide-bottom-space
                  outlined
                  dense
                  lazy-rules
                  borderless
                  v-model="status"
                  :label="`${'สถานะของเรื่อง'}`"
                  emit-value
                  map-options
                  :options="statusOp"
                  option-value="id"
                  option-label="name"
                  @update:model-value="onUpdateFilter"
                />
              </div>
              <div class="col-md-4 col-xs-12">
                <q-select
                  class="bg-white"
                  hide-bottom-space
                  outlined
                  dense
                  lazy-rules
                  borderless
                  hide-selected
                  v-model="posType"
                  :label="`${
                    employeeClass == 'officer' ? 'ประเภทตำแหน่ง' : 'กลุ่มงาน'
                  }`"
                  emit-value
                  map-options
                  :options="posTypeOp"
                  option-value="id"
                  option-label="posTypeName"
                  use-input
                  fill-input
                  @update:model-value="(value:string)=>(onUpdateFilter,updateLevel(value))"
                  @filter="(inputValue:any, doneFn:Function) =>
            filterOption(inputValue, doneFn,'type')
          "
                />
              </div>
              <div class="col-md-4 col-xs-12">
                <q-select
                  class="bg-white"
                  hide-bottom-space
                  outlined
                  dense
                  lazy-rules
                  borderless
                  hide-selected
                  v-model="posLevel"
                  :label="`${
                    employeeClass == 'officer' ? 'ระดับตำแหน่ง' : 'ระดับชั้นงาน'
                  }`"
                  emit-value
                  map-options
                  :options="posLevelOp"
                  option-value="id"
                  option-label="posLevelName"
                  use-input
                  fill-input
                  @update:model-value="onUpdateFilter"
                  @filter="(inputValue:any, doneFn:Function) =>
            filterOption(inputValue, doneFn,'level')
          "
                />
              </div>
            </div>
          </q-card>
        </div>
      </div>
    </q-card>
    <q-card flat bordered 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.orgLevel)
                  "
                  :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>
    </q-card>
  </div>
</template>

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

.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>
