<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 TreeView from "@/modules/02_organizationalNew/components/mainTree.vue";
import TableView from "@/modules/02_organizationalNew/components/tableTree.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 selected = ref<string>("");

const reqMaster = reactive<FilterMaster>({
  id: "",
  type: 0,
  isAll: false,
  page: 1,
  pageSize: 10,
  keyword: "",
});
const totalPage = ref<number>(1);
const action1 = ref<boolean>(false);
const posMaster = ref<PosMaster2[]>([]);

/**
 * function fetch ข้อมูลของ Tree
 * @param id id โครงสร้าง
 */
async function fetchDataTree(id: string) {
  showLoader();
  await http
    .get(config.API.orgByid(id.toString()))
    .then((res) => {
      const data = res.data.result;
      nodeTree.value = data;
      selected.value = "";
      nodeId.value = "";
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function fetch ข้อรายการตำแหน่ง
 * @param id  idTree
 * @param level  levelTree
 */
async function fetchDataTable(id: string, level: number, action: boolean) {
  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 = "";
  }

  if (action === true) {
    isLoad.value = true;
  }
  await http
    .post(config.API.orgPosMasterList, reqMaster)
    .then((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 = store.fetchPosMaster(dataMain);
    })
    .catch((err) => {
      messageError($q, err);
      posMaster.value = [];
    })
    .finally(() => {
      setTimeout(() => {
        isLoad.value = false;
      }, 500);
    });
}

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

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

/** 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,
  () => {
    if (reqMaster.page !== 1) {
      reqMaster.page = 1;
    } else {
      fetchDataTable(reqMaster.id, reqMaster.type, false);
    }
  }
);
</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">
          <TreeView
            v-model:nodeTree="nodeTree"
            v-model:nodeId="nodeId"
            v-model:selected="selected"
            :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>

              <TableView
                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"
                :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>
