<script setup lang="ts">
import { ref, watch, computed, reactive } from "vue";
import Header from "@/components/DialogHeader.vue";
import type {
  DataOption,
  FormFilter,
  NewPagination,
} from "@/modules/15_development/interface/index/Main";
import { useDevelopmentDataStore } from "@/modules/15_development/store/developmentStore";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar, type QTableProps } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";

const rows = ref<any[]>([]);
const props = defineProps({
  upDate: { type: Function },
});

const maxPage = ref<number>(1);

const formFilter = reactive<FormFilter>({
  page: 1,
  pageSize: 20,
  keyword: "",
  year: new Date().getFullYear(),
  type: "",
  posType: "",
  posLevel: "",
  retireYear: "",
  rangeYear: { min: 0, max: 60 },
  isShowRetire: null,
  isProbation: null,
});

const pagination = ref({
  page: 1,
  rowsPerPage: 20,
});

const $q = useQuasar();
const mixin = useCounterMixin();
const {
  dialogConfirm,
  messageError,
  dialogMessageNotify,
  showLoader,
  hideLoader,
} = mixin;
const store = useDevelopmentDataStore();

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

const selected = ref<any[]>([]);
const search = ref<string>("citizenId");
const inputSearch = ref<any>("");

const inputType = computed(() => {
  return search.value === "citizenId" ? "number" : "text";
});
const govOp = ref<DataOption[]>([
  {
    id: "citizenId",
    name: "เลขประจำตัวประชาชน",
  },
  {
    id: "fullName",
    name: "ชื่อ - นามสกุล",
  },
]);

const visibleColumns = ref<string[]>([
  "citizenId",
  "name",
  "position",
  "type",
  "level",
  "positionSide",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ - นามสกุล",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "position",
    align: "left",
    label: "ตําแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "type",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "type",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "level",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: true,
    field: "level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionSide",
    align: "left",
    label: "ตําแหน่งทางการบริหาร",
    sortable: true,
    field: "positionSide",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** save ข้อมูล */
function onSubmit() {
  if (selected.value?.length == 0) {
    dialogMessageNotify($q, `กรุณาเลือก 1 รายการ`);
  } else {
    const data = selected.value[0];
    const body = {
      id: data.id,
      name: data.name,
      prefix: data.prefix,
      rank: data.rank,
      firstName: data.firstName,
      lastName: data.lastName,
      citizenId: data.citizenId,
      level: data.level,
      type: data.type,
      posLevelId: data.posLevelId,
      posTypeId: data.posTypeId,
      position: data.position,
      positionSide: data.positionSide,
      posNo: data.posNo,
      org: data.org,
      rootId: data.rootId,
      root: data.root,
      orgRootShortName: data.orgRootShortName,
      orgRevisionId: data.orgRevisionId,
    };
    props.upDate?.(body);
    closeDialog();
  }
}

/** ปิด dialog */
function closeDialog() {
  modal.value = false;
  rows.value = [];
  selected.value = [];
  inputSearch.value = "";
}

/** class */
function getClass() {
  return "inputgreen";
}

function searchFilter() {
  showLoader();
  http
    .get(
      config.API.registryNew +
        `?page=${formFilter.page}&pageSize=${formFilter.pageSize}&searchField=${search.value}&searchKeyword=${inputSearch.value}`
    )
    .then((res) => {
      const data = res.data.result.data;
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
      rows.value = data.map((item: any) => ({
        id: item.id ? item.id : null,
        name: item.firstName
          ? `${item.prefix}${item.firstName} ${item.lastName}`
          : null,
        prefix: item.prefix ? item.prefix : null,
        rank: item.rank ? item.rank : null,
        firstName: item.firstName ? item.firstName : null,
        lastName: item.lastName ? item.lastName : null,
        citizenId: item.citizenId ? item.citizenId : null,
        level: item.posLevel ? item.posLevel : null,
        type: item.posType ? item.posType : null,
        posLevelId: item.posLevelId ? item.posLevelId : null,
        posTypeId: item.posTypeId ? item.posTypeId : null,
        position: item.position ? item.position : null,
        positionSide: item.posExecutive ? item.posExecutive : null,
        posNo: item.posNo ? item.posNo : null,
        org: item.org ? item.org : null,
        rootId: item.rootId ? item.rootId : null,
        root: item.root ? item.root : null,
        orgRootShortName: item.orgRootShortName ? item.orgRootShortName : null,
        orgRevisionId: item.orgRevisionId ? item.orgRevisionId : null,
      }));
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function updatePage(val: number) {
  formFilter.page = val;
  searchFilter();
}

function updatePageSize(newPagination: NewPagination) {
  formFilter.page = 1;
  formFilter.pageSize = newPagination.rowsPerPage;
}

watch(
  () => formFilter.pageSize,
  () => {
    searchFilter();
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 60%">
      <Header :tittle="'เลือกข้าราชการฯ'" :close="closeDialog" />
      <q-separator />

      <q-card-section>
        <div class="row q-col-gutter-x-sm">
          <div class="col-2">
            <q-select
              dense
              outlined
              label="ค้นหาจาก"
              v-model="search"
              option-label="name"
              option-value="id"
              :options="govOp"
              map-options
              emit-value
              :class="getClass()"
              @update:model-value="inputSearch = ''"
            />
          </div>
          <div class="col-8">
            <q-input
              dense
              outlined
              label="ค้นหา"
              v-model="inputSearch"
              :class="getClass()"
              :mask="search === 'citizenId' ? '#############' : undefined"
            />
          </div>
          <div class="col-2">
            <q-btn
              label="ค้นหา"
              class="full-width"
              unelevated
              color="teal"
              @click="searchFilter()"
            >
            </q-btn>
          </div>
        </div>
        <div class="q-mt-sm">
          <d-table
            style="max-height: 70vh"
            virtual-scroll
            selection="single"
            v-model:selected="selected"
            for="table"
            ref="table"
            :columns="columns"
            :rows="rows"
            row-key="id"
            flat
            bordered
            dense
            class="custom-header-table"
            :visible-columns="visibleColumns"
            v-model:pagination="pagination"
            :rows-per-page-options="[20, 25, 50, 100]"
            @update:pagination="updatePageSize"
          >
            <template v-slot:pagination="scope">
              <q-pagination
                v-model="formFilter.page"
                active-color="primary"
                color="dark"
                :max="Number(maxPage)"
                :max-pages="5"
                size="sm"
                boundary-links
                direction-links
                @update:model-value="updatePage"
              ></q-pagination>
            </template>
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th class="text-center"> </q-th>
                <q-th v-for="col in props.cols" :key="col.name" :props="props">
                  <span class="text-weight-medium">{{ col.label }}</span>
                </q-th>
              </q-tr>
            </template>
            <template v-slot:body="props">
              <q-tr :props="props" class="cursor-pointer">
                <q-td class="text-center">
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="props.selected"
                  />
                </q-td>
                <q-td v-for="col in props.cols" :key="col.name" :props="props">
                  <div>
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </q-card-section>
      <q-separator />

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn
          label="บันทึก"
          color="secondary"
          type="submit"
          @click="onSubmit()"
          ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
