<script setup lang="ts">
import { ref, onMounted, watch, reactive, computed } from "vue";
import { useQuasar, QForm } from "quasar";

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

import { useRoute, useRouter } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { usePlacementDataStore } from "@/modules/05_placement/store";
import avatar from "@/assets/avatar_user.jpg";

import type { PartialTableName } from "@/modules/05_placement/interface/request/placement";
import type { QTableProps } from "quasar";
import type { DataList } from "@/modules/05_placement/interface/response/SelectOrg";

import DialogSelectOrg from "@/modules/05_placement/components/PersonalList/DialogSelectOrg.vue";
import Table from "@/modules/05_placement/components/PersonalList/TableView.vue";
import DialogCard from "@/modules/05_placement/components/PersonalList/DialogDetail.vue";
import DialogFooter from "@/modules/05_placement/components/PersonalList/DialogFooter.vue";
import DialogHeader from "@/components/DialogHeader.vue";
import DialogOrders from "@/modules/05_placement/components/PersonalList/DialogOrders.vue"; //ส่งไปออกคำสั่งขอโอน
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";

const $q = useQuasar(); // show dialog
const DataStore = usePlacementDataStore();
const route = useRoute();
const router = useRouter();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const {
  messageError,
  showLoader,
  hideLoader,
  dateText,
  success,
  dialogConfirm,
  date2Thai,
} = mixin;

/** รับค่ามาจากหน้าหลัก */
const props = defineProps({
  statCard: {
    type: Function,
    default: () => console.log("getStat"),
  },
});

let roleAdmin = ref<boolean>(false);
const edit = ref<boolean>(true);
const modalPersonal = ref<boolean>(false);
const modal = ref<boolean>(false); //modal ขอผ่อนผัน + สละสิทธิ์
const modalOrder = ref<boolean>(false); //modal คำสั่ง
const editRow = ref<boolean>(false); //เช็คมีการแก้ไขข้อมูล
const modalDisclaim = ref<boolean>(false); //modal ที่แสดงใช้สำหรับแก้ไขหรือไม่
const editvisible = ref<boolean>(true);
const modalDefermentDisclaim = ref<boolean>(false); //modal add detail
const checkValidate = ref<boolean>(false);
const modalwaitInfo = ref<boolean>(false); //modal add detail

const userNote = ref<string>("");
const filter = ref<string>("");
const Name = ref<string>();
const rowsAll = ref<any>([]);
const rows = ref<any[]>([]);
const rowsAwait = ref<any[]>([]);
const rowsFilter = ref<any>([]);
const rowsOrder = ref<any[]>([]);
const myForm = ref<any>();
const files = ref<any>(null);

const appointModal = ref<boolean>(false);
const getNumFile = ref(0);
const dataRes = ref<any>([]);
const personal = ref<any>([]);
const displayAdd = ref<boolean>(true);
const containStatus = ref<boolean>(false);
const modaladdlist = ref<boolean>(false);
const selected = ref<any>([]);
const personal_selected = ref<any>([]);
const filterlistAdd = ref<string>("");
const paging = ref<boolean>(true);

// เช็ตสถานะการเลือกคนไปยังหน่วยงาน
const checkSelected = computed(() => {
  if (selected.value.length === 0) {
    return true;
  }
});

const dataInfo = reactive({
  reason: "",
  reliefDoc: "",
});

const examId = route.params.examId;
const examIdString = Array.isArray(examId) ? examId[0] : examId;
const personalId = ref<string>("");

/** แสดงข้อมูลตารางหลัก */
const visibleColumns = ref<any[]>([
  "no",
  "fullName",
  "examNumber",
  "idCard",
  "positionNumber",
  "organizationName",
  "reportingDate",
  "bmaOfficer",
  "statusName",
  "draft",
  "positionCandidate",
]);

/** แสดงข้แมูลใน ตาราง
 * ตาราง ส่งรายชื่อไปหน่วยงาน
 */
const visibleColumnslist = ref<any>([
  "no",
  "fullName",
  "examNumber",
  "idCard",
  "positionNumber",
  "organizationName",
  "draft",
  "bmaOfficer",
  "positionCandidate",
]);

/**หัวตาราง */
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px,",
  },
  {
    name: "examNumber",
    align: "center",
    label: "ลำดับที่สอบได้",
    sortable: true,
    field: "examNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organizationName",
    align: "left",
    label: "หน่วยงานที่รับการบรรจุ",
    sortable: true,
    field: "organizationName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionCandidate",
    align: "left",
    label: "ตำแหน่งที่สอบ",
    sortable: true,
    field: "positionCandidate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "reportingDate",
    align: "left",
    label: "วันที่รายงานตัว",
    sortable: true,
    field: "reportingDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "bmaOfficer",
    align: "left",
    label: "สถานภาพ",
    sortable: true,
    field: "bmaOfficer",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "draft",
    align: "left",
    label: "สถานะการส่งรายชื่อ",
    sortable: true,
    field: "draft",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "statusName",
    align: "left",
    label: "สถานะการบรรจุ",
    sortable: true,
    field: "statusName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

/**
 * แปลงสถานะพนักงาน
 * @param val type
 */
function convertBmaOfficer(val: string) {
  switch (val) {
    case "OFFICER":
      return "ขรก.กทม. สามัญ";
    case "EMPLOYEE_PERM":
      return "ลูกจ้างประจำ";
    case "EMPLOYEE_TEMP":
      return "ลูกจ้างชั่วคราว";
    default:
      return "บุคคลภายนอก";
  }
}

/**
 * แปลงสถานะบรรจุ
 * @param val type
 */
function convertContainStatus(val: string) {
  switch (val) {
    case "UN-CONTAIN":
      return "ยังไม่บรรจุ";
    case "PREPARE-CONTAIN":
      return "เตรียมบรรจุ";
    case "DONE":
      return "บรรจุแล้ว";
    case "DISCLAIM":
      return "สละสิทธิ์";
    case "REPORT":
      return "ส่งไปออกคำสั่ง";
    default:
      return "-";
  }
}

// /**
//  * แปลงสถานะ
//  * @param val type
//  */
// function convertTypeCommand(val: string) {
//   switch (val) {
//     case "APPOINTED":
//       return "บรรจุแต่งตั้ง";
//     case "APPOINT":
//       return "แต่งตั้ง/ย้าย";
//     // case "SLIP":
//     //   return "เลื่อน";
//     // case "MOVE":
//     //   return "ย้าย";
//     default:
//       return "";
//   }
// }

/**
 * แปลงสถานะการส่งรายชื่อ
 * @param val true/false
 */
function convertDraft(val: boolean) {
  switch (val) {
    case false:
      return "รอส่งตัว";
    case true:
      return "ส่งตัวแล้ว";
    default:
      return "-";
  }
}

/**
 * เรียกข้อมูลรายชื่อผู้สอบผ่าน
 */
async function getTable() {
  showLoader();
  await http
    .get(config.API.personalList(examIdString))
    .then(async (res: any) => {
      dataRes.value = res.data.result;

      rowsAll.value = [];
      (rowsFilter.value = []),
        res.data.result.map((data: any) => {
          const rowData = {
            personalId: data.personalId,
            avatar: avatar,
            name: data.fullName,
            fullName: data.fullName + " " + data.idCard,
            idCard: data.idCard,
            examNumber: data.examNumber,
            root: data.root,
            rootId: data.rootId,
            rootIdOld: data.rootIdOld, // หน่วยงานเดิม
            rootShortName: data.rootShortName,
            child1: data.child1,
            child1Id: data.child1Id,
            child1ShortName: data.child1ShortName,
            child2: data.child2,
            child2Id: data.child2Id,
            child2ShortName: data.child2ShortName,
            child3: data.child3,
            child3Id: data.child3Id,
            child3ShortName: data.child3ShortName,
            child4: data.child4,
            child4Id: data.child4Id,
            child4ShortName: data.child4ShortName,
            node: data.node,
            nodeName: data.nodeName,
            nodeId: data.nodeId,
            nodeShortName: data.nodeShortName,
            orgRevisionId: data.orgRevisionId,
            positionId: data.positionId,
            posMasterNo: data.posMasterNo,
            positionName: data.positionName,
            positionField: data.positionField,
            posTypeId: data.posTypeId,
            posTypeName: data.posTypeName,
            posLevelId: data.posLevelId,
            posLevelName: data.posLevelName,
            positionCandidate: data.positionCandidate,
            positionCandidateId: data.positionCandidateId,
            reportingDate: data.reportingDate,
            bmaOfficer: convertBmaOfficer(data.bmaOfficer),
            bmaOfficerCheck: data.bmaOfficer,
            statusId: data.statusId,
            draft: convertDraft(data.draft),
            typeCommand: data.typeCommand,
            posTypeCandidateId: data.posTypeCandidateId,
            posTypeCandidateName: data.posTypeCandidateName,
            posLevelCandidateId: data.posLevelCandidateId,
            posLevelCandidateName: data.posLevelCandidateName,
            posmasterId: data.posmasterId,
            statusNameCheck: convertContainStatus(data.statusId),
            deferment: data.isRelief,
            statusName:
              data.isRelief === true &&
              data.statusId == "PREPARE-CONTAIN" &&
              data.node == null
                ? "ขอผ่อนผัน"
                : data.statusId == "DONE"
                ? "บรรจุแล้ว"
                : convertContainStatus(data.statusId),
            organizationName:
              data.root +
              " " +
              data.rootShortName +
              " " +
              data.nodeName +
              "" +
              data.nodeShortName +
              "" +
              data.posMasterNo,
            prefix: data.prefix,
            firstName: data.firstname,
            lastName: data.lastname,
            citizenId: data.citizenId,
            id: data.id,
            profileId: data.profileId,
          };
          rowsAll.value.push(rowData);
        });

      // รายชื่อทั้งหมด
      rows.value = await (roleAdmin.value
        ? rowsAll.value
        : rowsAll.value.filter((x: any) => x.statusId !== "DONE"));

      rowsAwait.value = await (roleAdmin.value
        ? rowsAll.value
        : rowsAll.value.filter((x: any) => x.statusId !== "DONE"));

      // รายชื่อไปยังหน่วยงาน
      rowsFilter.value = await rows.value.filter(
        (e: any) =>
          e.draft == "รอส่งตัว" &&
          e.nodeName !== null &&
          e.reportingDate !== null
      );
      DataStore.checkLoad(1);
      // insertAvatar(rows.value);
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(async () => {});
}

/**
 * ยืนยันการผ่อนผัน
 */
async function saveDeferment() {
  myForm.value.validate().then(async (result: boolean) => {
    if (result) {
      dialogConfirm(
        $q,
        async () => await postDeferment(),
        "ยืนยันการขอผ่อนผัน",
        "ต้องการยืนยันการขอผ่อนผันข้อมูลนี้ใช่หรือไม่ ?"
      );
    }
  });
}
/**
 * post ผ่อนผัน
 */
async function postDeferment() {
  showLoader();
  const formData = new FormData();
  formData.append("personalId", personalId.value);
  formData.append("note", userNote.value);
  formData.append("files", files.value[0]);
  await http
    .post(config.API.deferment(), formData)
    .then(async () => {
      await Promise.all([getTable(), props.statCard()]);
      await success($q, "บันทึกสำเร็จ");
      userNote.value = "";
      modalDefermentDisclaim.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ยืนยันการสละสิทธิ์
 */
async function saveDisclaim() {
  myForm.value.validate().then(async (result: boolean) => {
    if (result) {
      dialogConfirm(
        $q,
        async () => await postDisclaimf(),
        "ยืนยันการสละสิทธิ์",
        "ต้องการยืนยันการสละสิทธิ์ข้อมูลนี้ใช่หรือไม่ ?"
      );
    }
  });
}

/**
 * post การสละสิทธิ์
 */
async function postDisclaimf() {
  showLoader();
  const dataPost = {
    note: userNote.value,
    personId: personalId.value,
  };
  await http
    .post(config.API.disclaimF(), {
      note: dataPost.note,
      personalId: dataPost.personId,
    })
    .then(async () => {
      await Promise.all([getTable(), props.statCard()]);
      await success($q, "บันทึกสำเร็จ");
      userNote.value = "";
      modalDefermentDisclaim.value = false;
    })
    .finally(() => {
      hideLoader();
    });
}

/** เ
 * ปิด dialog
 */
function clickEditRow() {
  editRow.value = true;
}

/**
 * เปลี่ยน class true/false
 */
function getClass(val: boolean) {
  return {
    "full-width inputgreen cursor-pointer ": val,
    "full-width cursor-pointer": !val,
  };
}

/**
 * เรียกดูรายละเอียดข้อมูล
 * @param pid id personal
 * @param draft status
 */
function selectData(pid: string, draft: string) {
  if (roleAdmin.value && draft === "ส่งตัวแล้ว") {
    personalId.value = pid;
    modal.value = true;
  } else {
    router.push("/placement/personal-detail/" + pid);
  }
}

/**
 * แก้ไขข้อมูล
 * @param props rows data
 * @param action type
 */
function editDetail(
  props: PartialTableName,
  action: "disclaim" | "deferment" | "defermentInfo" | "disclaimInfo"
) {
  Name.value = props.name;
  personalId.value = props.personalId;
  editRow.value = false;
  edit.value = true;

  if (action === "disclaim") {
    getNumFile.value = 0;
    modalDisclaim.value = true;
    modalDefermentDisclaim.value = true;
  } else if (action === "deferment") {
    getNumFile.value = 1;
    modalDisclaim.value = false;
    modalDefermentDisclaim.value = true;
  } else if (action === "defermentInfo") {
    http
      .get(config.API.placementDefermentInfo(props.personalId))
      .then((res: any) => {
        dataInfo.reason = res.data.result.reliefReason;
        dataInfo.reliefDoc = res.data.result.reliefDoc;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        modalDisclaim.value = false;
        modalwaitInfo.value = true;
      });
  } else if (action === "disclaimInfo") {
    http
      .get(config.API.placementDisclaimInfo(props.personalId))
      .then((res: any) => {
        dataInfo.reason = res.data.result.rejectReason;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        modalDisclaim.value = true;
        modalwaitInfo.value = true;
      });
  }
}

/**
 * เปิด dialog
 * @param pid id personal
 */
const modalDialogSelectOrg = ref<boolean>(false);
const typeCommand = ref<string>("");
const dataRow = ref<DataList>();
function openAppointModal(pid: string, data: DataList) {
  dataRow.value = data;
  modalDialogSelectOrg.value = !modalDialogSelectOrg.value;
}

/**
 * close dialog
 */
async function clickCloseModalTree() {
  await getTable();
  appointModal.value = false;
  props.statCard();
}

/**
 * validate
 */
async function validateData() {
  checkValidate.value = true;
  await myForm.value.validate().then((result: boolean) => {
    if (result == false) {
      checkValidate.value = false;
    }
  });
}

/**
 * ปิด dialog
 */
function clickCloseSendModal() {
  modaladdlist.value = false;
}

/**
 * validate
 */
async function clickClose() {
  userNote.value = "";
  if (editRow.value == true) {
    dialogConfirm(
      $q,
      () => {
        modalDefermentDisclaim.value = false;
        modalwaitInfo.value = false;
        modal.value = false;
        files.value = null;
      },
      `ข้อมูลมีการแก้ไข`,
      `ยืนยันที่จะปิดโดยไม่บันทึกใช่หรือไม่?`
    );
  } else {
    modalDefermentDisclaim.value = false;
    modalwaitInfo.value = false;
    modal.value = false;
    modalDate.value = false;
  }
}

/**
 * ยืนยันส่งรายชื่อไปหน่วยงาน
 */
function savelist() {
  selected.value.map((e: any) => {
    personal_selected.value.push(e.personalId);
  });
  if (personal_selected.value) {
    dialogConfirm(
      $q,
      async () => {
        showLoader();
        await http
          .put(config.API.putPosition(examId), personal_selected.value)
          .then(async () => {
            await getTable();
            await success($q, "ส่งรายชื่อไปยังหน่วยงานสำเร็จ");
            modaladdlist.value = false;
          })
          .catch((e: any) => {
            messageError($q, e);
          })
          .finally(() => {
            hideLoader();
          });
      },
      "ยืนยันการส่งรายชื่อไปยังหน่วยงาน",
      "ต้องการยืนยันการส่งรายชื่อไปยังหน่วยงานหรือไม่?"
    );
  }
}

/**
 * เปิด popup ส่งรายชื่อไปยังหน่วยงาน
 * @param val true/false
 */
function handleModalAddListUpdate(val: boolean) {
  modaladdlist.value = val;
  (selected.value = []), (personal_selected.value = []);
}

function paginationLabel(start: number, end: number, total: number) {
  if (paging.value == true) return " " + start + "-" + end + " ใน " + total;
  else return start + "-" + end + " ใน " + total;
}

function onRestorePos(id: string) {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      await http
        .post(config.API.clearPosition(id), {})
        .then(async () => {
          await Promise.all([getTable(), props.statCard()]);
          await success($q, "คืนตำแหน่งสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(async () => {
          hideLoader();
        });
    },
    "ยืนยันการคืนตำแหน่ง",
    "ต้องการยืนยันการคืนตำแหน่งนี้ใช่หรือไม่ ?"
  );
}

const modalDate = ref<boolean>(false);
const reportingDate = ref<Date | null>(null);
const rowId = ref<string>("");
function onSelectDate(id: string, date: Date) {
  modalDate.value = true;
  rowId.value = id;
  reportingDate.value = date;
}

function onSubmitDate() {
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(config.API.clearDate(rowId.value), { date: reportingDate.value })
      .then(async () => {
        await Promise.all([getTable(), props.statCard()]);
        await success($q, "บันทึกข้อมูลสำเร็จ");
        modalDate.value = false;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        hideLoader();
      });
  });
}

/**
 * ฟังก์ชันส่งไปออกคำสั่ง
 *
 * ค้นหารายชื่อออกคำสั่งตามสถานะ อนุมัติ (APPROVE)
 */
function openModalOrder(val: boolean) {
  // ยังไม่ได้ดัก ส่ง ไป ทั้ง object #e.draft == "รอส่งตัว" &&
  rowsOrder.value = rows.value.filter(
    (e: any) =>
      (DataStore.isStaff &&
        (e.rootId == e.rootIdOld || e.bmaOfficer == "บุคคลภายนอก") &&
        e.draft == "ส่งตัวแล้ว" &&
        e.nodeName !== null &&
        e.reportingDate !== null &&
        e.statusId !== "REPORT" &&
        e.statusId !== "DONE") ||
      (DataStore.isOfficer &&
        e.rootId != e.rootIdOld &&
        e.draft == "ส่งตัวแล้ว" &&
        e.nodeName !== null &&
        e.reportingDate !== null &&
        e.statusId !== "REPORT" &&
        e.statusId !== "DONE")
  );
  modalOrder.value = val;
}

function onUpdateNewRows(val: string) {
  const data = rowsAwait.value;
  if (val !== "") {
    rows.value = data.filter((item: any) => {
      if (val === "EXTERNAL") {
        return item.bmaOfficerCheck === null;
      } else if (val === "OFFICER") {
        return item.bmaOfficerCheck === "OFFICER";
      }
    });
  } else {
    rows.value = data;
  }
}

watch(containStatus, () => {
  if (containStatus.value) {
    rows.value = rowsAll.value.filter((x: any) => x.statusId == "DONE");
  } else {
    rows.value = rowsAll.value.filter((x: any) => x.statusId != "DONE");
  }
});

async function getWorkFlow() {
  showLoader();
  await http
    .get(config.API.workflowKeycloakSystem("SYS_PLACEMENT_PASS"))
    .then(async (res) => {
      const data = await res.data.result;
      DataStore.isOfficer = data.isOfficer;
      DataStore.isStaff = data.isStaff;
      roleAdmin.value = data.isOfficer;
      if (roleAdmin.value === false) {
        displayAdd.value = false;
        visibleColumns.value = [
          "position",
          "fullName",
          "examNumber",
          "idCard",
          "positionNumber",
          "organizationName",
          "reportingDate",
          "bmaOfficer",
          "statusName",
          "positionCandidate",
        ];
      }
      hideLoader();
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

function onclickViewinfo(id: string) {
  modalPersonal.value = true;
  personalId.value = id;
}

function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

onMounted(async () => {
  await getWorkFlow();
  await getTable();
});
</script>

<template>
  <q-form ref="myForm">
    <Table
      :contain-status="containStatus"
      :rows="rows"
      :columns="columns"
      :filter="filter"
      :visible-columns="visibleColumns"
      v-model:inputfilter="filter"
      v-model:inputvisible="visibleColumns"
      v-model:editvisible="editvisible"
      v-model:containfilter="containStatus"
      @update-modaladdlist="handleModalAddListUpdate"
      @update-modaladdSendPerson="openModalOrder"
      @update-new-Rows="onUpdateNewRows"
      :history="true"
      :boss="true"
      :saveNoDraft="true"
      :role-admin="roleAdmin"
      :display-add="displayAdd"
      row-key="fullname"
    >
      <template #columns="props">
        <q-tr :props="props">
          <q-td auto-width>
            <q-btn
              v-if="
                props.row.statusId !== 'DONE' &&
                props.row.statusId !== 'REPORT' &&
                (checkPermission($route)?.attrIsGet ||
                  checkPermission($route)?.attrIsUpdate)
              "
              flat
              dense
              color="secondary"
              icon="mdi-dots-horizontal-circle-outline"
              round
            >
              <q-menu transition-show="jump-down" transition-hide="jump-up">
                <q-list dense style="min-width: 180px">
                  <q-item
                    v-if="checkPermission($route)?.attrIsGet"
                    clickable
                    v-close-popup
                    @click="selectData(props.row.personalId, props.row.draft)"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon color="info" size="xs" name="mdi-eye" />
                    </q-item-section>
                    <q-item-section>รายละเอียด</q-item-section>
                  </q-item>
                  <q-item
                    v-if="
                      props.row.nodeName !== null &&
                      props.row.statusId !== 'DONE' &&
                      props.row.statusId !== 'DISCLAIM' &&
                      checkPermission($route)?.attrIsUpdate
                    "
                    clickable
                    v-close-popup
                    @click="
                      onSelectDate(
                        props.row.personalId,
                        props.row.reportingDate
                      )
                    "
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="blue-7"
                        size="xs"
                        name="mdi-calendar-account"
                      />
                    </q-item-section>
                    <q-item-section>เลือกวันรายงานตัว</q-item-section>
                  </q-item>
                  <q-item
                    v-if="
                      roleAdmin &&
                      props.row.draft === 'รอส่งตัว' &&
                      props.row.nodeName !== null &&
                      checkPermission($route)?.attrIsUpdate
                    "
                    clickable
                    v-close-popup
                    @click="onRestorePos(props.row.personalId)"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="orange-7"
                        size="xs"
                        name="mdi-backup-restore"
                      />
                    </q-item-section>
                    <q-item-section>คืนตำแหน่ง</q-item-section>
                  </q-item>
                  <q-item
                    v-if="
                      props.row.bmaOfficer !== 'บุคคลภายนอก' &&
                      roleAdmin &&
                      props.row.draft !== 'ส่งตัวแล้ว' &&
                      props.row.statusId !== 'DISCLAIM' &&
                      checkPermission($route)?.attrIsUpdate
                    "
                    clickable
                    v-close-popup
                    @click="openAppointModal(props.row.personalId, props.row)"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="primary"
                        size="xs"
                        name="mdi-bookmark-outline"
                      />
                    </q-item-section>
                    <q-item-section
                      >เลือกหน่วยงานที่รับแต่งตั้ง/ย้าย</q-item-section
                    >
                  </q-item>

                  <q-item
                    v-if="
                      props.row.bmaOfficer == 'บุคคลภายนอก' &&
                      roleAdmin &&
                      props.row.draft !== 'ส่งตัวแล้ว' &&
                      props.row.statusId !== 'DISCLAIM' &&
                      checkPermission($route)?.attrIsUpdate
                    "
                    clickable
                    v-close-popup
                    @click="openAppointModal(props.row.personalId, props.row)"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="primary"
                        size="xs"
                        name="mdi-bookmark-outline"
                      />
                    </q-item-section>
                    <q-item-section
                      >เลือกหน่วยงานที่รับบรรจุและแต่งตั้ง</q-item-section
                    >
                  </q-item>

                  <!-- <q-item
                    v-if="
                      props.row.bmaOfficer !== 'บุคคลภายนอก' &&
                      roleAdmin &&
                      props.row.draft !== 'ส่งตัวแล้ว' &&
                      props.row.statusId !== 'DISCLAIM' &&
                      checkPermission($route)?.attrIsUpdate
                    "
                    clickable
                    v-close-popup
                    @click="
                      openAppointModal(props.row.personalId, props.row, 'SLIP')
                    "
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="primary"
                        size="xs"
                        name="mdi-bookmark-outline"
                      />
                    </q-item-section>
                    <q-item-section>เลือกหน่วยงานที่รับเลื่อน</q-item-section>
                  </q-item> -->

                  <!-- <q-item
                    v-if="
                      props.row.bmaOfficer !== 'บุคคลภายนอก' &&
                      roleAdmin &&
                      props.row.draft !== 'ส่งตัวแล้ว' &&
                      props.row.statusId !== 'DISCLAIM' &&
                      checkPermission($route)?.attrIsUpdate
                    "
                    clickable
                    v-close-popup
                    @click="
                      openAppointModal(props.row.personalId, props.row, 'MOVE')
                    "
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="primary"
                        size="xs"
                        name="mdi-bookmark-outline"
                      />
                    </q-item-section>
                    <q-item-section>เลือกหน่วยงานที่รับย้าย</q-item-section>
                  </q-item> -->

                  <q-separator />
                  <q-item
                    v-if="
                      roleAdmin &&
                      props.row.statusId === 'UN-CONTAIN' &&
                      checkPermission($route)?.attrIsUpdate
                    "
                    clickable
                    v-close-popup
                    @click="editDetail(props.row, 'deferment')"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="blue"
                        size="xs"
                        name="mdi-account-alert-outline"
                      />
                    </q-item-section>
                    <q-item-section>ขอผ่อนผัน</q-item-section>
                  </q-item>

                  <q-item
                    v-else-if="
                      props.row.deferment === true &&
                      props.row.statusId != 'DISCLAIM' &&
                      checkPermission($route)?.attrIsGet
                    "
                    clickable
                    v-close-popup
                    @click="editDetail(props.row, 'defermentInfo')"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="blue"
                        size="xs"
                        name="mdi-account-details-outline"
                      />
                    </q-item-section>
                    <q-item-section>ข้อมูลการผ่อนผัน</q-item-section>
                  </q-item>

                  <q-separator />
                  <q-item
                    v-if="
                      props.row.statusId === 'UN-CONTAIN' ||
                      (props.row.statusId === 'PREPARE-CONTAIN' &&
                        checkPermission($route)?.attrIsUpdate)
                    "
                    clickable
                    v-close-popup
                    @click="editDetail(props.row, 'disclaim')"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="pink"
                        size="xs"
                        name="mdi-account-cancel-outline"
                      />
                    </q-item-section>
                    <q-item-section>สละสิทธิ์</q-item-section>
                  </q-item>

                  <q-item
                    v-else-if="
                      props.row.statusId === 'DISCLAIM' &&
                      checkPermission($route)?.attrIsGet
                    "
                    clickable
                    v-close-popup
                    @click="editDetail(props.row, 'disclaimInfo')"
                  >
                    <q-item-section
                      style="min-width: 0px"
                      avatar
                      class="q-py-sm"
                    >
                      <q-icon
                        color="pink"
                        size="xs"
                        name="mdi-account-cancel-outline"
                      />
                    </q-item-section>
                    <q-item-section>ข้อมูลการสละสิทธิ์</q-item-section>
                  </q-item>
                </q-list>
              </q-menu>
            </q-btn>
          </q-td>
          <q-td v-for="col in props.cols" :key="col.name" :props="props">
            <template v-if="col.name === 'no'">
              {{ props.rowIndex + 1 }}
            </template>
            <template
              v-else-if="col.name === 'fullName'"
              class="table_ellipsis"
            >
              <q-item v-ripple>
                <q-item-section avatar>
                  <q-avatar size="30px" color="grey-4">
                    <q-img :src="props.row.avatar" class="photo-profile" />
                  </q-avatar>
                </q-item-section>

                <q-item-section>
                  <div class="text-weight-medium">
                    {{ props.row.name
                    }}<q-btn
                      v-if="props.row.bmaOfficerCheck == 'OFFICER'"
                      flat
                      round
                      color="info"
                      icon="info"
                      size="sm"
                      @click="onclickViewinfo(props.row.profileId)"
                      ><q-tooltip>ดูข้อมูลทะเบียนประวัติ</q-tooltip></q-btn
                    >
                  </div>
                  <div class="text-weight-light">{{ props.row.idCard }}</div>
                </q-item-section>
              </q-item>
            </template>
            <template v-else-if="col.name === 'examNumber'">
              <div class="text-weight-medium">
                {{ props.row.examNumber !== null ? props.row.examNumber : "-" }}
              </div>
            </template>

            <template v-else-if="col.name === 'organizationName'">
              <div
                v-if="
                  props.row.orgName !== null || props.row.positionPath !== null
                "
              >
                <div class="col-4">
                  <div class="text-weight-medium">
                    {{ props.row.root !== null ? props.row.root : "-" }}
                    {{
                      props.row.rootShortName !== null
                        ? `(${props.row.rootShortName})`
                        : ""
                    }}
                  </div>
                  <div class="text-weight-light">
                    {{ props.row.nodeName !== null ? props.row.nodeName : "" }}
                    {{
                      props.row.nodeShortName !== null
                        ? `(${props.row.nodeShortName}${props.row.posMasterNo})`
                        : ""
                    }}
                  </div>
                </div>
              </div>

              <div v-else>
                <div class="col-4">
                  <div class="text-weight-medium">-</div>
                </div>
              </div>
            </template>

            <template v-else-if="col.name === 'positionCandidate'">
              <div
                class="text-weight-medium"
                v-if="props.row.positionCandidate == null"
              >
                -
              </div>
              <div class="text-weight-medium" v-else>
                {{ props.row.positionCandidate }}
              </div>
            </template>

            <template v-else-if="col.name === 'reportingDate'">
              <div class="text-weight-medium">
                {{
                  props.row.reportingDate !== null
                    ? dateText(props.row.reportingDate)
                    : "-"
                }}
              </div>
            </template>

            <template v-else-if="col.name === 'bmaOfficer'">
              <div class="text-weight-medium">
                {{ props.row.bmaOfficer }}
              </div>
            </template>

            <template v-else-if="col.name === 'draft'">
              <div class="text-weight-medium">
                {{ props.row.draft }}
              </div>
            </template>

            <template v-else-if="col.name === 'statusName'">
              <div class="text-weight-medium">
                {{ props.row.statusName }}
              </div>
            </template>
          </q-td>
        </q-tr>
      </template>
    </Table>
  </q-form>

  <DialogOrgTree
    v-model:modal="appointModal"
    :personalId="personalId"
    :close="clickCloseModalTree"
    :personal="personal"
  />

  <!-- popup ขอผ่อนผัน / สละสิทธิ์ -->
  <q-form ref="myForm">
    <DialogCard
      v-model:Modal="modal"
      :personal-id="personalId"
      :close="clickClose"
      :validate="validateData"
    />
  </q-form>

  <q-dialog v-model="modalDefermentDisclaim" persistent>
    <q-card style="width: 800px">
      <q-form ref="myForm">
        <DialogHeader
          :tittle="`${modalDisclaim ? 'สละสิทธิ์' : 'ขอผ่อนผัน'} ${Name}`"
          :close="clickClose"
        />
        <q-separator />
        <q-card-section class="q-pa-md bg-grey-1">
          <div class="col-xs-12 col-sm-12 col-md-12">
            <q-input
              :class="getClass(edit)"
              hide-bottom-space
              :outlined="edit"
              dense
              lazy-rules
              :rules="[(val:string) => !!val || 'กรุณากรอกเหตุผล']"
              :readonly="!edit"
              :borderless="!edit"
              v-model="userNote"
              :label="`${'กรอกเหตุผล'}`"
              @update:model-value="clickEditRow"
              type="textarea"
            />
            <q-file
              v-if="getNumFile === 1"
              v-model="files"
              dense
              :label="`${'เลือกไฟล์เอกสารหลักฐาน'}`"
              outlined
              use-chips
              :rules="[(val:string) => !!val || 'กรุณาเลือกไฟล์เอกสารหลักฐาน']"
              multiple
              @update:model-value="clickEditRow"
              class="q-py-sm"
            >
              <template v-slot:prepend>
                <q-icon name="attach_file" color="primary" />
              </template>
            </q-file>
          </div>
        </q-card-section>
        <q-separator />
        <DialogFooter
          :editvisible="true"
          :validate="validateData"
          :save="modalDisclaim ? saveDisclaim : saveDeferment"
        />
      </q-form>
    </q-card>
  </q-dialog>

  <!-- dialog ข้อมูลขอผ่อนผัน / สละสิทธิ์ -->
  <q-dialog v-model="modalwaitInfo" persistent>
    <q-card style="width: 500px; max-width: 500px">
      <q-form ref="myForm">
        <DialogHeader
          :tittle="`${modalDisclaim ? 'สละสิทธิ์' : 'ขอผ่อนผัน'} ${Name}`"
          :close="clickClose"
        />
        <q-separator />
        <q-card-section class="q-p-sm">
          <div class="row">
            <div class="col-3 text-grey-7">เหตุผล</div>
            <div class="col-4">{{ dataInfo.reason }}</div>
          </div>
          <div v-if="!modalDisclaim" class="row q-pt-md">
            <div class="col-3 text-grey-7 q-mt-sm">เอกสารหลักฐาน</div>
            <div class="col-2 q-mt-sm">
              <q-btn
                type="a"
                :href="dataInfo.reliefDoc"
                color="primary"
                flat
                dense
                round
                size="14px"
                icon="mdi-download"
                target="_blank"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
      </q-form>
    </q-card>
  </q-dialog>

  <!-- dialog เพิ่มรายชื่อ -->
  <q-dialog v-model="modaladdlist">
    <q-card style="width: 950px; max-width: 80vw">
      <DialogHeader
        tittle="ส่งรายชื่อไปยังหน่วยงาน"
        :close="clickCloseSendModal"
      />
      <q-separator />
      <q-card-section class="q-pt-none">
        <div class="row justify-end">
          <div class="col-5">
            <q-toolbar style="padding: 0">
              <q-input
                borderless
                outlined
                dense
                debounce="200"
                v-model="filterlistAdd"
                placeholder="ค้นหา"
                style="width: 850px; max-width: auto"
              >
                <template v-slot:append>
                  <q-icon name="search" />
                </template>
              </q-input>
              <q-select
                v-model="visibleColumnslist"
                multiple
                outlined
                dense
                options-dense
                :display-value="$q.lang.table.columns"
                emit-value
                map-options
                :options="columns"
                option-value="name"
                
                style="min-width: 140px"
                class="gt-xs q-ml-sm"
              />
            </q-toolbar>
          </div>
        </div>

        <d-table
          flat
          bordered
          dense
          :rows="rowsFilter"
          :columns="columns"
          :filter="filterlistAdd"
          row-key="name"
          class="custom-header-table"
          selection="multiple"
          v-model:selected="selected"
          :pagination-label="paginationLabel"
          :visible-columns="visibleColumnslist"
        >
          <template v-slot:header-selection="scope">
            <q-checkbox
              keep-color
              color="primary"
              dense
              v-model="scope.selected"
            />
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td>
                <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"
                class="cursor-pointer"
              >
                <template v-if="col.name === 'no'">
                  {{ props.rowIndex + 1 }}
                </template>
                <template
                  v-else-if="col.name === 'fullName'"
                  class="table_ellipsis"
                >
                  <q-item v-ripple style="padding: 0">
                    <q-item-section avatar>
                      <q-avatar size="30px" color="grey-4">
                        <q-img
                          :src="props.row.avatar"
                          class="photo-profile"
                          v-if="props.row.avatar"
                        />
                        <q-img :src="avatar" class="photo-profile" v-else"/>
                      </q-avatar>
                    </q-item-section>

                    <q-item-section>
                      <div class="text-weight-medium">{{ props.row.name }}</div>
                      <div class="text-weight-light">
                        {{ props.row.idCard }}
                      </div>
                    </q-item-section>
                  </q-item>
                </template>
                <template v-else-if="col.name === 'examNumber'">
                  <div class="text-weight-medium">
                    {{
                      props.row.examNumber !== null ? props.row.examNumber : "-"
                    }}
                  </div>
                </template>

                <template v-else-if="col.name === 'organizationName'">
                  <div
                    v-if="
                      props.row.orgName !== null ||
                      props.row.positionPath !== null
                    "
                  >
                    <div class="col-4">
                      <div class="text-weight-medium">
                        {{ props.row.root !== null ? props.row.root : "-" }}
                        {{
                          props.row.rootShortName !== null
                            ? `(${props.row.rootShortName})`
                            : ""
                        }}
                      </div>
                      <div class="text-weight-light">
                        {{
                          props.row.nodeName !== null ? props.row.nodeName : ""
                        }}
                        {{
                          props.row.nodeShortName !== null
                            ? `(${props.row.nodeShortName}${props.row.posMasterNo})`
                            : ""
                        }}
                      </div>
                    </div>
                  </div>

                  <div v-else>
                    <div class="col-4">
                      <div class="text-weight-medium">-</div>
                    </div>
                  </div>
                </template>
                <template v-else-if="col.name === 'positionCandidate'">
                  <div
                    class="text-weight-medium"
                    v-if="props.row.positionCandidate == null"
                  >
                    -
                  </div>
                  <div class="text-weight-medium" v-else>
                    {{ props.row.positionCandidate }}
                  </div>
                </template>
                <template v-else-if="col.name === 'reportingDate'">
                  <div class="text-weight-medium">
                    {{
                      props.row.reportingDate !== null
                        ? dateText(props.row.reportingDate)
                        : "-"
                    }}
                  </div>
                </template>
                <template v-else-if="col.name === 'bmaOfficer'">
                  <div class="text-weight-medium">
                    {{ props.row.bmaOfficer }}
                  </div>
                </template>
                <template v-else-if="col.name === 'draft'">
                  <div class="text-weight-medium">
                    {{ props.row.draft }}
                  </div>
                </template>
                <template v-else-if="col.name === 'statusName'">
                  <div class="text-weight-medium">
                    {{ props.row.statusName }}
                  </div>
                </template>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
      <q-separator />
      <q-card-actions
        v-if="checkPermission($route)?.attrIsUpdate"
        align="right"
      >
        <q-btn
          label="ส่งรายชื่อ"
          @click="savelist"
          :disable="checkSelected"
          color="public"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!-- เลือกหน่วยงานที่บรรจุ -->
  <DialogSelectOrg
    v-model:modal="modalDialogSelectOrg"
    :data-row="dataRow"
    :fetch-table="getTable"
    :fetch-stat-card="statCard"
    :type-command="typeCommand"
  />

  <!-- dialog วันรายงานตัว-->
  <q-dialog v-model="modalDate" persistent>
    <q-card style="width: 500px; max-width: 300px">
      <q-form
        ref="myForm"
        greedy
        @submit.prevent
        @validation-success="onSubmitDate"
      >
        <DialogHeader :tittle="`เลือกวันรายงานตัว`" :close="clickClose" />
        <q-separator />
        <q-card-section class="q-p-sm">
          <datepicker
            menu-class-name="modalfix"
            v-model="reportingDate"
            :locale="'th'"
            autoApply
            borderless
            :enableTimePicker="false"
            week-start="0"
            :min-date="new Date()"
          >
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input
                class="inputgreen"
                ref="dateRef"
                outlined
                dense
                hide-bottom-space
                :model-value="
                  reportingDate != null ? date2Thai(reportingDate) : null
                "
                label="วันที่รายงานตัว"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="event"
                    class="cursor-pointer"
                    style="color: var(--q-primary)"
                  >
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <DialogOrders v-model:modal="modalOrder" :rows="rowsOrder" />
  <PopupPersonal
    :modal="modalPersonal"
    :id="personalId"
    @update:modal="updatemodalPersonal"
  />
</template>

<style lang="scss" scoped>
.custom-input {
  font-size: 16px;
}

.my-list-link {
  border-radius: 5px;

  font-weight: 600;
  border: 1px solid #00aa86;
}

.q-table p {
  margin-bottom: 0;
  color: #818181;
}
.photo-profile {
  width: 30px;
  height: 30px;
}
</style>
