<script setup lang="ts">
import { ref } from "vue";
import { useQuasar } from "quasar";
import config from "@/app.config";
import http from "@/plugins/http";
import genreport from "@/plugins/genreportxlsx";

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

/** importComponents*/
import DialogFormPosotion from "@/modules/02_organizationalNew/components/DialogFormPosition.vue";
import DialogPositionDetail from "@/modules/02_organizationalNew/components/DialogPositionDetail.vue";
import DialogSort from "@/modules/02_organizationalNew/components/DialogSortPosition.vue";
import DialogMovePos from "@/modules/02_organizationalNew/components/DialogMovePos.vue";
import DialogHistoryPos from "@/modules/02_organizationalNew/components/DialogHistoryPos.vue";
import DialogSelectPerson from "@/modules/02_organizationalNew/components/DialogSelectPerson.vue";
import DialogSuccession from "@/modules/02_organizationalNew/components/DialogSuccession.vue";

/** importStore*/
import { useOrganizational } from "@/modules/02_organizationalNew/store/organizational";
import { useCounterMixin } from "@/stores/mixin";

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 });
const reqMaster = defineModel<FilterMaster>("reqMaster", { required: true });
const totalPage = defineModel<number>("totalPage", { required: true });
const posMaster = defineModel<PosMaster2[]>("posMaster", { required: true });
const props = defineProps({
  filterKeyword: { type: Function, require: true, default: () => {} },
  fetchDataTable: {
    type: Function,
    require: true,
    default: () => {},
  },
  fetchDataTree: {
    type: Function,
    require: true,
    default: () => {},
  },
  mainTree: {
    type: Object,
    require: true,
  },
});

const modalSelectPerson = ref<boolean>(false);
const rowId = ref<string>("");
const actionType = ref<string>("");
/** ListMenu Table*/
const listMenu = ref<ListMenu[]>([
  {
    label: "แก้ไข",
    icon: "edit",
    type: "EDIT",
    color: "primary",
  },
  {
    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: "history",
    type: "HISTORY",
    color: "deep-purple",
  },
]);
const document = ref<any>([
  {
    name: "บัญชี 1",
    val: "report1",
  },
  {
    name: "บัญชี 2",
    val: "report2",
  },
  {
    name: "บัญชี 3",
    val: "report3",
  },
]);

/** 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: true,
    field: "posMasterNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionName",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    field: "positionName",
    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: "positionIsSelected",
    align: "left",
    label: "คนครอง",
    sortable: true,
    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) {
  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(() => {
        success($q, "ลบข้อมูลสำเร็จ");
        props.fetchDataTable?.(reqMaster.value.id, reqMaster.value.type, false);
        getSummary();
      })
      .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 openPopup เลือกตนครอง*/
function openSelectPerson(data: DataPosition[]) {
  modalSelectPerson.value = true;
  dataDetailPos.value = data;
}

/** ลบคนครอง */
function removePerson(id: string) {
  dialogRemove(
    $q,
    async () => {
      showLoader();
      await http
        .post(config.API.orgDeleteProfile(id))
        .then(() => {
          success($q, "ลบข้อมูลสำเร็จ");
          props.fetchDataTable?.(
            reqMaster.value.id,
            reqMaster.value.type,
            false
          );
          getSummary();
        })
        .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) {
  showLoader();
  await http
    .get(config.API.orgReport(val))
    .then((res) => {
      const data = res.data.result;
      if (data) {
        genreport(data, name);
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}
</script>

<template>
  <!-- TOOLBAR -->
  <div class="col-12">
    <q-toolbar style="padding: 0">
      <div v-if="store.typeOrganizational === 'draft'">
        <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>

      <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" 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"
    >
      <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-th auto-width></q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props" class="cursor-pointer">
          <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">
            <div v-if="col.name == 'no'">
              {{
                (reqMaster.page - 1) * Number(reqMaster.pageSize) +
                props.rowIndex +
                1
              }}
            </div>

            <div v-else>
              {{ col.value }}
            </div>
          </q-td>
          <q-td>
            <q-btn
              flat
              dense
              icon="mdi-dots-vertical"
              class="q-pa-none q-ml-xs"
              color="grey-13"
              size="12px"
            >
              <q-menu>
                <q-list dense style="min-width: 150px">
                  <!-- เลือกคนครอง -->
                  <q-item
                    v-if="
                      props.row.positionIsSelected == 'ว่าง' &&
                      store.typeOrganizational === 'draft'
                    "
                    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 != 'ว่าง' &&
                      store.typeOrganizational === 'draft'
                    "
                    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 store.typeOrganizational === 'draft'
                      ? listMenu
                      : listMenu.filter((e) => e.type === 'HISTORY')"
                    :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)
                        : null
                    "
                  >
                    <q-item-section>
                      <div class="row items-center">
                        <q-icon
                          :color="item.color"
                          size="17px"
                          :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="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-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">
              <q-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" class="cursor-pointer">
                    <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 class="text-body2">
                        {{ col.value }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>
              </q-table>
            </q-card>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:pagination="scope">
        <q-pagination
          v-model="reqMaster.page"
          active-color="primary"
          color="dark"
          :max="totalPage"
          size="sm"
          boundary-links
          direction-links
        ></q-pagination>
      </template>
    </d-table>
  </div>

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

  <!-- อัตรากำลัง -->
  <DialogFormPosotion
    :modal="dialogPosition"
    :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"
  />

  <!-- ย้ายตำแหน่ง -->
  <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 : []"
  />

  <!-- ประวัติตำแหน่ง -->
  <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" />
</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;
  }
}
.q-table th:last-child,
.q-table td:last-child {
  padding: 0px !important;
}
</style>
