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

import http from "@/plugins/http";
import config from "@/app.config";
import { useOrganizational } from "@/modules/02_organization/store/organizational";
import { useCounterMixin } from "@/stores/mixin";

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

/** importComponents*/
import TreeMain from "@/modules/02_organization/components/TreeMain.vue";
import TreeTable from "@/modules/02_organization/components/TableMain.vue";
import LoadView from "@/components/LoadView.vue";

/** use*/
const store = useOrganizational();
const $q = useQuasar();
const { showLoader, hideLoader, messageError } = useCounterMixin();

/** props*/
const historyId = defineModel<string>("historyId", { required: true }); // id ประวัติโครงสร้าง
const count = defineModel<number>("count", { required: true });

const nodeTree = ref<OrgTree[]>(); // ข้อมูล Tree
const nodeId = ref<string>(""); // id ของ Tree
const orgRootId = ref<string>("");
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 totalData = 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(id: string) {
  isLoadTree.value = false;
  showLoader();
  await http
    .get(config.API.orgByid(id))
    .then((res) => {
      const data = res.data.result;
      nodeTree.value = data.data;
      store.remark = data.remark;
      selected.value = "";
      nodeId.value = "";
      store.treeId = "";
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function fetch ข้อรายการตำแหน่ง
 * @param id  idTree
 * @param level  levelTree
 */
async 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.typeOrganizational == "draft"
        ? store.draftId
        : store.typeOrganizational == "current"
        ? store.activeId
        : store.historyId;
    isLoad.value = true;
  }
  posMaster.value = [];

  await http
    .post(config.API.orgPosMasterList, {
      ...reqMaster,
      keyword: reqMaster.keyword.trim(),
    })
    .then(async (res) => {
      const dataMain: PosMaster[] = [];
      totalPage.value = Math.ceil(res.data.result.total / reqMaster.pageSize);
      totalData.value = res.data.result.total;
      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 = store.fetchPosMaster(dataMain);
    })
    .catch((err) => {
      messageError($q, err);
      posMaster.value = [];
    })
    .finally(() => {
      setTimeout(() => {
        isLoad.value = false;
      }, 1000);
    });
}

/**  ดึงข้อมูลสถิติจำนวนด้านบน*/
function getSummary() {
  http
    .post(config.API.orgSummary, {
      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*/
async function filterKeyword() {
  reqMaster.page = 1;
  action1.value === false &&
    fetchDataTable(reqMaster.id, reqMaster.type, false);
}

/**
 * ค้นหาโครงสร้างในข้อมูลแบบลำดับชั้นเพื่อหาที่ตรงกับ orgTreeId
 * @param data ข้อมูลโครงสร้าง
 * @param targetId id ของโครงสร้างที่ต้องการค้นหา
 */
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
}

/** callback function ทำงาน ทำการ fetch ข้อมูล Tree เมื่อมีการเลือกประวัติโครงสร้าง*/
watch(
  () => count.value,
  () => {
    fetchDataTree(historyId.value);
  }
);

/** callblck function ทำการ fetch ข้อมูล Tree เมื่อมีการเปลี่ยนโครงสร้าง*/
watch(
  () => store.typeOrganizational,
  () => {
    nodeTree.value = [];
    const id =
      store.typeOrganizational === "current" ? store.activeId : store.draftId;
    id && store.typeOrganizational !== "old" && fetchDataTree(id);
    nodeId.value = "";
    store.treeId = "";
  }
);

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

watch(
  () => store.draftId,
  () => {
    store.draftId && fetchDataTree(store.draftId?.toString());
  }
);

/**
 * lifecycle Hook ทำเมือ่ Components ถูกเรียกใช้งาน
 *
 * ุ และดึงช้อมูลโครงสร้างตาม ID ของประเภทโครงสร้าง ปัจจุบัน,แบบร่าง
 */
onMounted(async () => {
  const id =
    store.typeOrganizational === "current"
      ? store.activeId
      : store.typeOrganizational === "draft"
      ? store.draftId
      : historyId.value;
  id && (await fetchDataTree(id));
});
</script>

<template>
  <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"
            v-model:org-root-id="orgRootId"
            :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"
                v-model:org-root-id="orgRootId"
                v-model:total-data="totalData"
                :short-name="shortName"
                :main-tree="mainTree"
                :fetch-data-table="fetchDataTable"
                :filter-keyword="filterKeyword"
                :fetch-data-tree="fetchDataTree"
              />
            </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>
</template>

<style scoped>
.list-summary .item {
  border: 1px solid rgb(231, 231, 231);
  border-radius: 4px;
  background-color: white;
}
</style>
