<script setup lang="ts">
import { ref, watch } 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/16_positionEmployee/interface/index/Main";
import type { FilterMaster } from "@/modules/16_positionEmployee/interface/request/organizational";
import type {
  PosMaster2,
  OrgTree,
} 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";

/** importStore*/
import { usePositionEmp } from "@/modules/16_positionEmployee/store/organizational";
import { useCounterMixin } from "@/stores/mixin";

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 });
const reqMaster = defineModel<FilterMaster>("reqMaster", { required: true });
const totalPage = defineModel<number>("totalPage", { required: true });
const posMaster = defineModel<PosMaster2[]>("posMaster", { required: true });
// const shortName = defineModel<string>("shortName", { 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 modalSelectPerson = ref<boolean>(false);
const rowId = ref<string>("");
const actionType = ref<string>("");
/** ListMenu Table*/
const listMenu = ref<ListMenu[]>([
  {
    label: "แก้ไข",
    icon: "edit",
    type: "EDIT",
    color: "edit",
  },
  {
    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: 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 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.orgPosMasterByIdEmp(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.orgDeleteProfileEmp(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.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) {
  showLoader();
  await http
    .get(config.API.orgReportEmp(val))
    .then((res) => {
      const data = res.data.result;
      if (data) {
        genreport(data, name);
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}

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;
    }
  }
);
</script>

<template>
  <!-- TOOLBAR -->
  <div class="col-12">
    <q-toolbar style="padding: 0">
      <div>
        <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
        v-if="store.typeOrganizational === 'draft'"
        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"
      v-model:pagination="pagination"
    >
      <template v-slot:header="props">
        <q-tr :props="props">
          <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 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>
              {{ col.value ? 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 == 'ว่าง'"
                    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 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)
                        : 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>
      </template>
      <template v-slot:pagination="scope">
        <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"
  />

  <!-- ย้ายตำแหน่ง -->
  <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;
  }
}
</style>
