<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

/** importType*/
import type { OrgTree } from "@/modules/02_organizationalNew/interface/response/organizational";

import TreeView from "@/modules/02_organizationalNew/components/mainTree.vue";
import TableView from "@/modules/02_organizationalNew/components/tableTree.vue";

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

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

const showData = ref<boolean>(false);
const nodeTree = ref<OrgTree[]>();
const historyId = defineModel<string>("historyId", { required: true });
const count = defineModel<number>("count", { required: true });

// defineProps<{ dataActive: DataActive }>();

async function fetchDataTree(id: string) {
  showLoader();
  // const id =
  //   store.typeOrganizational === "current" ? store.activeId : store.draftId;
  // id &&
  await http
    .get(config.API.orgByid(id.toString()))
    .then((res) => {
      const data = res.data.result;
      nodeTree.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
  // console.log(nodeTree.value);
}

onMounted(async () => {
  const id =
    store.typeOrganizational === "current" ? store.activeId : store.draftId;
  id && (await fetchDataTree(id));
});

watch(
  () => count.value,
  () => {
    fetchDataTree(historyId.value);
  }
);

watch(
  () => store.typeOrganizational,
  () => {
    const id =
      store.typeOrganizational === "current" ? store.activeId : store.draftId;
    id && store.typeOrganizational !== "old" && 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">
          <TreeView
            v-model:nodeTree="nodeTree"
            :fetchDataTree="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">
        <div class="col-12 row items-center">
          <TableView v-model:showData="showData" />
        </div>
      </div>
    </q-card>
  </div>
</template>

<style scoped></style>
