<script setup lang="ts">
import { ref } from "vue";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

/** importType*/
import type { DataOption } from "@/modules/04_registryNew/interface/index/Main";
import type { QForm } from "quasar";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

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

/**props*/
const modal = defineModel<boolean>("modal", { required: true });

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 columns = ref<any["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",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const rows = ref<any>([]);

function fecthPositionOfficer() {
  http
    .get(config.API.listPositionPathHistory)
    .then((res) => {
      let data = res.data.result.items;
      positionOps.value = data.map((e: any) => ({ id: e.id, name: e.name }));
      options.value = positionOps.value;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

function fetchPositionPerm() {
  http
    .get(config.API.listPositionEmployeePositionHistory)
    .then((res) => {
      let data = res.data.result.items;
      positionOps.value = data.map((e: any) => ({ id: e.id, name: e.name }));
      options.value = positionOps.value;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

function changeEmployeeClass() {
  typeKeyword.value = "";
  Keyword.value = "";
  positionKeyword.value = "";
  rows.value = [];
}
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 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: any) => ({
              id: e.id,
              citizenId: e.citizenId,
              name: e.firstName + "    " + e.lastName,
              posNo: e.posNo,
              position: e.position,
              date: date2Thai(e.date),
            }));
          } else {
            dialogMessageNotify($q, "ไม่มีข้อมูลที่ต้องการค้นหา");
            rows.value = [];
          }
        })
        .catch((err) => {
          messageError($q, err);
          rows.value = [];
        })
        .finally(() => {
          hideLoader();
        });
    }
  });
}
const options = ref<any>([]);
function filterFn(val: string, update: any) {
  if (val === "") {
    update(() => {
      options.value = positionOps.value;
    });
    return;
  } else {
    update(() => {
      options.value = positionOps.value.filter(
        (e) => e.name.search(val) !== -1
      );
    });
  }
}
function clickRedirect(id: string) {
  router.push(`/registry/${id}`);
}

const paging = ref<boolean>(true);
const pagination = ref({
  sortBy: "order",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});
const paginationLabel = (start: number, end: number, total: number) => {
  if (paging.value == true) return " " + start + "-" + end + " ใน " + total;
  else return start + "-" + end + " ใน " + total;
};
</script>

<template>
  <q-dialog v-model="modal">
    <q-card style="width: 850px; max-width: 80vw">
      <q-toolbar>
        <q-toolbar-title class="text-subtitle2 text-bold"
          >ประวัติถือครองตำแหน่ง</q-toolbar-title
        >
        <q-btn
          icon="close"
          unelevated
          round
          dense
          v-close-popup
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-toolbar>
      <q-separator />

      <div class="dialog-card-contain">
        <q-card-section class="q-pa-sm">
          <q-form ref="myForm">
            <div class="col-12 bg-grey-2 q-pa-sm">
              <div class="q-col-gutter-xs row no-wrap">
                <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"
                />
                <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)"
                />
                <q-input
                  v-if="typeKeyword === 'no'"
                  borderless
                  outlined
                  dense
                  debounce="300"
                  v-model="Keyword"
                  placeholder="เลขที่ตำแหน่ง"
                  :rules="[(val:string) => !!val || `${'กรุณากรอก เลขที่ตำแหน่ง'}`]"
                  hide-bottom-space
                />
                <q-select
                  v-if="typeKeyword === 'position'"
                  hide-bottom-space
                  :rules="[(val:string) => !!val || `${'กรุณาเลือก ตำแหน่ง'}`]"
                  outlined
                  dense
                  v-model="positionKeyword"
                  emit-value
                  map-options
                  :options="options"
                  option-label="name"
                  option-value="id"
                  :label="`${' เลือกตำแหน่ง'}`"
                  use-input
                  input-debounce="0"
                  @filter="filterFn"
                  behavior="menu"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        ไม่มีข้อมูล
                      </q-item-section>
                    </q-item>
                  </template></q-select
                >
                <q-space />
                <div class="col-2 row">
                  <q-btn
                    dense
                    color="primary"
                    icon="mdi-magnify"
                    label="ค้นหา"
                    class="col-12"
                    @click="clickSearch(employeeClass)"
                  />
                </div>
              </div>
            </div>
          </q-form>
        </q-card-section>
      </div>

      <div class="col-12 q-px-sm q-pb-sm">
        <q-table
          flat
          dense
          bordered
          :rows="rows"
          :columns="columns"
          row-key="order"
          class="custom-header-table"
          no-data-label="ไม่มีข้อมูล"
          :pagination-label="paginationLabel"
          v-model:pagination="pagination"
        >
          <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 key="no" :props="props"> {{ props.rowIndex + 1 }}</q-td>
              <q-td key="order" :props="props">{{ props.row.order }} </q-td>
              <q-td
                key="citizenId"
                class="text-primary"
                @click="clickRedirect(props.row.id)"
                :props="props"
                >{{ props.row.citizenId }}</q-td
              >
              <q-td
                key="name"
                class="text-primary"
                @click="clickRedirect(props.row.id)"
                :props="props"
                >{{ props.row.name }}</q-td
              >

              <q-td key="posNo" :props="props">{{ props.row.posNo }}</q-td>
              <q-td key="position" :props="props">{{
                props.row.position
              }}</q-td>
              <q-td key="date" :props="props">{{ props.row.date }}</q-td>
            </q-tr>
          </template>
          <template v-slot:pagination="scope">
            <q-pagination
              v-model="pagination.page"
              color="primary"
              :max="scope.pagesNumber"
              :max-pages="5"
              size="sm"
              boundary-links
              direction-links
            ></q-pagination>
          </template>
        </q-table>
      </div>

      <!-- <q-card-actions align="right">
        <q-btn flat label="OK" color="primary" v-close-popup />
      </q-card-actions> -->
    </q-card>
  </q-dialog>
</template>

<style scoped>
.custom-header-table {
  max-height: 64vh;

  .q-table tr:nth-child(odd) td {
    background: white;
  }

  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
    z-index: 1;
  }

  .q-table thead tr:last-child th {
    top: 48px;
  }

  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
