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

import config from "@/app.config";
import http from "@/plugins/http";
import genreport from "@/plugins/genreportxlsx";
import { checkPermission } from "@/utils/permissions";
import { updateCurrentPage } from "@/utils/function";
import { useOrganizational } from "@/modules/02_organization/store/organizational";
import { useCounterMixin } from "@/stores/mixin";

/** importType*/
import type { QTableProps } from "quasar";
import type {
  ListMenu,
  NewPagination,
  DataDocument,
} from "@/modules/02_organization/interface/index/Main";
import type { FilterMaster } from "@/modules/02_organization/interface/request/organizational";
import type { PosMaster2 } from "@/modules/02_organization/interface/response/organizational";
import type { DataPosition } from "@/modules/02_organization/interface/index/organizational";
import type { DataPositionCondition } from "@/modules/19_condition/interface/response/Main";

/** importComponents*/
import DialogFormPosotion from "@/modules/02_organization/components/DialogFormPosition.vue"; //อัตรากำลัง
import DialogPositionDetail from "@/modules/02_organization/components/DialogPositionDetail.vue"; //รายละเอียดตำแหน่ง
import DialogSort from "@/modules/02_organization/components/DialogSortPosition.vue"; // จัดลำดับ
import DialogMovePos from "@/modules/02_organization/components/DialogMovePos.vue"; // ย้ายตำแหน่ง
import DialogHistoryPos from "@/modules/02_organization/components/DialogHistoryPos.vue"; // ประวัติตำแหน่ง
import DialogSelectPerson from "@/modules/02_organization/components/DialogSelectPerson.vue"; // เลือกคนครอง
import DialogSuccession from "@/modules/02_organization/components/DialogSuccession.vue"; // สืบทอดตำแหน่ง
import DialogCondition from "@/modules/19_condition/components/DialogCondition.vue";
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";

const $q = useQuasar();
const store = useOrganizational();
const { showLoader, hideLoader, messageError, success, dialogRemove } =
  useCounterMixin();

/** prosp*/
const nodeTree = defineModel<any>("nodeTree", { required: true });
const orgLevel = defineModel<number>("orgLevel", { required: true });
const treeId = defineModel<string>("treeId", { required: true });
let reqMaster = defineModel<FilterMaster>("reqMaster", { required: true });
const totalPage = defineModel<number>("totalPage", { required: true });
const totalData = defineModel<number>("totalData", { required: true });
const posMaster = defineModel<PosMaster2[]>("posMaster", { required: true });
const orgRootId = defineModel<string>("orgRootId", { required: true });
const props = defineProps({
  filterKeyword: { type: Function, require: true, default: () => {} },
  fetchDataTable: {
    type: Function,
    require: true,
    default: () => {},
  },
  shortName: { type: String, required: true },
  fetchDataTree: {
    type: Function,
    require: true,
    default: () => {},
  },
  mainTree: {
    type: Object,
    require: true,
  },
});

const modalPerson = ref<boolean>(false); //ตัวแปร popup ข้อมูลทะเบียนประวัติ
const personalId = ref<string>(""); //ตัวแปร id ข้อมูลทะเบียนประวัติ
const modalSelectPerson = ref<boolean>(false); //เลือกคนครอล
const rowId = ref<string>(""); //id ที่ต้องการกระทำ
const actionType = ref<string>(""); //ประเภทการกระทำ
const orgShortName = ref<string>(""); //ชื่อย่อหน่วยงาน

const isPositionHolder = ref<boolean>(false);
const positionHolderInfo = reactive({
  posMaster: "",
  position: "",
  profileId: " ",
  isSit: false,
});

/** ListMenu Table*/
const listMenu = ref<ListMenu[]>([
  {
    label: "แก้ไข",
    icon: "edit",
    type: "EDIT",
    color: "edit",
  },
  {
    label: "คัดลอก",
    icon: "content_copy",
    type: "COPY",
    color: "blue-6",
  },
  {
    label: "ลบ",
    icon: "delete",
    type: "DEL",
    color: "red",
  },
  {
    label: "ย้ายตำแหน่ง",
    icon: "mdi-cursor-move",
    type: "MOVE",
    color: "blue-10",
  },
  {
    label: "สืบทอดตำแหน่ง",
    icon: "mdi-account-multiple-outline",
    type: "INHERIT",
    color: "deep-orange",
  },
  {
    label: "จัดการตำแหน่งติดเงื่อนไข",
    icon: "mdi-account-alert",
    type: "CONDITION",
    color: "deep-orange",
  },
  {
    label: "ประวัติตำแหน่ง",
    icon: "history",
    type: "HISTORY",
    color: "deep-purple",
  },
  {
    label: "ดูรายละเอียด",
    icon: "mdi-eye",
    type: "VIEW",
    color: "blue",
  },
]);

/**
 * Returns filtered menu items for a given row.
 */
function getMenuItems(row: any) {
  if (
    row.positionIsSelected != "ว่าง" &&
    store.typeOrganizational === "current"
  ) {
    return listMenu.value.filter(
      (item) =>
        item.type !== "DEL" &&
        item.type !== "CONDITION" &&
        item.type !== "INHERIT"
    );
  } else if (store.typeOrganizational === "current") {
    return listMenu.value.filter((item) => item.type !== "INHERIT");
  } else if (
    row.positionIsSelected != "ว่าง" &&
    store.typeOrganizational === "draft"
  ) {
    return listMenu.value.filter((item) => item.type !== "CONDITION");
  } else {
    return listMenu.value;
  }
}

const baseDocument = ref<DataDocument[]>([
  {
    name: "บัญชี 1",
    val: "report1",
  },
  {
    name: "บัญชี 2",
    val: "report2",
  },
  {
    name: "บัญชี 3",
    val: "report3",
  },
  {
    name: "รายงานสรุปจำนวนกรอบอัตรากำลังของข้าราชการกรุงเทพมหานครสามัญ",
    val: "report4",
  },
]);

const document = computed(() => {
  if (store.typeOrganizational === "draft") {
    return baseDocument.value;
  } else {
    return baseDocument.value.filter(
      (e: DataDocument) => e.val === "report2" || e.val === "report4"
    );
  }
});

/** columns*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posMasterNo",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    sortable: false,
    field: "posMasterNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionName",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    field: "positionName",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posTypeName",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: false,
    field: "posTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevelName",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: false,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionIsSelected",
    align: "left",
    label: "คนครอง",
    sortable: false,
    field: "positionIsSelected",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const columnsExpand = 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 dialogPosition = ref<boolean>(false); //ตำแหน่ง

/**
 * function  openPopup เพิ่มอัตรากำลัง
 * @param type ประเภท
 * @param id id
 */
function onClickPosition(
  type: string,
  id: string,
  data: PosMaster2 = {} as PosMaster2
) {
  actionType.value = type;
  orgShortName.value = type === "EDIT" ? data?.orgShortname : "";
  rowId.value = id ? id : "";
  dialogPosition.value = !dialogPosition.value;

  if (type === "EDIT") {
    isPositionHolder.value = data.positionIsSelected !== "ว่าง";
    positionHolderInfo.posMaster = data.id || "";
    positionHolderInfo.position =
      data.positions.find((e) => e.positionIsSelected === true)?.id || "";
    positionHolderInfo.profileId =
      store.typeOrganizational === "current"
        ? data.current_holderId || ""
        : data.next_holderId || "";
    positionHolderInfo.isSit = data.isSit || false;
  }
}

/**
 *  function เปิด popup เพิ่มแก้ไข อัตรากำลัง
 * @param type ประเภทการกระทำ
 * @param id  id ที่ต้องการกระทำ
 */
function onClickCopyPosition(
  type: string,
  id: string,
  data: PosMaster2 = {} as PosMaster2
) {
  orgShortName.value = data?.orgShortname;
  rowId.value = id ? id : "";
  actionType.value = type;
  dialogPosition.value = !dialogPosition.value;
}

const dialogDetail = ref<boolean>(false); //ดูรายละเอียดประวัติตำแหน่ง
const dataDetailPos = ref<DataPosition[]>([]); //รายละเอียดตำแหน่ง
/**
 * function ดูรายละเอียดประวัติตำแหน่ง
 * @param data ข้อมูล ประวัติตำแหน่ง
 */
function onClickViewDetail(data: DataPosition[]) {
  dialogDetail.value = !dialogDetail.value;
  dataDetailPos.value = data;
}

/**
 * function ยืนยันการลบตำแหน่ง
 * @param id id ตำแหน่ง
 */
function onClickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.orgPosMasterById(id))
      .then(async () => {
        reqMaster.value.page = await updateCurrentPage(
          reqMaster.value.page,
          totalPage.value,
          posMaster.value.length
        );
        await Promise.all([
          props.fetchDataTable?.(
            reqMaster.value.id,
            reqMaster.value.type,
            false
          ),
          getSummary(),
        ]);

        await success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

const modalSort = ref<boolean>(false);
/** fdunction จัดลำดับตำแหน่ง */
function onClickSort() {
  modalSort.value = true;
}

const modalDialogMMove = ref<boolean>(false);
const typeMove = ref<string>("");
/**
 * function openPopup  ย้ายตำแหน่ง
 * @param id ID ตำแหน่ง
 * @param type ประเภท [ALL,SINGER]
 */
function onClickMovePos(id: string, type: string) {
  modalDialogMMove.value = !modalDialogMMove.value;
  typeMove.value = type;
  rowId.value = id;
}

const modalDialogHistoryPos = ref<boolean>(false);
/**
 * function ดูประวัติตำแหน่ง
 * @param id ID ตำแหน่ง
 */
function onClickHistoryPos(id: string) {
  modalDialogHistoryPos.value = !modalDialogHistoryPos.value;
  rowId.value = id;
}

/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: NewPagination) {
  reqMaster.value.pageSize = newPagination.rowsPerPage;
  reqMaster.value.page = 1;
}

/**
 * function เปิด pop เลือกตนครอง
 * @param data  ข้อมูลตำแหน่งที่ต้องการเพิ่มคนครอง
 */
function openSelectPerson(data: DataPosition[]) {
  modalSelectPerson.value = true;
  dataDetailPos.value = data;
}

/**
 * function ยืนยันการลบข้อมูลคนครอง
 * @param id รายการที่ต้องการลบ
 */
function removePerson(id: string) {
  dialogRemove(
    $q,
    async () => {
      showLoader();
      await http
        .post(config.API.orgDeleteProfile(id))
        .then(async () => {
          await Promise.all([
            props.fetchDataTable?.(
              reqMaster.value.id,
              reqMaster.value.type,
              false
            ),
            getSummary(),
          ]);
          await success($q, "ลบข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการลบคนครอง",
    "ต้องการยืนยันการลบคนครองนี้ใช่หรือไม่?"
  );
}

const modalDialogSuccession = ref<boolean>(false);
/**
 * function openPopup สืบทอดตำแหน่ง
 */
function onClickInherit(id: string) {
  modalDialogSuccession.value = !modalDialogSuccession.value;
  rowId.value = id;
}

/**
 * ดึงข้อมูลสถิติจำนวนด้านบน
 */
function getSummary() {
  showLoader();
  http
    .post(config.API.orgSummary, {
      id: reqMaster.value.id, //*Id node
      type: reqMaster.value.type, //*ประเภทnode
      isNode: reqMaster.value.isAll, //*นับทั้ง node ไหม
    })
    .then(async (res: any) => {
      const data = await res.data.result;

      store.getSumPosition({
        totalPosition: data.totalPosition,
        totalPositionCurrentUse: data.totalPositionCurrentUse,
        totalPositionCurrentVacant: data.totalPositionCurrentVacant,
        totalPositionNextUse: data.totalPositionNextUse,
        totalPositionNextVacant: data.totalPositionNextVacant,
        totalRootPosition: data.totalPosition,
        totalRootPositionCurrentUse: data.totalPositionCurrentUse,
        totalRootPositionCurrentVacant: data.totalPositionCurrentVacant,
        totalRootPositionNextUse: data.totalPositionNextUse,
        totalRootPositionNextVacant: data.totalPositionNextVacant,
      });
    })
    .catch((err) => {
      // messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function DownloadReport
 */
async function onClickDownloadReport(val: string, name: string) {
  const newReport =
    store.typeOrganizational !== "draft" && val === "report2"
      ? "report2-history"
      : val;

  showLoader();
  await http
    .get(config.API.orgReport(newReport) + `/${orgRootId.value}`)
    .then(async (res) => {
      const data = res.data.result;
      if (data) {
        await genreport(data, name);
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const modalCondition = ref<boolean>(false);
const dataCondition = ref<DataPositionCondition>();

function onClickCodition(data: PosMaster2) {
  dataCondition.value = {
    conditionReason: data.conditionReason,
    id: data.id,
    isCondition: data.isCondition,
    orgShortname: data.orgShortname,
    posMasterNo: Number(data.posMasterNo),
    posMasterNoPrefix: data.posMasterNoPrefix,
    posMasterNoSuffix: data.posMasterNoSuffix,
    profilePosition: data.profilePosition,
    profilePoslevel: data.profilePoslevel,
    profilePostype: data.profilePostype,
    positions: [],
  };
  modalCondition.value = true;
}

async function fetchDataCondition() {
  await props.fetchDataTable?.(
    reqMaster.value.id,
    reqMaster.value.type,
    reqMaster.value.isAll
  );
}

const pagination = ref({
  page: reqMaster.value.page,
  rowsPerPage: reqMaster.value.pageSize,
});

watch(
  () => modalDialogMMove.value,
  () => {
    if (!modalDialogMMove.value) {
      pagination.value.page = 1;
      pagination.value.rowsPerPage = reqMaster.value.pageSize;

      if (posMaster.value.length === 0) {
        props.fetchDataTable?.(reqMaster.value.id, reqMaster.value.type, false);
      }
    }
  }
);
</script>

<template>
  <!-- TOOLBAR -->
  <div class="col-12">
    <q-toolbar style="padding: 0">
      <div
        v-if="
          (checkPermission($route)?.attrOwnership == 'OWNER' &&
            store.typeOrganizational === 'current') ||
          (store.typeOrganizational === 'draft' && !store.isLock)
        "
      >
        <q-btn
          flat
          round
          dense
          color="primary"
          icon="add"
          @click="onClickPosition('ADD', '')"
        >
          <q-tooltip>เพิ่มตำแหน่ง</q-tooltip>
        </q-btn>

        <q-btn
          flat
          round
          dense
          color="blue"
          icon="mdi-sort"
          @click="onClickSort()"
        >
          <q-tooltip>จัดลำดับ</q-tooltip>
        </q-btn>

        <q-btn
          flat
          round
          dense
          color="blue-10"
          icon="mdi-cursor-move"
          @click="onClickMovePos('', 'All')"
        >
          <q-tooltip>ย้ายตำแหน่ง</q-tooltip>
        </q-btn>
      </div>

      <!-- v-if="store.typeOrganizational === 'draft'" -->
      <q-btn flat round dense color="deep-purple" icon="save_alt">
        <q-menu>
          <q-list
            dense
            style="min-width: 100px"
            v-for="(item, index) in document"
            :key="index"
          >
            <q-item
              clickable
              v-close-popup
              @click.stop="onClickDownloadReport(item.val, item.name)"
            >
              <q-item-section>{{ item.name }}</q-item-section>
            </q-item>
          </q-list>
        </q-menu>
        <q-tooltip>ดาวน์โหลด</q-tooltip>
      </q-btn>

      <q-space />
      <div class="row q-gutter-md">
        <div>
          <q-checkbox
            keep-color
            v-model="reqMaster.isAll"
            label="แสดงตำแหน่งทั้งหมด"
            color="primary"
          >
            <q-tooltip
              >แสดงตำแหน่งทั้งหมดภายใต้หน่วยงาน/ส่วนราชการที่เลือก</q-tooltip
            >
          </q-checkbox>
        </div>
        <div>
          <q-input
            outlined
            dense
            v-model="reqMaster.keyword"
            label="ค้นหา"
            @keydown.enter.prevent="props.filterKeyword(reqMaster.keyword)"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
        </div>
      </div>
    </q-toolbar>
  </div>

  <!-- TABLE -->
  <div class="col-12">
    <d-table
      ref="table"
      :columns="columns"
      :rows="posMaster"
      :paging="true"
      row-key="id"
      flat
      bordered
      dense
      :rows-per-page-options="[10, 25, 50, 100]"
      @update:pagination="updatePagination"
      v-model:pagination="pagination"
    >
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th auto-width></q-th>
          <q-th auto-width></q-th>
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            <span class="text-weight-medium">{{ col.label }}</span>
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td>
            <q-btn
              v-if="
                (checkPermission($route)?.attrOwnership == 'OWNER' &&
                  store.typeOrganizational === 'current') ||
                (store.typeOrganizational === 'draft' && !store.isLock)
              "
              flat
              color="secondary"
              icon="mdi-dots-horizontal-circle-outline"
              round
              class="q-pa-none q-ml-xs"
            >
              <q-menu>
                <q-list dense style="min-width: 150px">
                  <!-- เลือกคนครอง -->
                  <q-item
                    v-if="props.row.positionIsSelected == 'ว่าง'"
                    clickable
                    v-close-popup
                    @click="openSelectPerson(props.row)"
                  >
                    <q-item-section>
                      <div class="row items-center">
                        <q-icon
                          color="secondary"
                          size="17px"
                          name="mdi-account"
                        />
                        <div class="q-pl-md">เลือกคนครอง</div>
                      </div>
                    </q-item-section>
                  </q-item>
                  <q-item
                    v-else-if="props.row.positionIsSelected != 'ว่าง'"
                    clickable
                    v-close-popup
                    @click="removePerson(props.row.id)"
                  >
                    <q-item-section>
                      <div class="row items-center">
                        <q-icon
                          color="red"
                          size="17px"
                          name="mdi-account-remove"
                        />
                        <div class="q-pl-md">ลบคนครอง</div>
                      </div>
                    </q-item-section>
                  </q-item>
                  <q-item
                    v-for="(item, index) in getMenuItems(props.row)"
                    :key="index"
                    clickable
                    v-close-popup
                    @click="
                      item.type === 'EDIT'
                        ? onClickPosition('EDIT', props.row.id, props.row)
                        : item.type === 'DEL'
                        ? onClickDelete(props.row.id)
                        : item.type === 'MOVE'
                        ? onClickMovePos(props.row.id, 'SINGER')
                        : item.type === 'HISTORY'
                        ? onClickHistoryPos(props.row.id)
                        : item.type === 'INHERIT'
                        ? onClickInherit(props.row.id)
                        : item.type === 'COPY'
                        ? onClickCopyPosition('COPY', props.row.id, props.row)
                        : item.type === 'CONDITION'
                        ? onClickCodition(props.row)
                        : item.type === 'VIEW'
                        ? onClickViewDetail(props.row)
                        : null
                    "
                  >
                    <q-item-section>
                      <div class="row items-center">
                        <q-icon
                          :color="item.color"
                          size="xs"
                          :name="item.icon"
                        />
                        <div class="q-pl-md">{{ item.label }}</div>
                      </div>
                    </q-item-section>
                  </q-item>
                  <!-- <q-item
                    clickable
                    v-close-popup
                    @click="onClickViewDetail(props.row)"
                  >
                    <q-item-section>
                      <div class="row items-center">
                        <q-icon color="blue" size="17px" name="mdi-eye" />
                        <div class="q-pl-md">ดูรายละเอียด</div>
                      </div>
                    </q-item-section>
                  </q-item> -->
                </q-list>
              </q-menu>
            </q-btn>

            <q-btn
              v-else-if="checkPermission($route)?.attrIsGet"
              flat
              dense
              color="deep-purple"
              icon="mdi-history"
              round
              @click.stop.prevent="onClickHistoryPos(props.row.id)"
            >
              <q-tooltip>ประวัติตำแหน่ง</q-tooltip>
            </q-btn>
          </q-td>
          <q-td>
            <q-btn
              flat
              size="14px"
              color="primary"
              round
              dense
              @click="props.expand = !props.expand"
              :icon="props.expand ? 'mdi-menu-down' : 'mdi-menu-right'"
            />
          </q-td>

          <q-td
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
            :class="props.row.isCondition ? 'text-red' : ''"
          >
            <div v-if="col.name == 'no'">
              {{
                (reqMaster.page - 1) * Number(reqMaster.pageSize) +
                props.rowIndex +
                1
              }}
            </div>
            <div v-else-if="col.name === 'posMasterNo'">
              {{
                props.row.isSit
                  ? col.value + " " + "(นั่งทับตำแหน่ง)"
                  : col.value
              }}

              <q-icon
                name="mdi-star"
                color="primary"
                v-if="props.row.isDirector"
              >
                <q-tooltip>ผู้อำนวยการ/หัวหน้า</q-tooltip>
              </q-icon>
            </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 == 'positionIsSelected'">
              {{
                props.row.positionIsSelected
                  ? props.row.positionIsSelected
                  : "-"
              }}
              {{
                props.row.isCondition && props.row.conditionReason
                  ? `(${props.row.conditionReason})`
                  : ""
              }}

              <q-btn
                v-if="props.row.positionIsSelected != 'ว่าง'"
                size="12px"
                dense
                flat
                icon="info"
                color="info"
                round
                @click="
                  (modalPerson = true),
                    (personalId =
                      store.typeOrganizational === 'draft'
                        ? props.row.next_holderId
                        : props.row.current_holderId)
                "
              >
                <q-tooltip>ดูข้อมูลในทะเบียนประวัติ</q-tooltip>
              </q-btn>
            </div>
            <div v-else>
              {{ col.value ? col.value : "-" }}
            </div>
          </q-td>
        </q-tr>

        <q-tr v-show="props.expand" :props="props">
          <q-td colspan="100%" class="bg-grey-1">
            <q-card flat bordered class="text-left q-ma-sm">
              <d-table
                flat
                :columns="columnsExpand"
                :rows="props.row.positions"
                table-class="text-grey-9"
                row-key="id"
                dense
                hide-bottom
                bordered
                separator="vertical"
                class="custom-header-table-expand"
              >
                <template v-slot:header="props">
                  <q-tr :props="props" class="bg-grey-2">
                    <q-th
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                    >
                      <span class="q-px-sm text-body2 text-black">{{
                        col.label
                      }}</span>
                    </q-th>
                  </q-tr>
                </template>
                <template v-slot:body="props">
                  <q-tr :props="props">
                    <q-td
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                    >
                      <div v-if="col.name == 'no'" class="text-body2">
                        {{ props.rowIndex + 1 }}
                      </div>
                      <div
                        v-else-if="col.name === 'posExecutiveName'"
                        class="text-body2"
                      >
                        {{ col.value ? col.value : "-" }}
                      </div>

                      <div
                        v-else-if="col.name === 'positionExecutiveField'"
                        class="text-body2"
                      >
                        {{ col.value ? col.value : "-" }}
                      </div>

                      <div
                        v-else-if="col.name === 'positionArea'"
                        class="text-body2"
                      >
                        {{ col.value ? col.value : "-" }}
                      </div>

                      <div v-else-if="col.name === 'positionName'">
                        {{ col.value ? col.value : "-" }}

                        <q-icon
                          v-if="props.row.positionIsSelected"
                          name="check"
                          color="primary"
                        />
                      </div>

                      <div v-else class="text-body2">
                        {{ col.value ? col.value : "-" }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>
              </d-table>
            </q-card>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:pagination="scope">
        ทั้งหมด {{ totalData.toLocaleString() }} รายการ
        <q-pagination
          v-model="reqMaster.page"
          active-color="primary"
          color="dark"
          :max="totalPage"
          :max-pages="5"
          size="sm"
          boundary-links
          direction-links
        ></q-pagination>
      </template>
    </d-table>
  </div>

  <!-- รายละเอียดตำแหน่ง -->
  <DialogPositionDetail
    v-model:position-detail="dialogDetail"
    :dataDetailPos="dataDetailPos"
  />

  <!-- อัตรากำลัง -->
  <DialogFormPosotion
    :modal="dialogPosition"
    :data-tree="mainTree"
    :shortName="shortName"
    :orgShortName="orgShortName"
    :close="onClickPosition"
    :orgLevel="orgLevel"
    :treeId="treeId"
    :actionType="actionType"
    :rowId="rowId"
    v-model:reqMaster="reqMaster"
    :fetchDataTable="props.fetchDataTable"
    :getSummary="getSummary"
    v-model:is-position-holder="isPositionHolder"
    :position-holder-info="positionHolderInfo"
  />

  <!-- จัดลำดับ -->
  <DialogSort
    v-model:sort-position="modalSort"
    :fetchDataTable="props.fetchDataTable"
    :total-data="totalData"
  />

  <!-- ย้ายตำแหน่ง -->
  <DialogMovePos
    v-model:modal="modalDialogMMove"
    v-model:nodeTree="nodeTree"
    v-model:columns="columns as QTableProps[]"
    v-model:rows="posMaster"
    v-model:totalPage="totalPage"
    v-model:reqMaster="reqMaster"
    :fetchDataTree="props.fetchDataTree"
    :type="typeMove"
    :rowId="rowId"
    :mainTree="props.mainTree ? props.mainTree : []"
    :fetchDataTable="props.fetchDataTable"
  />

  <!-- ประวัติตำแหน่ง -->
  <DialogHistoryPos v-model:modal="modalDialogHistoryPos" :rowId="rowId" />

  <!-- เลือกคนครอง -->
  <DialogSelectPerson
    v-model:modal="modalSelectPerson"
    :dataDetailPos="dataDetailPos"
    :fetchDataTable="props.fetchDataTable"
    :getSummary="getSummary"
  />

  <!-- สืบทอดตำแหน่ง -->
  <DialogSuccession v-model:modal="modalDialogSuccession" :rowId="rowId" />

  <!-- จัดการตำแหน่งติดเงื่อนไข -->
  <DialogCondition
    v-model:modal="modalCondition"
    :fetch-data="fetchDataCondition"
    :data-condition="dataCondition"
  />

  <!-- ข้อมูลทะเบียนประวัติ -->
  <PopupPersonal
    :modal="modalPerson"
    :id="personalId"
    @update:modal="(value:any)=>{modalPerson = value}"
  />
</template>

<style lang="scss" scoped>
.custom-header-table-expand {
  height: auto;
  .q-table tr:nth-child(odd) td {
    background: white;
  }
  .q-table tr:nth-child(even) td {
    background: white;
  }

  .q-table thead tr {
    background: white;
  }

  .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;
    padding: 0px;
  }
}
</style>
