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

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

/** importComponents*/
import TreeMain from "@/modules/02_organizationalNew/components/TreeMain.vue";
import TreeTable from "@/modules/02_organizationalNew/components/TreeTable.vue";

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

/** 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 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(id: string) {
  isLoadTree.value = false;
  showLoader();
  await http
    .get(config.API.orgByid(id.toString()))
    .then((res) => {
      const data = res.data.result;
      nodeTree.value = data;
      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;
  }

  await http
    .post(config.API.orgPosMasterList, 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;
      }, 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);
}

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
}

/**lifecycle Hook*/
onMounted(async () => {
  const id =
    store.typeOrganizational === "current"
      ? store.activeId
      : store.typeOrganizational === "draft"
      ? store.draftId
      : historyId.value;
  id && (await fetchDataTree(id));
});

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

/** callblck function ทำการ fetch ข้อมูล Tree เมื่อมีการเปลี่ยนโครงสร้าง*/
watch(
  () => store.typeOrganizational,
  () => {
    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());
  }
);
</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:nodeTree="nodeTree"
            v-model:shortName="shortName"
            v-model:nodeId="nodeId"
            :fetchDataTree="fetchDataTree"
            :fetchDataTable="fetchDataTable"
          />

          <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">
          <div
            class="row col-12 justify-center"
            v-if="isLoad"
            style="height: 550px"
          >
            <div class="col-2">
              <q-spinner color="primary" size="3em" />
            </div>
          </div>

          <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:nodeTree="nodeTree"
                v-model:orgLevel="orgLevel"
                v-model:treeId="nodeId"
                v-model:reqMaster="reqMaster"
                v-model:totalPage="totalPage"
                v-model:posMaster="posMaster"
                :shortName="shortName"
                :mainTree="mainTree"
                :fetchDataTable="fetchDataTable"
                :filterKeyword="filterKeyword"
                :fetchDataTree="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>
