<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { usePagination } from "@/composables/usePagination";

import type { QTableColumn } from "quasar";
import type { DataOption } from "@/modules/06_retirement/interface/index/Main";
import type { FilterRetirementOld } from "@/modules/06_retirement/interface/request/Main";
import type {
  RetirementOld,
  DataRecords,
  OfficerDocument,
} from "@/modules/06_retirement/interface/response/Main";

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

const $q = useQuasar();
const { showLoader, hideLoader, messageError } = useCounterMixin();
const { pagination, params, onRequest } = usePagination(
  "",
  fetchDataRetirement
);

/** Title Page */
const titlePage = computed(() => {
  return `ข้อมูลผู้พ้นราชการก่อนปี ${new Date().getFullYear() + 543}`;
});

const optionStatusMain = ref<DataOption[]>([
  { name: "ข้าราชการ", id: "officer" },
  { name: "ลูกจ้างชั่วคราว", id: "employee" },
]);
const optionStatus = ref<DataOption[]>(optionStatusMain.value);

/** Filter */
const filter = ref<FilterRetirementOld>({
  type: "officer",
  retireYear: new Date().getFullYear() - 1,
  citizenID: "",
  firstNameTH: "",
  lastNameTH: "",
});

const rows = ref<DataRecords[]>([]); // ข้อมูลผู้พ้นราชการ
const columns = ref<QTableColumn[]>([
  {
    name: "recordRow",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "recordRow",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenID",
    align: "left",
    label: "เลขบัตรประชาชน",
    sortable: false,
    field: "citizenID",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: false,
    field: "fullName",
    format(val, row) {
      return `${row.firstNameTH} ${row.lastNameTH}`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionNameTH",
    align: "left",
    label: "ตำแหน่ง",
    sortable: false,
    field: "positionNameTH",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionTypeNameTH",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: false,
    field: "positionTypeNameTH",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionLevelNameTH",
    align: "left",
    label: "ระดับ",
    sortable: false,
    field: "positionLevelNameTH",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organizeNameTH",
    align: "left",
    label: "สังกัด",
    sortable: false,
    field: "organizeNameTH",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "retireYear",
    align: "left",
    label: "ปีที่พ้น",
    sortable: false,
    field: "retireYear",
    format(val, row) {
      return val ? (Number(val) + 543).toString() : "-";
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "retireTypeNameTH",
    align: "left",
    label: "เหตุผลของการพ้นจากตำแหน่ง",
    sortable: false,
    field: "retireTypeNameTH",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const modalViewDocument = ref<boolean>(false);
const documentData = ref<OfficerDocument[]>([]);

/** ฟังก์ชันสำหรับดึงข้อมูลผู้พ้นราชการ */
async function fetchDataRetirement() {
  showLoader();
  try {
    const response = await http.post(config.API.exRetirement, {
      page: params.value.page,
      type: filter.value.type,
      retireYear: filter.value.retireYear.toString(),
      citizenID: filter.value.citizenID,
      firstNameTH: filter.value.firstNameTH.trim(),
      lastNameTH: filter.value.lastNameTH.trim(),
    });
    const data: RetirementOld = response.data.data;
    pagination.value.rowsNumber = data.totalRecords;
    rows.value = data.dataRecords;
  } catch (error) {
    messageError($q, error);
  } finally {
    hideLoader();
  }
}

/**
 * ฟังก์ชันสำหรับกรองตัวเลือกสถานะ
 * @param inputValue ค่าที่กรอกในช่องค้นหา
 * @param doneFn ฟังก์ชันที่เรียกเมื่อกรองเสร็จ
 */
function filterOption(inputValue: string, doneFn: Function) {
  const needle = inputValue.toLowerCase();
  optionStatus.value = optionStatusMain.value.filter(
    (v) => v.name.toLowerCase().indexOf(needle) > -1
  );
  doneFn();
}

/** ฟังก์ชันสำหรับค้นหาข้อมูลผู้พ้นราชการ */
function searchData() {
  pagination.value.page = 1; // Reset to first page on new search
  fetchDataRetirement();
}

/** ฟังก์ชันสำหรับรีเซ็ตตัวกรอง */
function resetFilter() {
  filter.value = {
    type: "officer",
    retireYear: new Date().getFullYear() - 1,
    citizenID: "",
    firstNameTH: "",
    lastNameTH: "",
  };
  pagination.value = {
    page: 1,
    rowsPerPage: 25,
    rowsNumber: 0,
  };
  rows.value = [];
}

function handlerViewDocument(row: DataRecords) {
  modalViewDocument.value = true;
  documentData.value = row.officerDocument || [];
}

async function downloadDocument(item: OfficerDocument) {
  showLoader();
  try {
    const res = await http.get(
      config.API.exRetirement + `/document/${item.officerDocumentID}`,
      {
        headers: {
          "Content-Type": "application/pdf",
          Accept: "application/pdf",
        },
        responseType: "blob",
      }
    );
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", item.documentTypeName + ".pdf");
    document.body.appendChild(link);
    link.click();

    // // ทำความสะอาด
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    messageError($q, error);
  } finally {
    hideLoader();
  }
}

onMounted(() => {
  pagination.value.rowsPerPage = 25;
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    {{ titlePage }}
  </div>

  <!-- Filter Section -->
  <q-form greedy @submit.prevent @validation-success="searchData">
    <q-card class="q-mb-sm" flat bordered>
      <q-card-section>
        <div class="row q-col-gutter-md">
          <!-- Position Type -->
          <div class="col-12 col-md-6 col-lg-3">
            <div class="row q-col-gutter-sm">
              <!-- Type of Position -->
              <div class="col">
                <q-select
                  v-model="filter.type"
                  label="ประเภทตำแหน่ง"
                  option-label="name"
                  :options="optionStatus"
                  option-value="id"
                  dense
                  emit-value
                  map-options
                  outlined
                  use-input
                  hide-selected
                  fill-input
                  @filter="(inputValue:string,doneFn:Function) => filterOption(inputValue, doneFn)"
                  class="full-width"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        ไม่มีข้อมูล
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </div>

              <!-- Retirement Year -->
              <div class="col">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="filter.retireYear"
                  :locale="'th'"
                  autoApply
                  year-picker
                  :enableTimePicker="false"
                  :max-date="`${new Date().getFullYear() - 1}, 11, 31`"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      dense
                      outlined
                      :model-value="Number(filter.retireYear) + 543"
                      label="ปีที่ออกจากราชการ"
                      bg-color="white"
                      class="full-width"
                    >
                      <template v-slot:prepend>
                        <q-icon name="event" color="primary" />
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
            </div>
          </div>

          <!-- Citizen ID -->
          <div class="col-12 col-md-6 col-lg-3">
            <q-input
              outlined
              v-model="filter.citizenID"
              dense
              label="เลขบัตรประชาชน"
              hide-bottom-space
              maxlength="13"
              mask="#############"
            >
            </q-input>
          </div>

          <!-- Name Filters -->
          <div class="col-12 col-md-6 col-lg-3">
            <q-input
              outlined
              v-model="filter.firstNameTH"
              dense
              label="ชื่อ"
              hide-bottom-space
            >
            </q-input>
          </div>
          <div class="col-12 col-md-6 col-lg-3">
            <q-input
              outlined
              v-model="filter.lastNameTH"
              dense
              label="นามสกุล"
              hide-bottom-space
            >
            </q-input>
          </div>

          <!-- Search Actions -->
          <div class="row col-12 justify-end">
            <div class="row col-md-6 col-lg-3 q-gutter-sm full-height">
              <q-space />
              <q-btn
                color="primary"
                icon="search"
                label="ค้นหา"
                no-caps
                type="submit"
              />
              <q-btn
                color="grey-6"
                icon="refresh"
                label="รีเซ็ต"
                @click="resetFilter"
                outline
                no-caps
              />
            </div>
          </div>
        </div>
      </q-card-section>
    </q-card>
  </q-form>

  <!-- Results Section -->
  <q-card flat bordered>
    <q-card-section>
      <p-table
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="personId"
        flat
        bordered
        :paging="true"
        dense
        class="custom-header-table"
        :rows-per-page-options="[25]"
        v-model:pagination="pagination"
        @request="onRequest"
      >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              style="color: #000000; font-weight: 500"
            >
              <span class="text-weight-medium">{{ col.label }}</span>
            </q-th>
            <q-th auto-width />
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div v-if="col.name == 'no'">
                {{ props.rowIndex + 1 }}
              </div>

              <div>
                {{ col.value ?? "-" }}
              </div>
            </q-td>
            <q-td auto-width>
              <q-btn
                color="info"
                dense
                flat
                round
                icon="mdi-file-eye-outline"
                @click="handlerViewDocument(props.row)"
              >
                <q-tooltip>ไฟล์เอกสาร</q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </p-table>
    </q-card-section>
  </q-card>

  <q-dialog v-model="modalViewDocument" persistent max-width="600px">
    <q-card style="min-width: 400px">
      <DialogHeader
        :tittle="'ไฟล์เอกสาร'"
        :close="() => (modalViewDocument = false)"
      />
      <q-separator />
      <q-card-section class="row items-center">
        <q-list bordered separator class="full-width">
          <q-item v-for="item in documentData" :key="item.documentTypeID">
            <q-item-section> {{ item.documentTypeName }}</q-item-section>
            <q-item-section avatar>
              <q-btn
                color="primary"
                dense
                flat
                round
                icon="mdi-file-eye-outline"
                @click="downloadDocument(item)"
              >
                <q-tooltip>ไฟล์เอกสาร</q-tooltip>
              </q-btn>
            </q-item-section>
          </q-item>
        </q-list>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
