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

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

/**
 * importType
 */
import type { QTableProps } from "quasar";
import type {
  ListMenu,
  NewPagination,
  DataDocumentList,
} from "@/modules/16_positionEmployee/interface/index/Main";
import type { FilterMaster } from "@/modules/16_positionEmployee/interface/request/organizational";
import type { PosMaster2 } from "@/modules/16_positionEmployee/interface/response/organizational";
import type { DataPosition } from "@/modules/16_positionEmployee/interface/index/organizational";

/**
 * importComponents
 */
import DialogFormPosotion from "@/modules/16_positionEmployee/components/DialogFormPosition.vue";
import DialogPositionDetail from "@/modules/16_positionEmployee/components/DialogPositionDetail.vue";
import DialogSort from "@/modules/16_positionEmployee/components/DialogSortPosition.vue";
import DialogMovePos from "@/modules/16_positionEmployee/components/DialogMovePos.vue";
import DialogHistoryPos from "@/modules/16_positionEmployee/components/DialogHistoryPos.vue";
import DialogSelectPerson from "@/modules/16_positionEmployee/components/DialogSelectPerson.vue";
import DialogSuccession from "@/modules/16_positionEmployee/components/DialogSuccession.vue";
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";

/**
 * ues
 */
const $q = useQuasar();
const store = usePositionEmp();
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 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,
  },
});

/**
 * modal popup
 */
const modalPerson = ref<boolean>(false); //ตัวแปร popup ข้อมูลทะเบียนประวัติ
const personalId = ref<string>(""); //ตัวแปร id ข้อมูลทะเบียนประวัติ
const dialogDetail = ref<boolean>(false); // รายละเอียดตำแหน่ง
const modalSelectPerson = ref<boolean>(false); // เลือกคนครอง
const dialogPosition = ref<boolean>(false); // อัตรากำลัง
const modalSort = ref<boolean>(false); // จัดลำดับ
const modalDialogMMove = ref<boolean>(false); // ย้ายตำแหน่ง
const modalDialogSuccession = ref<boolean>(false); // สืบทอดตำแหน่ง
const modalDialogHistoryPos = ref<boolean>(false); // ประวัติตำแหน่ง

const rowId = ref<string>("");
const actionType = ref<string>("");
/** ListMenu Table*/
const listMenu = ref<ListMenu[]>([
  {
    label: "ย้ายตำแหน่ง",
    icon: "mdi-cursor-move",
    type: "MOVE",
    color: "blue-10",
  },
  {
    label: "แก้ไข",
    icon: "edit",
    type: "EDIT",
    color: "edit",
  },
  {
    label: "คัดลอก",
    icon: "content_copy",
    type: "COPY",
    color: "blue-6",
  },
  {
    label: "ลบ",
    icon: "delete",
    type: "DEL",
    color: "red",
  },
]);
const documentItems = ref<DataDocumentList[]>([
  {
    name: "รายงานสรุปจำนวนกรอบอัตรากำลังของลูกจ้างประจำกรุงเทพมหานคร",
    val: "report4-employee",
  },
]);

/** 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",
  },
]);

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

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.orgPosMasterByIdEmp(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(),
        ]);
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

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

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;
}

/**
 * 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 openPopup เลือกตนครอง
 */
function openSelectPerson(data: DataPosition[]) {
  modalSelectPerson.value = true;
  dataDetailPos.value = data;
}

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

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

/**
 * ดึงข้อมูลสถิติจำนวนด้านบน
 */
function getSummary() {
  showLoader();
  http
    .post(config.API.orgSummaryEmp, {
      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) {
  // รอ API
  showLoader();
  await http
    .get(config.API.orgReport(val) + `/${treeId.value}`)
    .then(async (res) => {
      const data = res.data.result;
      if (data) {
        await genreport(data, name);
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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>
        <q-btn
          v-if="checkPermission($route)?.attrIsCreate"
          flat
          round
          dense
          color="primary"
          icon="add"
          @click="onClickPosition('ADD', '')"
        >
          <q-tooltip>เพิ่มตำแหน่ง</q-tooltip>
        </q-btn>

        <q-btn
          v-if="checkPermission($route)?.attrIsUpdate"
          flat
          round
          dense
          color="blue"
          icon="mdi-sort"
          @click="onClickSort()"
        >
          <q-tooltip>จัดลำดับ</q-tooltip>
        </q-btn>

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

        <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 documentItems"
              :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>
      </div>

      <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" color="grey-5" />
            </template>
          </q-input>
        </div>
      </div>
    </q-toolbar>
  </div>

  <!-- TABLE -->
  <div class="col-12">
    <d-table
      ref="table"
      :columns="columns"
      :rows="posMaster"
      row-key="id"
      flat
      bordered
      :paging="true"
      dense
      :rows-per-page-options="[10, 25, 50, 100]"
      @update:pagination="updatePagination"
      class="tableTb"
      v-model:pagination="pagination"
    >
      <template v-slot:header="props">
        <q-tr :props="props">
          <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)?.attrIsUpdate ||
                checkPermission($route)?.attrIsDelete
              "
              class="q-pa-none q-ml-xs"
              flat
              dense
              color="secondary"
              icon="mdi-dots-horizontal-circle-outline"
              round
            >
              <q-menu>
                <q-list dense style="min-width: 150px">
                  <!-- เลือกคนครอง -->
                  <q-item
                    v-if="
                      props.row.positionIsSelected == 'ว่าง' &&
                      checkPermission($route)?.attrIsUpdate
                    "
                    clickable
                    v-close-popup
                    @click="openSelectPerson(props.row)"
                  >
                    <q-item-section>
                      <div class="row items-center">
                        <q-icon
                          color="secondary"
                          size="xs"
                          name="mdi-account"
                        />
                        <div class="q-pl-md">เลือกคนครอง</div>
                      </div>
                    </q-item-section>
                  </q-item>
                  <q-item
                    v-else-if="
                      props.row.positionIsSelected != 'ว่าง' &&
                      checkPermission($route)?.attrIsUpdate
                    "
                    clickable
                    v-close-popup
                    @click="removePerson(props.row.id)"
                  >
                    <q-item-section>
                      <div class="row items-center">
                        <q-icon
                          color="red"
                          size="xs"
                          name="mdi-account-remove"
                        />
                        <div class="q-pl-md">ลบคนครอง</div>
                      </div>
                    </q-item-section>
                  </q-item>
                  <q-item
                    v-for="(item, index) in checkPermission($route)
                      ?.attrIsUpdate && !checkPermission($route)?.attrIsDelete
                      ? listMenu.filter((e) => e.type !== 'DEL')
                      : checkPermission($route)?.attrIsDelete &&
                        !checkPermission($route)?.attrIsUpdate
                      ? listMenu.filter((e) => e.type === 'DEL')
                      : listMenu"
                    :key="index"
                    clickable
                    v-close-popup
                    @click="
                      item.type === 'EDIT'
                        ? onClickPosition('EDIT', props.row.id)
                        : 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'
                        ? onClickPosition('COPY', props.row.id)
                        : 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
                    v-if="props.row.positionIsSelected != 'ว่าง'"
                    clickable
                    v-close-popup
                    @click="onClickViewDetail(props.row)"
                  >
                    <q-item-section>
                      <div class="row items-center">
                        <q-icon color="info" size="xs" name="mdi-eye" />
                        <div class="q-pl-md">ดูรายละเอียด</div>
                      </div>
                    </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">
            <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
              }}
            </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
                  : "-"
              }}
              <q-btn
                v-if="
                  props.row.positionIsSelected !== 'ว่าง' &&
                  props.row.positionIsSelected
                "
                size="12px"
                dense
                flat
                icon="info"
                color="info"
                round
                @click="
                  (modalPerson = true),
                    (personalId = props.row.current_holderId)
                "
              >
                <q-tooltip>ดูข้อมูลในทะเบียนประวัติ</q-tooltip>
              </q-btn>
            </div>
            <div v-else>
              {{ col.value ? col.value : "-" }}
            </div>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:pagination="scope">
        ทั้งหมด {{ totalData }} รายการ
        <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"
    :shortName="shortName"
    :close="onClickPosition"
    :orgLevel="orgLevel"
    :treeId="treeId"
    :actionType="actionType"
    :rowId="rowId"
    v-model:reqMaster="reqMaster"
    :fetchDataTable="props.fetchDataTable"
    :getSummary="getSummary"
  />

  <!-- จัดลำดับ -->
  <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" />

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