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

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

import { useCounterMixin } from "@/stores/mixin";

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

const modal = defineModel<boolean>("modal", { default: false });

const emit = defineEmits(["update:updateAgency"]);
const node = ref<any>([]);
const expanded = ref<any>([]);
const ticked = ref<any>([]);

function closeDialog() {
  modal.value = false;
  ticked.value = [];
  expanded.value = [];
}
function fetchActive() {
  showLoader();
  http
    .get(config.API.activeOrganization)
    .then((res) => {
      const data = res.data.result;
      fetchTree(data.activeId);
    })
    .catch((err) => {
      messageError($q, err);
      hideLoader();
    });
}

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

function updateTicked(val: any) {
  console.log(expanded.value);

  ticked.value = [];
  ticked.value.push(val[val.length - 1]);
}

function onSubmit() {
  emit("update:updateAgency", ticked.value[0]);
  closeDialog();
}

function splitWords(sentence: string) {
  // ใช้ฟังก์ชั่น split เพื่อแยกข้อความด้วยเครื่องหมาย '/'
  const words = sentence.split("/");
  console.log(words);

  // ticked.value = sentence;
  // expanded.value = words.reverse();
}

watch(
  () => modal.value,
  () => {
    modal.value && fetchActive();
    // splitWords("ฝ่ายบริหารทั่วไป/กองโครงสร้างและอัตรากำลัง/สำนักงาน ก.ก.");
  }
);
</script>
<template>
  <q-dialog v-model="modal">
    <q-card style="width: 600px; max-width: 80vw">
      <DialogHeader
        :tittle="'เลือกหน่วยงานที่รับผิดชอบ'"
        :close="closeDialog"
      />
      <q-separator />

      <q-card-section class="q-pt-none scroll" style="max-height: 65vh">
        <q-tree
          class="q-pa-sm q-gutter-sm"
          dense
          :nodes="node"
          node-key="orgName"
          label-key="labelName"
          v-model:expanded="expanded"
          tick-strategy="strict"
          v-model:ticked="ticked"
          @update:ticked="updateTicked"
        >
          <template v-slot:default-header="prop">
            <q-item
              clickable
              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>
      </q-card-section>

      <q-separator />

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn dense unelevated label="บันทึก" color="public" @click="onSubmit">
          <q-tooltip>บันทึกข้อมูล</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
