<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import type { QTableProps } from "quasar";
import DialogHeader from "@/components/DialogHeader.vue";
import DialogAddPosition from "@/modules/02_organizationalNew/components/DialogAddPosition.vue";

import type {
  FormDataPosition,
  FormPositionRef,
  DataOption,
  FormPositionSelect,
  RowDetailPositions,
  FormPositionSelectRef,
  ListMenu,
} from "@/modules/02_organizationalNew/interface/index/Main";
import type {
  OptionType,
  OptionLevel,
  OptionExecutive,
  DataPosition,
} from "@/modules/02_organizationalNew/interface/response/organizational";
import type { FilterMaster } from "@/modules/02_organizationalNew/interface/request/organizational";
import http from "@/plugins/http";
import config from "@/app.config";

const props = defineProps({
  modal: Boolean,
  close: Function,
  orgLevel: Number,
  treeId: String,
  actionType: String,
  rowId: { type: String, default: "" },
  fetchDataTable: Function,
  getSummary: Function,
  shortName: { type: String, required: true },
});

const isEdit = ref<boolean>(false);
const modalAdd = ref<boolean>(false);
const reqMaster = defineModel<FilterMaster>("reqMaster", { required: true });
const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const isDisValidate = ref<boolean>(false);
const isPosition = ref<boolean>(false);
const succession = ref<boolean>(false); // id ของตำแหน่งที่จะสืบทอด
const dataCopy = ref<any>();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  dialogRemove,
  dialogMessageNotify,
} = mixin;
const selected = ref<any>([]);
const search = ref<string>("");
const type = ref<string>("positionName");
const optionFilter = ref<DataOption[]>([
  { id: "positionName", name: "ตำแหน่งในสายงาน" },
  { id: "positionField", name: "สายงาน" },
  { id: "positionType", name: "ประเภทตำแหน่ง" },
  { id: "positionLevel", name: "ระดับตำแหน่ง" },
  { id: "positionExecutive", name: "ตำแหน่งทางการบริหาร" },
  { id: "positionExecutiveField", name: "ด้านทางการบริหาร" },
  { id: "positionArea", name: "ด้าน/สาขา" },
]);

const typeOpsMain = ref<DataOption[]>([]);
const levelOpsMain = ref<DataOption[]>([]);
const executiveOpsMain = ref<DataOption[]>([]);
const executiveOps = ref<DataOption[]>([]);
const typeOps = ref<DataOption[]>([]);
const levelOps = ref<any[]>([]);

const listMenu = ref<ListMenu[]>([
  {
    label: "คัดลอก",
    icon: "mdi-content-copy",
    type: "copy",
    color: "blue-6",
  },
  {
    label: "แก้ไข",
    icon: "mdi-pencil",
    type: "edit",
    color: "edit",
  },
  {
    label: "ลบ",
    icon: "delete",
    type: "remove",
    color: "red",
  },
]);

const rows = ref<RowDetailPositions[]>([]);
const rowsPositionSelect = ref<RowDetailPositions[]>([]);
const ocLevelOp = ref<DataOption[]>([]);

const prefixNoRef = ref<Object | null>(null);
const positionNoRef = ref<Object | null>(null);

const positionNameRef = ref<Object | null>(null);
const positionFieldRef = ref<Object | null>(null);
const positionTypeRef = ref<Object | null>(null);
const positionLevelRef = ref<Object | null>(null);
const positionExecutiveRef = ref<Object | null>(null);
const positionExecutiveFieldRef = ref<Object | null>(null);
const positionAreaRef = ref<Object | null>(null);

const formData = reactive<FormDataPosition>({
  shortName: props.shortName,
  prefixNo: "",
  positionNo: "",
  suffixNo: "",
  reason: "",
});

const formPositionSelect = reactive<FormPositionSelect>({
  positionId: "",
  positionName: "",
  positionField: "",
  positionType: "",
  positionLevel: "",
  positionExecutive: "",
  positionExecutiveField: "",
  positionArea: "",
});
/** maping ref เข้าตัวแปรเพื่อเตรียมตรวจสอบ */
const objectPositionRef: FormPositionRef = {
  prefixNo: prefixNoRef,
  positionNo: positionNoRef,
};

const objectPositionSelectRef: FormPositionSelectRef = {
  positionName: positionNameRef,
  positionField: positionFieldRef,
  positionType: positionTypeRef,
  positionLevel: positionLevelRef,
  positionExecutive: positionExecutiveRef,
  positionExecutiveField: positionExecutiveFieldRef,
  positionArea: positionAreaRef,
};

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionName",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: true,
    field: "positionName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionField",
    align: "left",
    label: "สายงาน",
    sortable: true,
    field: "positionField",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posTypeName",
    align: "left",
    label: "ประเภทตำเเหน่ง",
    sortable: true,
    field: "posTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevelName",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: true,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posExecutiveName",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "posExecutiveName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionExecutiveField",
    align: "left",
    label: "ด้านทางการบริหาร",
    sortable: true,
    field: "positionExecutiveField",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionArea",
    align: "left",
    label: "ด้าน/สาขา",
    sortable: true,
    field: "positionArea",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "positionName",
  "positionField",
  "posTypeName",
  "posLevelName",
  "posExecutiveName",
  "positionExecutiveField",
  "positionArea",
]);

async function fetchPosition(id: string) {
  showLoader();
  await http
    .get(config.API.orgPosPositionById(id))
    .then((res) => {
      const data = res.data.result;
      formData.prefixNo = data.posMasterNoPrefix;
      formData.positionNo = data.posMasterNo;
      formData.suffixNo = data.posMasterNoSuffix;
      formData.reason = data.reason;
      rows.value = data.positions;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const dataLevel = ref<any>();
/** function เรียกรายการประเภทตำแหน่ง */
async function fetchType() {
  showLoader();
  await http
    .get(config.API.orgPosType)
    .then((res) => {
      dataLevel.value = res.data.result;
      typeOpsMain.value = res.data.result.map((e: OptionType) => ({
        id: e.id,
        name: e.posTypeName,
      }));
      typeOps.value = typeOpsMain.value;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เรียกรายการระดับตำแหน่ง */
// async function fetchLevel() {
//   showLoader();
//   await http
//     .get(config.API.orgPosLevel)
//     .then((res) => {
//       levelOpsMain.value = res.data.result.map((e: OptionLevel) => ({
//         id: e.id,
//         name: e.posLevelName,
//       }));
//       levelOps.value = levelOpsMain.value;
//     })
//     .catch((err) => {
//       messageError($q, err);
//     })
//     .finally(() => {
//       hideLoader();
//     });
// }

/** function เรียกรายการตำแหน่งทางการบริหาร */
async function fetchExecutive() {
  showLoader();
  await http
    .get(config.API.orgPosExecutive)
    .then((res) => {
      executiveOpsMain.value = res.data.result.map((e: OptionExecutive) => ({
        id: e.id,
        name: e.posExecutiveName,
      }));
      executiveOps.value = executiveOpsMain.value;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
function validateForm() {
  const hasError = [];
  for (const key in objectPositionRef) {
    if (Object.prototype.hasOwnProperty.call(objectPositionRef, key)) {
      const property = objectPositionRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    if (rows.value.length == 0) {
      dialogMessageNotify($q, "กรุณาเลือกตำแหน่งอย่างน้อย 1 ตำแหน่ง");
    } else {
      onSubmit();
    }
  }
}

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
// function validateFormPositionEdit() {
//   isDisValidate.value = false;
//   const hasError = [];
//   for (const key in objectPositionSelectRef) {
//     if (Object.prototype.hasOwnProperty.call(objectPositionSelectRef, key)) {
//       const property = objectPositionSelectRef[key];
//       if (property.value && typeof property.value.validate === "function") {
//         const isValid = property.value.validate();
//         hasError.push(isValid);
//       }
//     }
//   }
//   if (hasError.every((result) => result === true)) {
//     onSubmitSelectEdit();
//   }
// }

/** ฟังชั่น บันทึก */
function onSubmit() {
  dialogConfirm($q, async () => {
    const positionsData = rows.value.map((e: any) => ({
      posDictName: e.positionName, //ชื่อตำแหน่งในสายงาน (ชื่อตำแหน่ง)
      posDictField: e.positionField, //สายงาน
      posTypeId: e.posTypeId, //*ประเภทตำแหน่ง
      posLevelId: e.posLevelId, //*ระดับตำแหน่ง
      posExecutiveId: e.posExecutiveId ? e.posExecutiveId : "", //ตำแหน่งทางการบริหาร
      posDictExecutiveField: e.positionExecutiveField, //ด้านทางการบริหาร
      posDictArea: e.positionArea, //ด้าน/สาขา
      isSpecial: e.isSpecial,
      positionIsSelected: e.positionIsSelected,
    }));
    const body = {
      posMasterNoPrefix: formData.prefixNo, //*Prefix นำหน้าเลขที่ตำแหน่ง เป็น Optional (ไม่ใช่อักษรย่อของหน่วยงาน/ส่วนราชการ)
      posMasterNo: Number(formData.positionNo), //*เลขที่ตำแหน่ง เป็นตัวเลข
      posMasterNoSuffix: formData.suffixNo, //Suffix หลังเลขที่ตำแหน่ง เช่น ช.
      reason: formData.reason, //Suffix หลังเลขที่ตำแหน่ง เช่น ช.
      orgRootId: props.orgLevel === 0 ? props.treeId : null, //Id สำนัก
      orgChild1Id: props.orgLevel === 1 ? props.treeId : null,
      orgChild2Id: props.orgLevel === 2 ? props.treeId : null,
      orgChild3Id: props.orgLevel === 3 ? props.treeId : null,
      orgChild4Id: props.orgLevel === 4 ? props.treeId : null,
      positions: positionsData,
      // succession: succession.value,
    };

    showLoader();
    props.actionType === "ADD" || props.actionType === "COPY"
      ? await http
          .post(config.API.orgPosMaster, body)
          .then(() => {
            success($q, "เพิ่มข้อมูลสำเร็จ");
            props.fetchDataTable?.(
              reqMaster.value.id,
              reqMaster.value.type,
              false
            );
            props.getSummary?.();
            close();
          })
          .catch((err) => {
            messageError($q, err);
          })
          .finally(() => {
            hideLoader();
          })
      : props.rowId &&
        (await http
          .put(config.API.orgPosMasterById(props.rowId), body)
          .then(() => {
            success($q, "แก้ไขข้อมูลสำเร็จ");
            props.fetchDataTable?.(
              reqMaster.value.id,
              reqMaster.value.type,
              false
            );
          })
          .catch((err) => {
            messageError($q, err);
          })
          .finally(() => {
            close();
            hideLoader();
          }));
  });
}
/** ฟังชั่น บันทึก */
// function onSubmitSelectEdit() {
//   dialogConfirm(
//     $q,
//     async () => {
//       showLoader();
//       const body = {
//         posDictName: formPositionSelect.positionName,
//         posDictField: formPositionSelect.positionField, //สายงาน
//         posTypeId: formPositionSelect.positionType, //*ประเภทตำแหน่ง
//         posLevelId: formPositionSelect.positionLevel, //*ระดับตำแหน่ง
//         posExecutiveId:
//           formPositionSelect.positionExecutive !== ""
//             ? formPositionSelect.positionExecutive
//             : null, //ตำแหน่งทางการบริหาร
//         posDictExecutiveField: formPositionSelect.positionExecutiveField, //ด้านทางการบริหาร
//         posDictArea: formPositionSelect.positionArea, //ด้าน/สาขา
//       };
//       await http
//         .post(config.API.orgPosPosition, body)
//         .then(() => {
//           success($q, "เพิ่มข้อมูลสำเร็จ");

//           clearFormPositionSelect();
//         })
//         .catch((err) => {
//           messageError($q, err);
//         })
//         .finally(() => {
//           hideLoader();
//         });
//     },
//     "ยืนยันการเพิ่มตำแหน่ง",
//     "ต้องการยืนยันการเพิ่มตำแหน่งนี้ใช่หรือไม่?"
//   );
// }

/** input ค้นหา */
const searchRef = ref<any>(null);
async function searchInput() {
  searchRef.value.validate();
  if (!searchRef.value.hasError) {
    showLoader();
    await http
      .get(
        config.API.orgPosPosition +
          `?keyword=${search.value}&type=${type.value}`
      )
      .then((res) => {
        rowsPositionSelect.value = res.data.result;
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

// function updateSelectType(val: string) {
//   const listLevel = dataLevel.value.find((e: any) => e.id === val);
//   levelOpsMain.value = listLevel.posLevels.map((e: OptionLevel) => ({
//     id: e.id,
//     name: e.posLevelName,
//   }));
//   levelOps.value = levelOpsMain.value;
//   formPositionSelect.positionLevel = "";
// }

/**
 * คัดลอกข้อมูล
 * @param data ข้อมูลตำแหน่ง
 */
function copyDetiail(data: RowDetailPositions) {
  modalAdd.value = true;
  dataCopy.value = data;
}
/**
 * แก้ไขข้อมูล
 * @param data ข้อมูลตำแหน่ง
 */
function editDetiail(data: RowDetailPositions) {
  isEdit.value = true;
  modalAdd.value = true;
  dataCopy.value = data;
  console.log(isEdit.value);
}

/**
 * ส่งค่า css ออกไปตามเงื่อนไข
 * @param val true/false
 */
function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer inputgreen ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

watch(
  () => props.modal,
  () => {
    if (props.modal === true) {
      fetchType();
      fetchExecutive();

      if (props.actionType === "ADD") {
        rowsPositionSelect.value = [];
        search.value = "";
        rows.value = [];
        clearFormPositionSelect();
        formData.prefixNo = "";
        formData.positionNo = "";
        formData.suffixNo = "";
        formData.reason = "";
      } else {
        props.rowId && fetchPosition(props.rowId);
      }
    }
  }
);

async function addPosition(data: RowDetailPositions) {
  console.log(data);

  const isIdExist = await rows.value.some(
    (item: any) =>
      item.posExecutiveId == data.posExecutiveId &&
      item.positionField == data.positionField &&
      item.posLevelId == data.posLevelId &&
      item.posTypeId == data.posTypeId &&
      item.positionArea == data.positionArea &&
      item.positionExecutiveField == data.positionExecutiveField &&
      item.positionName == data.positionName &&
      item.isSpecial == data.isSpecial
  );

  if (!isIdExist) {
    rows.value = [...rows.value, data];
  }
}

function deleteData(id: string) {
  const dataRow = rows.value;
  const updatedRows = dataRow.filter((item: any) => item.id !== id);
  rows.value = updatedRows;
}

function deletePos(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.orgPosPositionById(id))
      .then(() => {
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        searchInput();
        hideLoader();
      });
  });
}

async function clearFormPositionSelect() {
  isDisValidate.value = await true;
  formPositionSelect.positionId = "";
  formPositionSelect.positionName = "";
  formPositionSelect.positionField = "";
  formPositionSelect.positionType = "";
  formPositionSelect.positionLevel = "";
  formPositionSelect.positionExecutive = "";
  formPositionSelect.positionExecutiveField = "";
  formPositionSelect.positionArea = "";

  setTimeout(async () => {
    isDisValidate.value = await false;
  }, 1000);
}

function close() {
  props.close?.();
  clearFormPositionSelect();
  isPosition.value = false;
}

async function emitSearch(keyword: string, typeSelect: string) {
  search.value = await keyword;
  type.value = await typeSelect;

  await searchInput();
}
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="min-width: 80vw">
      <DialogHeader
        :tittle="
          props.actionType === 'ADD' ? 'เพิ่มอัตรากำลัง' : 'แก้ไขอัตรากำลัง'
        "
        :close="close"
      />
      <q-separator />
      <form @submit.prevent="validateForm">
        <q-card-section class="q-pa-sm fixed-height">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-card bordered class="col-12" style="border: 1px solid #d6dee1">
                <div
                  class="col-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
                >
                  ข้อมูลอัตรากำลัง
                </div>
                <div class="col-12"><q-separator /></div>
                <div class="row q-col-gutter-sm col-12 q-pa-sm">
                  <div class="row col-8 q-col-gutter-sm">
                    <div class="col-12">
                      <q-input
                        v-model="formData.shortName"
                        dense
                        outlined
                        readonly
                        for="#shortName"
                        label="อักษรย่อ"
                      />
                    </div>
                    <div class="col-4">
                      <q-input
                        v-model="formData.prefixNo"
                        :class="inputEdit(isReadonly)"
                        ref="prefixNoRef"
                        dense
                        outlined
                        for="#prefixNo"
                        label="Prefix เลขที่ตำเเหน่ง"
                      />
                    </div>
                    <div class="col-4">
                      <q-input
                        v-model="formData.positionNo"
                        :class="inputEdit(isReadonly)"
                        ref="positionNoRef"
                        dense
                        outlined
                        for="#positionNo"
                        label="เลขที่ตำแหน่ง"
                        lazy-rules
                        hide-bottom-space
                        :rules="[
                          (val) => !!val || `${'กรุณากรอกเลขที่ตำแหน่ง'}`,
                        ]"
                        mask="########################"
                      />
                    </div>
                    <div class="col-4">
                      <q-input
                        v-model="formData.suffixNo"
                        :class="inputEdit(isReadonly)"
                        dense
                        outlined
                        for="#suffixNo"
                        label="Suffix เลขที่ตำแหน่ง"
                      />
                    </div>
                  </div>

                  <div class="col-4">
                    <q-input
                      v-model="formData.reason"
                      :class="inputEdit(isReadonly)"
                      dense
                      outlined
                      for="#reason"
                      label="หมายเหตุ"
                      type="textarea"
                      rows="4"
                    />
                  </div>

                  <div class="col-12">
                    <d-table
                      ref="table"
                      :columns="columns"
                      :rows="rows"
                      row-key="idcard"
                      flat
                      bordered
                      :paging="true"
                      dense
                      class="custom-header-table"
                      :visible-columns="visibleColumns"
                    >
                      <template v-slot:header="props">
                        <q-tr :props="props">
                          <q-th
                            v-for="col in props.cols"
                            :key="col.name"
                            :props="props"
                            style="color: #000000; font-weight: 500"
                          >
                            <span class="text-weight-medium">{{
                              col.label
                            }}</span>
                          </q-th>
                          <q-th auto-width></q-th>
                        </q-tr>
                      </template>
                      <template v-slot:body="props">
                        <q-tr :props="props" class="cursor-pointer">
                          <q-td
                            v-for="col in props.cols"
                            :key="col.name"
                            :props="props"
                          >
                            <div v-if="col.name == 'no'">
                              {{ props.rowIndex + 1 }}
                            </div>
                            <div v-else-if="col.name === 'posExecutiveName'">
                              {{ col.value ? col.value : "-" }}
                            </div>

                            <div
                              v-else-if="col.name === 'positionExecutiveField'"
                            >
                              {{ col.value ? col.value : "-" }}
                            </div>
                            <div v-else-if="col.name === 'posLevelName'">
                              {{
                                props.row.posLevelName
                                  ? props.row.isSpecial == true
                                    ? `${props.row.posLevelName} (ฉ)`
                                    : props.row.posLevelName
                                  : "-"
                              }}
                            </div>
                            <div v-else-if="col.name === 'positionArea'">
                              {{ col.value ? col.value : "-" }}
                            </div>
                            <div v-else>
                              {{ col.value }}
                            </div>
                          </q-td>
                          <q-td auto-width>
                            <q-btn
                              flat
                              dense
                              icon="mdi-delete"
                              class="q-pa-none q-ml-xs"
                              color="red"
                              @click="deleteData(props.row.id)"
                            >
                              <q-tooltip>ลบข้อมูล</q-tooltip>
                            </q-btn>
                          </q-td>
                        </q-tr>
                      </template>
                    </d-table>
                  </div>
                </div>
                <q-separator />

                <q-card-actions class="bg-white q-pa-xs">
                  <q-btn
                    :icon="!isPosition ? 'mdi-menu-right' : 'mdi-menu-down'"
                    flat
                    color="teal"
                    class="q-ml-sm"
                    label="เพิ่มตำแหน่ง"
                    @click="isPosition = !isPosition"
                    ><q-tooltip>{{
                      !isPosition
                        ? "คลิกเพื่อแสดงส่วนของการเพิ่มตำแหน่ง"
                        : "ปิดหน้าต่างการเพิ่มตำแหน่ง"
                    }}</q-tooltip></q-btn
                  >
                  <q-space />
                </q-card-actions>
              </q-card>
            </div>
          </div>

          <div v-if="isPosition" class="row q-col-gutter-sm q-mt-sm">
            <div class="col-12">
              <q-card bordered class="col-12" style="border: 1px solid #d6dee1">
                <div
                  class="col-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
                >
                  เลือกตำแหน่งที่ต้องการเพิ่ม
                  <q-btn
                    icon="mdi-plus"
                    flat
                    round
                    color="teal"
                    @click="() => (modalAdd = true)"
                    ><q-tooltip>สร้างตำแหน่ง</q-tooltip></q-btn
                  >
                </div>
                <div class="col-12"><q-separator /></div>
                <div class="q-pa-sm">
                  <div class="row col-12 q-col-gutter-sm items-start">
                    <div class="col-12 col-sm-6 col-md-3">
                      <q-select
                        label="ค้นหาจาก"
                        v-model="type"
                        :options="optionFilter"
                        emit-value
                        dense
                        map-options
                        outlined
                        option-label="name"
                        option-value="id"
                      />
                    </div>

                    <div class="col-12 col-sm-6 col-md-6">
                      <q-input
                        ref="searchRef"
                        :class="inputEdit(isReadonly)"
                        v-model="search"
                        outlined
                        clearable
                        dense
                        lazy-rules
                        label="คำค้น"
                        hide-bottom-space
                        :rules="[(val) => !!val || `กรุณากรอกคำค้น`]"
                        @keydown.enter.prevent="searchInput()"
                      />
                    </div>

                    <div class="col-12 col-sm-6 col-md-3">
                      <q-btn
                        color="primary"
                        icon="search"
                        label="ค้นหา"
                        class="full-width q-pa-sm"
                        @click="searchInput()"
                      >
                      </q-btn>
                    </div>
                  </div>

                  <div class="full-width q-mt-sm">
                    <d-table
                      ref="table"
                      :columns="columns"
                      :rows="rowsPositionSelect"
                      row-key="id"
                      flat
                      bordered
                      :paging="true"
                      dense
                      class="custom-header-table"
                      :visible-columns="visibleColumns"
                    >
                      <template v-slot:header="props">
                        <q-tr :props="props">
                          <q-th
                            v-for="col in props.cols"
                            :key="col.name"
                            :props="props"
                            style="color: #000000; font-weight: 500"
                          >
                            <span class="text-weight-medium">{{
                              col.label
                            }}</span>
                          </q-th>
                          <q-th auto-width></q-th>
                        </q-tr>
                      </template>
                      <template v-slot:body="props">
                        <q-tr :props="props" class="cursor-pointer">
                          <q-td
                            v-for="col in props.cols"
                            :key="col.name"
                            :props="props"
                            @click="addPosition(props.row)"
                          >
                            <div v-if="col.name == 'no'">
                              {{ props.rowIndex + 1 }}
                            </div>
                            <div v-else-if="col.name === 'posExecutiveName'">
                              {{ col.value ? col.value : "-" }}
                            </div>

                            <div
                              v-else-if="col.name === 'positionExecutiveField'"
                            >
                              {{ col.value ? col.value : "-" }}
                            </div>
                            <div v-else-if="col.name === 'posLevelName'">
                              {{
                                props.row.posLevelName
                                  ? props.row.isSpecial == true
                                    ? `${props.row.posLevelName} (ฉ)`
                                    : props.row.posLevelName
                                  : "-"
                              }}
                            </div>

                            <div v-else-if="col.name === 'positionArea'">
                              {{ col.value ? col.value : "-" }}
                            </div>
                            <div v-else>
                              {{ col.value }}
                            </div>
                          </q-td>
                          <q-td auto-width>
                            <q-btn
                              flat
                              dense
                              icon="mdi-dots-vertical"
                              class="q-pa-none q-ml-xs"
                              color="grey-13"
                            >
                              <q-menu anchor="bottom middle" self="top middle">
                                <q-list
                                  dense
                                  v-for="(item, index) in listMenu"
                                  :key="index"
                                >
                                  <q-item
                                    clickable
                                    v-close-popup
                                    @click="
                                      item.type === 'copy'
                                        ? copyDetiail(props.row)
                                        : item.type === 'edit'
                                        ? editDetiail(props.row)
                                        : deletePos(props.row.id)
                                    "
                                  >
                                    <q-item-section avatar>
                                      <q-icon
                                        :color="item.color"
                                        :name="item.icon"
                                        size="sm"
                                      />
                                    </q-item-section>
                                    <q-item-section>{{
                                      item.label
                                    }}</q-item-section>
                                  </q-item>
                                </q-list>
                              </q-menu>
                            </q-btn>
                          </q-td>
                        </q-tr>
                      </template>
                    </d-table>
                  </div>
                </div>
              </q-card>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn type="submit" :label="`บันทึก`" color="public" />
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>
  <DialogAddPosition
    v-model:modalAdd="modalAdd"
    :emitSearch="emitSearch"
    :data="dataCopy"
    v-model:is-edit="isEdit"
    :get-data="searchInput"
  />
</template>

<style scoped>
.fixed-height {
  overflow-y: auto;
  height: 80vh;
}
</style>
