<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";

import type { PersonData } from "@/modules/06_retirement/interface/index/Main";
import DialogHeader from "@/components/DialogHeader.vue";

/** Use */
const $q = useQuasar(); //ใช้ noti quasar
const mixin = useCounterMixin();
const {
  messageError,
  success,
  showLoader,
  hideLoader,
  dialogConfirm,
  findOrgName,
} = mixin;
const route = useRoute();
const retireld_params = route.params.id;

/** props*/
const props = defineProps({
  retireld: String,
  profileId: String,
  dataProfile: Object,
  UpdateListId: {
    type: Function,
    default: () => console.log("UpdateListId"),
  },
});

const modal = ref<boolean>(false);
const retireld = ref<any>();
const type = ref<any>();

/** คอลัมน์ */
const columns = ref<any["columns"]>([
  {
    name: "index",
    required: true,
    label: "ลำดับ",
    field: "index",
    align: "left",
  },
  {
    name: "fullname",
    required: true,
    label: "ชื่อ-นามสกุล",
    field: "fullname",
    align: "left",
  },
  {
    name: "position",
    required: true,
    label: "ตำแหน่งในสายงาน",
    field: "position",
    align: "left",
  },
  {
    name: "level",
    required: true,
    label: "ประเภทตำแหน่ง",
    field: "level",
    align: "left",
  },
  {
    name: "organizationOrganization",
    required: true,
    label: "สังกัด",
    field: "organizationOrganization",
    align: "left",
  },
]);
const rows = ref<PersonData[]>([]);

function findOrgChildName(obj: any) {
  if (obj) {
    let name =
      obj.orgChild4Name != null && obj.orgChild3Name != null
        ? obj.orgChild4Name + "/"
        : obj.orgChild4Name != null
        ? obj.orgChild4Name
        : "";

    name +=
      obj.orgChild3Name != null && obj.orgChild2Name != null
        ? obj.orgChild3Name + "/"
        : obj.orgChild3Name !== null
        ? obj.orgChild3Name
        : "";

    name +=
      obj.orgChild2Name != null && obj.orgChild1Name != null
        ? obj.orgChild2Name + "/"
        : obj.orgChild2Name != null
        ? obj.orgChild2Name
        : "";

    name +=
      obj.orgChild1Name != null && obj.orgRootName != null
        ? obj.orgChild1Name + "/"
        : obj.orgChild1Name != null
        ? obj.orgChild1Name
        : "";
    name += obj.orgRootName != null ? obj.orgRootName : "";
    return name == "" ? "-" : name;
  } else {
    return "";
  }
}

const formPagePersonList = reactive({ keyword: "", pageSize: 10, page: 1 });
const maxPage = ref<number>(1);
const totalList = ref<number>(0);

// fecth profile
async function fecthProfile() {
  showLoader();
  if (props?.dataProfile?.type === "OFFICER") {
    formPagePersonList.keyword =
      formPagePersonList.keyword === null ? "" : formPagePersonList.keyword;
    await http
      .post(config.API.orgProfileRetire, formPagePersonList)
      .then((res) => {
        maxPage.value = Math.ceil(
          res.data.result.total / formPagePersonList.pageSize
        );
        totalList.value = res.data.result.total;
        rows.value = res.data.result.data.map((e: any) => ({
          id: e.id,
          prefix: e.prefix,
          firstName: e.firstName,
          lastName: e.lastName,
          fullname: e.prefix + e.firstName + " " + e.lastName,
          position: e.position,
          level:
            e.posTypeName && e.posLevelName
              ? e.posTypeName + " (" + e.posLevelName + ")"
              : "-",
          organizationOrganization: findOrgChildName(e),
        }));
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  } else {
    let queryParams: any = {
      page: formPagePersonList.page,
      pageSize: formPagePersonList.pageSize,
      searchKeyword: formPagePersonList.keyword,
      searchField: "fullName",
      type: "perm",
    };
    http
      .get(config.API.registryNew("-employee"), { params: queryParams })
      .then((res) => {
        maxPage.value = Math.ceil(
          res.data.result.total / formPagePersonList.pageSize
        );
        totalList.value = res.data.result.total;
        rows.value = res.data.result.data.map((e: any) => ({
          id: e.id,
          prefix: e.prefix,
          firstName: e.firstName,
          lastName: e.lastName,
          fullname: e.prefix + e.firstName + " " + e.lastName,
          position: e.position,
          level:
            e.posType && e.posLevel ? e.posType + " (" + e.posLevel + ")" : "-",
          organizationOrganization: findOrgName(e),
        }));
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

// ยืนยันการเพิ่มราชชื่อ
function clickAdd(props: any) {
  if (retireld.value == undefined) {
    retireld.value = retireld_params;
  }
  let data: any = props.row.id;
  dialogConfirm(
    $q,
    async () => {
      await http
        .put(config.API.profileRetire(retireld.value), { profileId: data })
        .then(() => {
          success($q, "เพิ่มข้อมูลสำเร็จ");
          updateListData(retireld.value, data);
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          modal.value = false;
        });
    },
    "ยืนยันการเพิ่มข้อมูล",
    "ต้องการเพิ่มข้อมูลนี้ใช่หรือไม่ ?"
  );
}

// update retireld
function updateListData(retireld: string, pId: string) {
  props.UpdateListId(retireld, pId);
}

function updatePageSize(newPagination: any) {
  formPagePersonList.page = 1;
  formPagePersonList.pageSize = newPagination.rowsPerPage;
}

function closeDialog() {
  modal.value = false;
}

watch(
  () => formPagePersonList.pageSize,
  () => {
    fecthProfile();
  }
);

watch(modal, () => {
  if (modal.value === true) {
    retireld.value = props.retireld;
    formPagePersonList.page = 1;
    formPagePersonList.keyword = "";
    if (props.dataProfile) {
      if (props.dataProfile.type === "OFFICER") {
        type.value = "officer";
      } else type.value = "all";
    }

    fecthProfile();
  }
});
</script>

<template>
  <q-btn flat round class="primary" icon="mdi-plus" @click="modal = true">
    <q-tooltip>เพิ่มรายชื่อ</q-tooltip></q-btn
  >

  <q-dialog v-model="modal" Persistent>
    <q-card style="width: 900px; max-width: 80vw">
      <DialogHeader :tittle="'เพิ่มรายชื่อ'" :close="closeDialog" />
      <q-separator />
      <q-card-section>
        <div class="row q-col-gutter-sm">
          <div class="col-12">
            <q-input
              borderless
              outlined
              dense
              clearable
              v-model="formPagePersonList.keyword"
              placeholder="ค้นหา"
              @keyup.enter="(formPagePersonList.page = 1), fecthProfile()"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>
          </div>
          <div class="col-12">
            <d-table
              flat
              bordered
              dense
              :rows="rows"
              :columns="columns"
              row-key="name"
              class="custom-header-table"
              :rows-per-page-options="[10, 20, 50, 100]"
              @update:pagination="updatePageSize"
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th v-for="col in props.cols" :key="col.name" :props="props"
                    ><div>
                      <span class="row text-black">{{ col.label }}</span>
                    </div>
                  </q-th>
                  <q-th auto-width />
                </q-tr>
              </template>
              <template v-slot:body="props">
                <q-tr :props="props" class="cursor-pointer">
                  <q-td>{{
                    (formPagePersonList.page - 1) *
                      Number(formPagePersonList.pageSize) +
                    props.rowIndex +
                    1
                  }}</q-td>
                  <q-td key="fullname" :props="props">
                    {{ props.row.prefix ? props.row.prefix : ""
                    }}{{ props.row.firstName ? props.row.firstName : "" }}
                    {{ props.row.lastName ? props.row.lastName : "" }}
                  </q-td>
                  <q-td key="position" :props="props">
                    {{ props.row.position ? props.row.position : "-" }}
                  </q-td>
                  <q-td key="level" :props="props">{{ props.row.level }}</q-td>
                  <q-td
                    key="organizationOrganization"
                    :props="props"
                    class="table_ellipsis"
                  >
                    {{ props.row.organizationOrganization }}
                  </q-td>
                  <q-td>
                    <q-btn
                      outline
                      :props="props"
                      label="เพิ่ม"
                      class="text-teal-5"
                      @click="clickAdd(props)"
                    />
                  </q-td>
                </q-tr>
              </template>
              <template v-slot:pagination="scope">
                ทั้งหมด {{ totalList }} รายการ
                <q-pagination
                  v-model="formPagePersonList.page"
                  color="primary"
                  :max="maxPage"
                  :max-pages="5"
                  size="sm"
                  boundary-links
                  direction-links
                  @update:model-value="fecthProfile"
                ></q-pagination>
              </template>
            </d-table>
          </div>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style lang="scss">
.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;
  }

  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }

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