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

import type { ListMenu } from "@/modules/02_organizationalNew/interface/index/Main";
import type { OrgTree } from "@/modules/02_organizationalNew/interface/response/organizational";

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

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

const filter = ref<string>("");
const nodes = ref<Array<any>>([]);
const lazy = ref(nodes);
const expanded = ref<Array<any>>([]);
const notFound = ref<string>("ไม่พบข้อมูลที่ค้นหา");
const noData = ref<string>("ไม่มีข้อมูล");
const selected = ref("");

const idVal = ref("");
async function fetchDataTree(id: string) {
  showLoader();
  await http
    .get(config.API.orgByid(id.toString()))
    .then((res) => {
      const data = res.data.result;
      nodes.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const breakLoop = ref<boolean>(false);
const dataObject = ref([]);
async function onSort(orgRootId: string) {
  if (orgRootId) {
    idVal.value = 'children => '+orgRootId;
    breakLoop.value = false;

    const targetNodeId = orgRootId;

    for (let index = 0; index < nodes.value.length; index++) {
      const element = nodes.value[index];
      searchAndReplace(element, targetNodeId);
      if (breakLoop.value) break;
    }
  } else {
    idVal.value = 'root';
  }
}

function searchAndReplace(treeNode: any, organizationId: string) {
  if (treeNode.orgTreeId === organizationId) {
    dataObject.value = treeNode.children;
    breakLoop.value = true;
  } else if (treeNode.children) {
    for (const child of treeNode.children) {
      searchAndReplace(child, organizationId);
    }
  }
}

const listAdd = ref<ListMenu[]>([
  {
    label: "จัดลำดับ",
    icon: "filter_list",
    type: "SORT",
    color: "green-7",
  },
]);

onMounted(async () => {
  await fetchDataTree("a449eac0-93a5-4ccc-8fbc-2974ca8ee61b");
});
</script>

<template>
  <div class="col-12 q-py-md q-px-lg">
    <q-tree
      class="q-pa-md q-gutter-sm"
      dense
      default-expand-all
      selected-color="primary"
      :nodes="lazy"
      node-key="orgTreeId"
      label-key="orgTreeName"
      :filter="filter"
      :no-results-label="notFound"
      :no-nodes-label="noData"
      v-model:expanded="expanded"
      v-model:selected="selected"
    >
      <template v-slot:default-header="prop">
        <!-- {{ prop.node.orgTreeName }} -->

        <div class="row items-center q-px-xs q-pt-xs q-gutter-sm">
          <!--แสดงชื่อแผนก พิมพ์ตัวหนา คลิกแล้วกาง/หุบ Tree-->
          <div>
            <div class="text-weight-medium">
              {{ prop.node.orgTreeName }}
            </div>
            <div class="text-weight-light">
              {{ prop.node.orgCode == null ? null : prop.node.orgCode }}
              {{
                prop.node.orgTreeShortName == null
                  ? null
                  : prop.node.orgTreeShortName
              }}
            </div>
          </div>
        </div>

        <q-btn
          flat
          dense
          icon="mdi-dots-vertical"
          class="q-pa-none q-ml-xs"
          color="grey-13"
        >
          <q-menu>
            <q-list
              dense
              v-for="(item, index) in prop.node.orgLevel === 4
                ? listAdd.slice(1, 6)
                : listAdd"
              :key="index"
              style="min-width: 100px"
            >
              <q-item
                clickable
                v-close-popup
                @click="onSort(prop.node.orgRootId)"
              >
                <q-item-section avatar>
                  <q-icon :color="item.color" :name="item.icon" />
                </q-item-section>
                <div>
                  <q-item-section> {{ item.label }}หน่วยงาน </q-item-section>
                </div>
              </q-item>
            </q-list>
          </q-menu>
        </q-btn>
      </template>
    </q-tree>

    <h5>orgRootId = {{ idVal }}</h5>
    <div>
      {{ dataObject }}
    </div>
  </div>
</template>

<style scoped></style>
