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

import { useRouter, useRoute } 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 } from "@/modules/04_registryPerson/interface/response/History";

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

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

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

//ตัวแปร
const employeeClass = ref<string>(
  route.name == "registryNew" ? "officer" : "perm"
); //ประเภทข้า่รายการ
const typeKeyword = ref<string>("");
const Keyword = ref<string>("");
const positionKeyword = ref<string>("");

//ตัวเลือกประเภทการค้นหา
const typeKeywordOps = ref<DataOption[]>([
  {
    id: "no",
    name: employeeClass.value === "officer" ? "เลขที่ตำแหน่ง" : "ตำแหน่งเลขที่",
  },
  { id: "position", name: "ตำแหน่ง" },
]);

/** 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:
      employeeClass.value === "officer" ? "เลขที่ตำแหน่ง" : "ตำแหน่งเลขที่",
    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 ค้นหาประวัติถือครองตำแหน่ง
 * @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.positionName,
              date: e.date,
            }));
          } else {
            rows.value = [];
          }
        })
        .catch((err) => {
          messageError($q, err);
          rows.value = [];
        })
        .finally(() => {
          hideLoader();
        });
    }
  });
}

/**
 * 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: 60vw; max-width: 80vw">
      <DialogHeader :tittle="'ประวัติถือครองตำแหน่ง'" :close="closeDialog" />

      <q-separator />

      <q-card-section class="q-pa-sm">
        <q-form ref="myForm">
          <div class="bg-grey-2 q-pa-sm">
            <div class="row q-col-gutter-sm full-width">
              <div class="col-3">
                <q-select
                  hide-bottom-space
                  :rules="[(val:string) => !!val || `${'กรุณาเลือก ฟิลด์ที่จะค้น'}`]"
                  outlined
                  dense
                  lazy-rules
                  bg-color="white"
                  v-model="typeKeyword"
                  emit-value
                  map-options
                  :options="typeKeywordOps"
                  option-label="name"
                  option-value="id"
                  :label="`${' เลือกฟิลด์ที่จะค้น'}`"
                  use-input
                  input-debounce="0"
                  @update:model-value="(Keyword = ''), (positionKeyword = '')"
                />
              </div>

              <div class="col-3" v-if="typeKeyword === 'no'">
                <q-input
                  outlined
                  dense
                  bg-color="white"
                  v-model="Keyword"
                  :placeholder="
                    employeeClass === 'officer'
                      ? 'เลขที่ตำแหน่ง'
                      : 'ตำแหน่งเลขที่'
                  "
                  :rules="[(val:string) => !!val ||  `${employeeClass === 'officer' ? 'กรุณากรอก เลขที่ตำแหน่ง' :
                      'กรุณากรอก ตำแหน่งเลขที่'}`]"
                  hide-bottom-space
                  @keyup.enter="clickSearch(employeeClass)"
                />
              </div>

              <div class="col-3" v-if="typeKeyword === 'position'">
                <q-input
                  outlined
                  dense
                  bg-color="white"
                  v-model="positionKeyword"
                  placeholder="ตำแหน่ง"
                  :rules="[(val:string) => !!val || `${'กรุณากรอก ตำแหน่ง'}`]"
                  hide-bottom-space
                  @keyup.enter="clickSearch(employeeClass)"
                />
              </div>
              <div :class="typeKeyword ? 'offset-3 col-3' : 'col-3 offset-6'">
                <q-btn
                  class="on-right bg-white full-width"
                  outline
                  color="primary"
                  label="ค้นหา"
                  @click="clickSearch(employeeClass)"
                  icon="mdi-magnify"
                />
              </div>
            </div>
          </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>
