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

import { useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

/** importType*/
import type { QTableProps } from "quasar";
import type { QForm } from "quasar";
import type { DataOption } from "@/modules/04_registryPerson/interface/index/Main";
import type {
  HistoryPos,
  Position,
} from "@/modules/04_registryPerson/interface/response/History";

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

//use
const myForm = ref<QForm>();
const router = useRouter();
const $q = useQuasar();
const { showLoader, hideLoader, messageError, date2Thai } = useCounterMixin();

//props
const modal = defineModel<boolean>("modal", { required: true }); //แสดง popup ประวัติถือครองตำแหน่ง

//ตัวแปร
const employeeClass = ref<string>(""); //ประเภทข้า่รายการ
const typeKeyword = ref<string>("");
const Keyword = ref<string>("");
const positionKeyword = ref<string>("");
const employeeClassOps = ref<DataOption[]>([
  { id: "officer", name: "ข้าราชการ กทม.สามัญ" },
  { id: "perm", name: "ลูกจ้างประจำ" },
]);
//ตัวเลือกประเภทการค้นหา
const typeKeywordOps = ref<DataOption[]>([
  { id: "no", name: "ตำแหน่งเลขที่" },
  { id: "position", name: "ตำแหน่ง" },
]);
const positionOps = ref<DataOption[]>([]);
const options = ref<DataOption[]>([]);

/** Table*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    label: "ลำดับ",
    field: "no",
    align: "left",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posNo",
    align: "left",
    label: "ตำแหน่งเลขที่",
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "date",
    align: "left",
    label: "วันที่ถือครอง",
    field: "date",
    format: (val, row) => `${date2Thai(val)}`,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const rows = ref<HistoryPos[]>([]);

/**  function fetch ข้อมูลตำแหน่ง ข้าราชการ*/
function fecthPositionOfficer() {
  http
    .get(config.API.listPositionPathHistory)
    .then((res) => {
      let data = res.data.result.items;

      positionOps.value = data.map((e: Position) => ({
        id: e.id,
        name: e.name,
      }));
      options.value = positionOps.value;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** function fetch ข้อมูลตำแหน่ง ลูกจ้างประจำ*/
function fetchPositionPerm() {
  http
    .get(config.API.listPositionEmployeePositionHistory)
    .then((res) => {
      let data = res.data.result.items;
      console.log(data);

      positionOps.value = data.map((e: Position) => ({
        id: e.id,
        name: e.name,
      }));
      options.value = positionOps.value;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** function เปลี่ยนประเภท*/
function changeEmployeeClass() {
  typeKeyword.value = "";
  Keyword.value = "";
  positionKeyword.value = "";
  rows.value = [];
}

/**
 * function เลือกฟิลด์ที่จะค้นหา
 * @param typeKeyword  ประเภทฟิลด์
 */
function selectTypeKeyword(typeKeyword: string) {
  positionOps.value = [];
  positionKeyword.value = "";
  Keyword.value = "";

  if (typeKeyword == "position" && employeeClass.value === "officer") {
    fecthPositionOfficer();
  } else if (typeKeyword == "position" && employeeClass.value === "perm") {
    fetchPositionPerm();
  }
}

/**
 * function ค้นหาประวัติถือครองตำแหน่ง
 * @param type ประเภทข่าราชการ
 */
function clickSearch(type: string) {
  myForm.value!.validate().then((result: boolean) => {
    if (result) {
      showLoader();
      let body = {};
      if (typeKeyword.value === "no") {
        Object.assign(body, {
          posNo: Keyword.value,
        });
      } else if (typeKeyword.value === "position") {
        Object.assign(body, {
          position: positionKeyword.value,
        });
      }
      const empType = type === "officer" ? "" : "-employee";
      http
        .post(config.API.registryNew(empType) + `/search/history/oc`, body)
        .then((res) => {
          let data = res.data.result;
          if (data.length !== 0) {
            rows.value = data.map((e: HistoryPos) => ({
              id: e.id,
              citizenId: e.citizenId,
              name: e.fullName,
              posNo: e.posNo,
              position: e.position,
              date: e.date,
            }));
          } else {
            rows.value = [];
          }
        })
        .catch((err) => {
          messageError($q, err);
          rows.value = [];
        })
        .finally(() => {
          hideLoader();
        });
    }
  });
}

/**
 * function ค้นหาข่อมูล Optiion
 * @param val คำค้นหา
 * @param update function
 */
function filterFn(val: string, update: Function) {
  if (val === "") {
    update(() => {
      options.value = positionOps.value;
    });
    return;
  } else {
    update(() => {
      options.value = positionOps.value.filter(
        (e) => e.name.search(val) !== -1
      );
    });
  }
}

/**
 * function redirect ไปทะเบียนประวัติ
 * @param id
 */
function clickRedirect(id: string) {
  const url =
    employeeClass.value === "officer"
      ? "registry-officer"
      : "registry-employee";
  router.push(`${url}/${id}`);
}

/** function ปิด popup*/
function closeDialog() {
  modal.value = false;
  employeeClass.value = "";
  typeKeyword.value = "";
  Keyword.value = "";
  positionKeyword.value = "";
  rows.value = [];
}
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 850px; max-width: 80vw">
      <DialogHeader :tittle="'ประวัติถือครองตำแหน่ง'" :close="closeDialog" />

      <q-separator />

      <q-card-section class="q-pa-sm">
        <q-form ref="myForm">
          <div class="col-12 bg-grey-2 q-pa-sm">
            <div class="col-12 row q-pb-sm q-col-gutter-sm items-center"></div>
            <q-toolbar>
              <div class="row q-col-gutter-sm">
                <q-select
                  hide-bottom-space
                  :rules="[(val:string) => !!val || `${'กรุณาเลือก ประเภท'}`]"
                  outlined
                  dense
                  lazy-rules
                  v-model="employeeClass"
                  emit-value
                  map-options
                  :options="employeeClassOps"
                  option-label="name"
                  option-value="id"
                  :label="`${'ประเภท'}`"
                  use-input
                  input-debounce="0"
                  @update:model-value="changeEmployeeClass"
                  style="width: 250px"
                />

                <q-select
                  hide-bottom-space
                  :rules="[(val:string) => !!val || `${'กรุณาเลือก ฟิลด์ที่จะค้น'}`]"
                  outlined
                  dense
                  lazy-rules
                  v-model="typeKeyword"
                  emit-value
                  map-options
                  :options="typeKeywordOps"
                  option-label="name"
                  option-value="id"
                  :label="`${' เลือกฟิลด์ที่จะค้น'}`"
                  use-input
                  input-debounce="0"
                  @update:model-value="selectTypeKeyword(typeKeyword)"
                  style="width: 250px"
                />
              </div>

              <q-space />
              <q-btn
                color="primary"
                icon="mdi-magnify"
                label="ค้นหา"
                outlined
                @click="clickSearch(employeeClass)"
              />
            </q-toolbar>
          </div>

          <div class="col-12 q-mt-sm">
            <d-table
              flat
              dense
              bordered
              :rows="rows"
              :columns="columns"
              row-key="order"
              no-data-label="ไม่มีข้อมูล"
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    <div class="text-grey-7 text-weight-medium">
                      <span class="row">{{ col.label }}</span>
                    </div>
                  </q-th>
                </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
                      v-else-if="col.name === 'citizenId'"
                      class="text-primary"
                      @click="clickRedirect(props.row.id)"
                    >
                      {{ props.row.citizenId ?? "-" }}
                    </div>
                    <div
                      v-else-if="col.name === 'name'"
                      class="text-primary"
                      @click="clickRedirect(props.row.id)"
                    >
                      {{ props.row.name ?? "-" }}
                    </div>
                    <div v-else class="table_ellipsis2">
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
            </d-table>
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
