<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import { useRoute } from "vue-router";
import { useStructureTree } from "@/stores/structureTree";

import { useReportStore } from "@/modules/21_report/store";

import type {
  DataStructureTree,
  DataNodeData,
} from "@/modules/21_report/interface/Main";

import DialogHeader from "@/components/DialogHeader.vue";

const store = useReportStore();
const route = useRoute();
const { fetchStructureTree } = useStructureTree();

const modal = defineModel<boolean>("modal", { required: true });
const orgName = defineModel<string>("name", { required: true });

const filter = ref<string>("");

const node = ref<DataStructureTree[]>([]);
const expanded = ref<string[]>([]);
const nodeData = reactive<DataNodeData>({
  name: "",
  nodeId: null,
  node: null,
});

/** ปิด dialog */
function close() {
  modal.value = false;
}

async function fetchTree() {
  const data = await fetchStructureTree(route.meta.Key as string, true);
  if (data) {
    node.value = data;
    store.formFilter.node = nodeData.node;
    store.formFilter.nodeId = nodeData.nodeId;
  }
}

/** ค้นหาข้อมูลรายชื่อข้อมูลทะเบียนประวัติตามหน่วยงาน/ส่วนราชการ*/
function sendNode() {
  nodeData.node = store.formFilter.node;
  nodeData.nodeId = store.formFilter.nodeId;
  orgName.value = nodeData.name;
  modal.value = false;
}

/**
 * ฟังก์ชันเลือกหน่วยงาน/ส่วนราชการ
 * @param data  ข้อมูลหน่วยงาน/ส่วนราชการที่ต้องการค้นหาร
 * เพื่อค้นหาข้อมูลตามหน่วยงาน/ส่วนราชการ
 */
function updateSelectedTreeMain(data: DataStructureTree) {
  if (nodeData.node === data.orgLevel && nodeData.nodeId === data.orgTreeId) {
    store.formFilter.node = null;
    store.formFilter.nodeId = null;
    nodeData.name = "";
  } else {
    store.formFilter.node = data.orgLevel;
    store.formFilter.nodeId = data.orgTreeId;
    nodeData.name = data.orgName;
  }
}

watch(
  () => modal.value,
  async () => {
    if (modal.value) {
      await fetchTree();

      if (!orgName.value) {
        nodeData.name = "";
        nodeData.node = "";
        nodeData.nodeId = "";
        store.formFilter.node = null;
        store.formFilter.nodeId = null;
        expanded.value = [];
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 850px; max-width: 80vw">
      <DialogHeader tittle="เลือกหน่วยงาน/ส่วนราชการ" :close="close" />

      <q-separator />

      <q-card-section class="q-pa-sm">
        <div class="row q-col-gutter-sm">
          <div class="col-12">
            <q-input dense outlined v-model="filter" label="ค้นหา">
              <template v-slot:append>
                <q-icon
                  v-if="filter !== ''"
                  name="clear"
                  class="cursor-pointer"
                  @click="filter = ''"
                />
                <q-icon v-else name="search" color="grey-5" />
              </template>
            </q-input>
          </div>
          <div class="col-12">
            <q-tree
              class="tree-container"
              dense
              :nodes="node"
              node-key="orgTreeName"
              label-key="labelName"
              v-model:expanded="expanded"
              :filter="filter.trim()"
              no-results-label="ไม่พบข้อมูลที่ค้นหา"
              no-nodes-label="ไม่มีข้อมูล"
              v-model:selected="nodeData.nodeId"
            >
              <template v-slot:default-header="prop">
                <q-item
                  clickable
                  @click.stop="updateSelectedTreeMain(prop.node)"
                  :active="store.formFilter.nodeId === prop.node.orgTreeId"
                  active-class="my-list-link text-primary text-weight-medium"
                  class="row col-12 items-center text-dark q-py-xs q-pl-sm rounded-borders my-list"
                >
                  <div>
                    <div class="text-weight-medium">
                      {{ prop.node.orgTreeName }}
                    </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-item>
              </template>
            </q-tree>
          </div>
        </div>
      </q-card-section>
      <q-separator />

      <q-card-actions align="right">
        <q-btn label="เลือก" color="secondary" @click="sendNode">
          <q-tooltip>เลือก</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
