<script setup lang="ts">
import { reactive, ref, watch, computed } 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,
  findOrgChildNameHtml,
} = mixin;
const route = useRoute();
const retireld_params = route.params.id;

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

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

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

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

// fecth profile
async function fecthProfile() {
  rows.value = [];
  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: findOrgChildNameHtml(e),
        }));
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  } else {
    http
      .post(config.API.registryNew("-employee") + "/retire", {
        page: formPagePersonList.page,
        pageSize: formPagePersonList.pageSize,
        keyword: formPagePersonList.keyword,
        type: "EMPLOYEE",
      })
      .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: findOrgChildNameHtml(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 () => {
      showLoader();
      await http
        .put(config.API.profileRetire(retireld.value), { profileId: data })
        .then(() => {
          success($q, "เพิ่มข้อมูลสำเร็จ");
          updateListData(retireld.value, data);
        })
        .catch((e) => {
          hideLoader();
          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-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">
                    <div class="text-html">
                      {{ props.row.organizationOrganization }}
                    </div>
                  </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.toLocaleString() }} รายการ
                <q-pagination
                  v-model="formPagePersonList.page"
                  active-color="primary"
                  color="dark"
                  :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"></style>
