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

import { useRoute } from "vue-router";
import { useStructureTree } from "@/stores/structureTree";
import { usePositionEmp } from "@/modules/16_positionEmployee/store/organizational";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

/** importType*/
import type {
  OrgTree,
  PosMaster,
  Position,
  PosMaster2,
} from "@/modules/16_positionEmployee/interface/response/organizational";
import type { FilterMaster } from "@/modules/16_positionEmployee/interface/request/organizational";

/** importComponents*/
import TreeMain from "@/modules/16_positionEmployee/components/TreeMain.vue";
import TreeTable from "@/modules/16_positionEmployee/components/TreeTable.vue";
import LoadView from "@/components/LoadView.vue";

/** use*/
const store = usePositionEmp();
const $q = useQuasar();
const { messageError } = useCounterMixin();
const route = useRoute();
const { fetchStructureTree } = useStructureTree();
const storeStructureTree = useStructureTree();

const nodeTree = ref<OrgTree[]>([]); // ข้อมูล Tree
const nodeId = ref<string>(""); // id ของ Tree
const orgLevel = ref<number>(0); // levelTree
const isLoad = ref<boolean>(false); // loadTable
const isLoadTree = ref<boolean>(false); // loadTable
const mainTree = ref<OrgTree>();
const selected = ref<string>("");

const reqMaster = reactive<FilterMaster>({
  id: "",
  type: 0,
  isAll: false,
  page: 1,
  pageSize: 10,
  keyword: "",
  revisionId: "",
});
const totalPage = ref<number>(1); //จำนวนหน้า
const action1 = ref<boolean>(false);
const posMaster = ref<PosMaster2[]>([]); //รายการตำแหน่ง
const shortName = ref<string>(""); //ชื่อย่อย

/**
 * function fetch ข้อมูลของ Tree
 * @param id id โครงสร้าง
 */
async function fetchDataTree() {
  isLoadTree.value = false;
  const dataTree = await fetchStructureTree(route.meta.Key as string, true);
  store.activeId = storeStructureTree.activeId;
  if (dataTree) {
    nodeTree.value = dataTree;
    selected.value = "";
    nodeId.value = "";
    store.treeId = "";
  }
}

/**
 * function fetch ข้อรายการตำแหน่ง
 * @param id  idTree
 * @param level  levelTree
 */
function fetchDataTable(id: string, level: number, action: boolean) {
  searchAndReplaceOrgName(nodeTree.value, id);
  orgLevel.value = level;
  reqMaster.id = id;
  reqMaster.type = level;
  action1.value = action;
  if (action) {
    setTimeout(() => {
      action1.value = false;
    }, 1000);
    reqMaster.isAll = false;
    reqMaster.page = 1;
    reqMaster.pageSize = 10;
    reqMaster.keyword = "";
    reqMaster.revisionId = store.activeId;
  }

  if (action === true) {
    isLoad.value = true;
  }
  http
    .post(config.API.orgPosMasterListEmp, reqMaster)
    .then(async (res) => {
      posMaster.value = [];
      const dataMain: PosMaster[] = [];
      totalPage.value = Math.ceil(res.data.result.total / reqMaster.pageSize);
      res.data.result.data.forEach((e: PosMaster) => {
        const p = e.positions;
        if (p.length !== 0) {
          const a = p.find((el: Position) => el.positionIsSelected === true);
          const { id, ...rest } = a ? a : p[0];
          const test = { ...e, ...rest };
          dataMain.push(test);
        }
      });
      posMaster.value = await store.fetchPosMaster(dataMain);
    })
    .catch((err) => {
      messageError($q, err);
      posMaster.value = [];
    })
    .finally(() => {
      setTimeout(() => {
        isLoad.value = false;
      }, 500);
    });
}

/**
 * ดึงข้อมูลสถิติจำนวนด้านบน
 */
function getSummary() {
  http
    .post(config.API.orgSummaryEmp, {
      id: reqMaster.id, //*Id node
      type: reqMaster.type, //*ประเภทnode
      isNode: reqMaster.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,
      });
    });
}

/**
 * funcion ค้นหาข้อมูลใน Table
 */
function filterKeyword() {
  reqMaster.page = 1;
  action1.value === false &&
    fetchDataTable(reqMaster.id, reqMaster.type, false);
}

/**
 * function ค้นหาชือ
 * @param data ข้อมูล Tree
 * @param targetId tree
 */
function searchAndReplaceOrgName(data: any, targetId: string) {
  for (const child of data) {
    if (child.orgTreeId === targetId) {
      mainTree.value = child;

      return true; // Found the targetId in this level
    }
    if (child.children && searchAndReplaceOrgName(child.children, targetId)) {
      return true; // Found the targetId in the nested children
    }
  }
  return false; // Not found in this branch
}

/**
 * callblck function ทำการ fetch ข้อมูล Table เมื่อมีการเปลี่ยนหน้า
 */
watch([() => reqMaster.page, () => reqMaster.pageSize], () => {
  action1.value === false &&
    fetchDataTable(reqMaster.id, reqMaster.type, false);
});

/**
 *  callblck function ทำการ fetch ข้อมูล Table เมื่อแสดงตำแหน่งทั้งหมด
 */
watch(
  () => reqMaster.isAll,
  () => {
    getSummary();
    if (reqMaster.page !== 1) {
      reqMaster.page = 1;
    } else {
      fetchDataTable(reqMaster.id, reqMaster.type, false);
    }
  }
);

/**
 * lifecycle Hook
 */
onMounted(() => {
  fetchDataTree();
});
</script>

<template>
  <div class="row items-center">
    <div class="toptitle text-dark row items-center q-py-xs">
      อัตรากำลังลูกจ้างประจำ ฯ
    </div>
  </div>

  <q-card flat bordered>
    <q-card class="my-card">
      <q-card-section style="padding: 0px">
        <div class="col-12">
          <q-card bordered class="col-12 row caedNone">
            <div class="col-xs-12 col-sm-3 row">
              <div class="col-12 row no-wrap bg-grey-1">
                <TreeMain
                  v-model:node-tree="nodeTree"
                  v-model:short-name="shortName"
                  v-model:node-id="nodeId"
                  :fetch-data-table="fetchDataTable"
                  :fetch-data-tree="fetchDataTree"
                />

                <div class="col-12 row">
                  <q-separator :vertical="!$q.screen.lt.md" />
                </div>
              </div>
            </div>

            <div class="col-xs-12 col-sm-9 q-pa-md row">
              <div class="col-12 row">
                <LoadView v-if="isLoad" />

                <div v-else class="col-12 row">
                  <div class="col-12" v-if="nodeId !== ''">
                    <!-- summary -->
                    <q-card
                      bordered
                      v-if="nodeId"
                      class="row col-12 justify-between list-summary q-gutter-xs bg-grey-1 q-pb-xs q-pr-xs"
                    >
                      <div class="row col q-pa-sm item">
                        <div class="ellipsis">ตำแหน่งทั้งหมด</div>
                        <q-space />
                        <q-badge
                          color="secondary"
                          :label="
                            reqMaster.isAll
                              ? store.sumPosition.total
                              : store.sumPosition.totalRoot
                          "
                        />
                      </div>
                      <div class="row col q-pa-sm item">
                        <div class="ellipsis">ตำแหน่งที่มีคนครอง</div>
                        <q-space />
                        <q-badge
                          color="primary"
                          :label="
                            reqMaster.isAll
                              ? store.sumPosition.use
                              : store.sumPosition.useRoot
                          "
                        />
                      </div>
                      <div class="row col q-pa-sm item">
                        <div class="ellipsis">ตำแหน่งว่าง</div>
                        <q-space />
                        <q-badge
                          color="red"
                          :label="
                            reqMaster.isAll
                              ? store.sumPosition.vacant
                              : store.sumPosition.vacantRoot
                          "
                        />
                      </div>
                    </q-card>

                    <TreeTable
                      v-if="nodeId !== ''"
                      v-model:node-tree="nodeTree"
                      v-model:org-level="orgLevel"
                      v-model:tree-id="nodeId"
                      v-model:pos-master="posMaster"
                      v-model:req-master="reqMaster"
                      v-model:total-page="totalPage"
                      :short-name="shortName"
                      :main-tree="mainTree"
                      :fetch-data-table="fetchDataTable"
                      :fetch-data-tree="fetchDataTree"
                      :filter-keyword="filterKeyword"
                    />
                  </div>
                  <div class="row col-12 items-center" v-else>
                    <q-banner class="q-pa-lg col-12 text-center">
                      <q-icon
                        name="mdi-hand-pointing-left"
                        size="lg"
                        color="primary"
                      />
                      <p class="text-grey-9 q-pt-sm">กรุณาเลือกโครงสร้าง</p>
                    </q-banner>
                  </div>
                </div>
              </div>
            </div>
          </q-card>
        </div>

        <!-- <TreeView /> -->
      </q-card-section>
    </q-card>
  </q-card>
</template>

<style scoped></style>
