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

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

/** importComponents*/
import DialogStructureDetail from "@/modules/02_organization/components/DialogStructureDetail.vue";

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

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

/** props*/
const nodeTEST = defineModel<OrgTree[]>("nodeTree", { default: [] });
const nodeId = defineModel<string>("nodeId", { required: true });
const orgRootId = defineModel<string | undefined>("orgRootId", {
  required: true,
});

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

/**
 * funtion เลือกข้อมูล Tree
 * @param data ข่อมูล Tree
 */
async function updateSelected(data: DataTree) {
  showLoader();
  try {
    orgRootId.value = data?.orgLevel === 0 ? data?.orgTreeId : data?.orgRootId;
    store.rootId = (
      data.orgLevel === 0 ? data.orgTreeId : data.orgRootId
    ) as string;

    if (!store.treeId || store.treeId != data.orgTreeId) {
      store.treeId = data.orgTreeId;
      store.level = data.orgLevel;

      nodeId.value = data.orgTreeId ? data.orgTreeId : "";

      /** ดึงข้อมูลสถิติจำนวนด้านบน*/
      await fetchSummary(data);
    }
  } catch (error) {
    console.error("Error showing loader:", error);
  } finally {
    hideLoader();
  }
}

const treeId = ref<string>("");
const dialogDetail = ref<boolean>(false);
/**
 * funtion ดูรายละเอียดโครงสร้าง
 * @param id ID โครงสร้าง
 * @param level ระดับโครงสร้าง
 */
function onClickDetail(id: string, level: number) {
  showLoader();
  treeId.value = id;
  dialogDetail.value = !dialogDetail.value;
  orgLevel.value = level;
}

/**
 * ฟังก์ชันดึงข้อมูลสถิติ
 * @param data ขอมูลโครงสร้าง
 */
async function fetchSummary(data: DataTree) {
  await http
    .post(config.API.orgSummary, {
      id: data.orgTreeId, //*Id node
      type: data.orgLevel, //*ประเภทnode
      isNode: true, //*นับทั้ง node ไหม
    })
    .then(async (res: any) => {
      const data = await res.data.result;
      if (data) {
        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,
        });
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}

watch(
  () => nodeTEST.value,
  () => {
    nodes.value = nodeTEST.value;
  }
);
</script>

<template>
  <div class="col-12 q-py-sm q-px-sm">
    <div class="q-gutter-sm">
      <div class="row q-col-gutter-sm q-pl-sm">
        <div class="col-12">
          <q-input dense outlined v-model="filter" label="ค้นหา">
            <template v-slot:append>
              <q-icon name="search" color="grey-5" />
            </template>
          </q-input>
        </div>
      </div>
      <div class="bg-white tree-container q-pa-xs">
        <q-tree
          class="q-pa-sm q-gutter-sm"
          dense
          default-expand-all
          :nodes="lazy"
          node-key="orgTreeId"
          label-key="labelName"
          :filter="filter.trim()"
          :no-results-label="notFound"
          :no-nodes-label="noData"
          v-model:expanded="expanded"
        >
          <template v-slot:default-header="prop">
            <q-item
              clickable
              :active="nodeId == prop.node.orgTreeId"
              @click.stop="updateSelected(prop.node)"
              active-class="my-list-link text-primary text-weight-medium"
              class="row col-12 text-dark items-center q-py-xs q-pl-sm rounded-borders my-list"
            >
              <div>
                <div
                  :class="
                    prop.node.isOfficer || prop.node.isInformation
                      ? 'text-weight-medium text-blue'
                      : 'text-weight-medium'
                  "
                >
                  <div
                    v-if="
                      (prop.node.isDeputy == true && prop.node.orgLevel == 0) ||
                      (prop.node.isCommission == true &&
                        prop.node.orgLevel == 0)
                    "
                    class="text-info"
                  >
                    {{ prop.node.orgTreeName
                    }}{{
                      prop.node.isCommission == true && prop.node.orgLevel == 0
                        ? ` (กก.)`
                        : ""
                    }}
                  </div>
                  <div v-else>
                    {{ prop.node.orgTreeName }}
                  </div>
                  {{ prop.node.isOfficer ? "(สกจ.)" : "" }}
                </div>
                <div class="text-weight-light text-grey-8">
                  {{ prop.node.orgCode == null ? null : prop.node.orgCode }}
                  {{
                    prop.node.orgTreeShortName == null
                      ? null
                      : prop.node.orgTreeShortName
                  }}
                </div>
              </div>

              <q-btn
                v-if="checkPermission($route)?.attrIsGet"
                @click.stop
                flat
                dense
                color="grey-13"
                icon="mdi-dots-vertical"
                round
              >
                <q-menu>
                  <q-list dense>
                    <q-item
                      clickable
                      v-close-popup
                      @click="
                        onClickDetail(prop.node.orgTreeId, prop.node.orgLevel)
                      "
                    >
                      <q-item-section avatar style="min-width: 20px">
                        <q-icon size="xs" color="blue-9" name="mdi-eye" />
                      </q-item-section>
                      <q-item-section>ดูรายละเอียด</q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </q-btn>
            </q-item>
          </template>
        </q-tree>
      </div>
    </div>
  </div>

  <!-- รายละเอียดโครงสร้าง -->
  <DialogStructureDetail
    v-model:structure-detail="dialogDetail"
    v-model:treeId="treeId"
    v-model:orgLevel="orgLevel"
  />
</template>

<style scoped>
.tree-container {
  overflow: auto;
  height: 73vh;
  border: 1px solid #e6e6e7;
  border-radius: 10px;
}

.my-list-link {
  color: rgb(118, 168, 222);
  border-radius: 5px;
  background: #a3d3fb48 !important;
  font-weight: 600;
  border: 1px solid rgba(175, 185, 196, 0.217);
}
</style>
