<script setup lang="ts">
import { ref, watch, reactive } from "vue";

import { useQuasar, type QTableProps } from "quasar";

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

import type { DataOption } from "@/modules/15_development/interface/index/Main";

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

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

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

const modal = defineModel<boolean>("modal", { required: true });
const selected = ref<any[]>([]); // checkbox
const search = ref<string>("citizenId"); // กำหนดค่าเริ่มต้น ค้นหาจาก
const inputSearch = ref<any>(""); //ตัวแปร ค้นหา
const govOp = ref<DataOption[]>([
  {
    id: "citizenId",
    name: "เลขประจำตัวประชาชน",
  },
  {
    id: "fullName",
    name: "ชื่อ-นามสกุล",
  },
]);

const visibleColumns = ref<string[]>([
  "citizenId",
  "firstName",
  "position",
  "posType",
  "posLevel",
  "posExecutive",
]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "firstName",
    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: "posType",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "type",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevel",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: true,
    field: "level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posExecutive",
    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,
      rootDnaId: data.rootDnaId,
      root: data.root,
      orgRootShortName: data.orgRootShortName,
      orgRevisionId: data.orgRevisionId,
    };
    closeDialog();
    props.upDate?.(body);
  }
}

/** ปิด dialog */
function closeDialog() {
  modal.value = false;
  rows.value = [];
  selected.value = [];
  inputSearch.value = "";
  pagination.value = {
    page: 1,
    rowsPerPage: 10,
    rowsNumber: 0,
    sortBy: "",
  };
}

/** ดึงข้อมูลตาม keyword */
async function searchFilter() {
  showLoader();
  await http
    .get(config.API.developmentProfile, {
      params: {
        ...params.value,
        searchField: search.value,
        searchKeyword: inputSearch.value.trim(),
      },
    })
    .then((res) => {
      const result = res.data.result;
      pagination.value.rowsNumber = result.total;

      if (result.data.length !== 0) {
        rows.value = result.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,
          rootDnaId: item.rootId ? item.rootDnaId : 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 onfetchNewData() {
  pagination.value.page = 1;
  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-4">
            <q-select
              dense
              outlined
              label="ค้นหาจาก"
              v-model="search"
              option-label="name"
              option-value="id"
              :options="govOp"
              map-options
              emit-value
              @update:model-value="inputSearch = ''"
            />
          </div>
          <div class="col-6">
            <q-input
              dense
              outlined
              label="ค้นหา"
              v-model="inputSearch"
              :mask="search === 'citizenId' ? '#############' : undefined"
              @keyup.enter="onfetchNewData()"
            />
          </div>
          <div class="col-2">
            <q-btn
              label="ค้นหา"
              class="full-width full-height"
              unelevated
              outline
              color="primary"
              @click="onfetchNewData()"
            >
            </q-btn>
          </div>
        </div>
        <div class="q-mt-sm">
          <p-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]"
            @request="onRequest"
          >
            <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>
          </p-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>
