<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";

/** importComponents*/
import DialogAgency from "@/modules/02_organizationalNew/components/DialogFormAgency.vue";
import DialogStructureDetail from "@/modules/02_organizationalNew/components/StructureDetail.vue";

/** 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 props = defineProps({
  fetchDataTree: {
    type: Function,
    require: true,
  },
});

const listAdd = ref<ListMenu[]>([
  {
    label: "เพิ่ม",
    icon: "add",
    type: "ADD",
    color: "primary",
  },
  {
    label: "แก้ไข",
    icon: "edit",
    type: "EDIT",
    color: "info",
  },
  {
    label: "ลบ",
    icon: "mdi-trash-can-outline",
    type: "DEL",
    color: "red",
  },
  // {
  //   label: "สำเนาหน่วยงาน",
  //   icon: "content_copy",
  //   type: "COPY",
  //   color: "blue",
  // },
  {
    label: "ประวัติ",
    icon: "history",
    type: "HISTORY",
    color: "purple",
  },
  {
    label: "จัดลำดับ",
    icon: "filter_list",
    type: "SORT",
    color: "green-7",
  },
  // {
  //   label: "แก้ไขสถานะ",
  //   icon: "rule",
  //   type: "STATUS",
  //   color: "yellow-9",
  // },
  {
    label: "ดูรายละเอียด",
    icon: "mdi-eye",
    type: "DETAIL",
    color: "blue-9",
  },
]);

const nodeTEST = defineModel<OrgTree[]>("nodeTree", { default: [] });
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 selected = ref("");
const orgLevel = ref<number>(0);

const updateSelected = (target: any) => {
  console.log("updateSelected===>", target);
};

const breakLoop = ref<boolean>(false);
async function edit(id: string, type: string, data: any) {
  const data2 = {
    orgName: data[`org${type}Name`],
    orgShortName: data[`org${type}ShortName`],
    orgCode: data[`org${type}Code`],
    orgPhoneEx: data[`org${type}PhoneEx`],
    orgPhoneIn: data[`org${type}PhoneIn`],
    orgFax: data[`org${type}Fax`],
    orgLevel: data[`org${type}Rank`],
  };

  breakLoop.value = false;

  // Usage
  const targetNodeId = id;
  const replacementNode = {
    orgTreeName: data2.orgName,
    orgTreeShortName: data2.orgShortName,
    orgCode: data2.orgCode,
    orgTreePhoneEx: data2.orgPhoneEx,
    orgTreePhoneIn: data2.orgPhoneIn,
    orgTreeFax: data2.orgFax,
    orgTreeRank: data2.orgLevel,
  };

  for (let index = 0; index < nodes.value.length; index++) {
    const element = nodes.value[index];
    if (type !== "edit") {
      searchAndReplace(element, targetNodeId, replacementNode);
    } else deleteNode(element, targetNodeId);

    console.log("index===>", index);
    console.log("breakLoop===>", breakLoop.value);
    if (breakLoop.value) break;
  }
}

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

function deleteNode(treeNode: any, organizationId: any): boolean {
  // console.log("tttttttttttttt", treeNode.orgTreeId, organizationId);

  if (treeNode.orgTreeId === organizationId) {
    treeNode.children = [];

    breakLoop.value = true;
  } else if (treeNode.children) {
    for (let i = 0; i < treeNode.children.length; i++) {
      const child = treeNode.children[i];
      if (deleteNode(child, organizationId)) {
        treeNode.children.splice(i, 1);
        i--; // ลดค่า i เพราะที่ลบข้อมูล
      }
    }
  }

  return false;
}

const dialogAgency = ref<boolean>(false);
const actionType = ref<string>("");
const dataNode = ref<any>();
const treeId = ref<string>("");

function onClickAgency(level: number, node: OrgTree | {}) {
  dialogAgency.value = !dialogAgency.value;
  orgLevel.value = level;
  dataNode.value = node;
  actionType.value = "ADD";
}

const dialogDetail = ref<boolean>(false);
function onClickDetail(id: string, level: number) {
  showLoader();
  treeId.value = id;
  dialogDetail.value = !dialogDetail.value;
  orgLevel.value = level;
}

async function onClickEdit(node: OrgTree) {
  dialogAgency.value = !dialogAgency.value;
  actionType.value = "EDIT";
  orgLevel.value = node.orgLevel;
  dataNode.value = node;
}

async function onClickDel(type: number, id: string) {
  const level = store.checkLevel(type);

  dialogRemove($q, async () => {
    // edit(id, "edit", {});
    showLoader();
    await http
      .delete(config.API.orgLevelByid(level.toLocaleLowerCase(), id))
      .then(() => {
        success($q, "ลบข้อมูลสำเร็จ");
        // edit(id, "edit", {});
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(async () => {
        await props.fetchDataTree?.();
        await hideLoader();
      });
  });
}

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

onMounted(async () => {});
</script>

<template>
  <div class="col-12 q-py-md q-px-lg">
    <div class="q-gutter-md">
      <div class="row q-col-gutter-sm">
        <div class="col-2" v-if="store.typeOrganizational === 'draft'">
          <q-btn
            dense
            flat
            round
            color="primary"
            icon="add"
            @click="onClickAgency(0, {})"
          >
            <q-tooltip>เพิ่มหน่วยงาน</q-tooltip>
          </q-btn>
        </div>

        <div
          :class="store.typeOrganizational === 'draft' ? 'col-10' : '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 = ''"
              />
            </template>
          </q-input>
        </div>
      </div>
      <div
        class="bg-white"
        style="
          height: 60vh;
          border: 1px solid rgb(210, 210, 210);
          border-radius: 10px;
        "
      >
        <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"
          @update:selected="updateSelected"
        >
          <template v-slot:default-header="prop">
            {{ prop.node.orgTreeName }}

            <q-btn
              v-if="store.typeOrganizational === 'draft'"
              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="
                      item.type === 'EDIT'
                        ? onClickEdit(prop.node)
                        : item.type === 'ADD'
                        ? onClickAgency(prop.node.orgLevel + 1, prop.node)
                        : item.type === 'DETAIL'
                        ? onClickDetail(prop.node.orgTreeId, prop.node.orgLevel)
                        : item.type === 'DEL'
                        ? onClickDel(prop.node.orgLevel, prop.node.orgTreeId)
                        : null
                    "
                  >
                    <q-item-section avatar>
                      <q-icon :color="item.color" :name="item.icon" />
                    </q-item-section>
                    <div v-if="prop.node.orgLevel === 0">
                      <q-item-section
                        v-if="
                          item.type === 'EDIT' ||
                          item.type === 'DEL' ||
                          item.type === 'HISTORY'
                        "
                        >{{ item.label }}หน่วยงาน</q-item-section
                      >
                      <q-item-section v-else-if="item.type === 'ADD'"
                        >{{ item.label }}ส่วนราชการ</q-item-section
                      >
                      <q-item-section v-else>{{ item.label }}</q-item-section>
                    </div>

                    <div v-else>
                      <q-item-section
                        v-if="
                          item.type === 'ADD' ||
                          item.type === 'EDIT' ||
                          item.type === 'DEL' ||
                          item.type === 'HISTORY'
                        "
                        >{{ item.label }}ส่วนราชการ</q-item-section
                      >
                      <q-item-section v-else>{{ item.label }}</q-item-section>
                    </div>
                  </q-item>
                </q-list>
              </q-menu>
            </q-btn>

            <q-btn
              v-else
              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 listAdd.slice(5, 6)"
                  :key="index"
                  style="min-width: 100px"
                >
                  <q-item
                    clickable
                    v-close-popup
                    @click="
                      item.type === 'EDIT'
                        ? onClickEdit(prop.node)
                        : item.type === 'ADD'
                        ? onClickAgency(prop.node.orgLevel + 1, prop.node)
                        : item.type === 'DETAIL'
                        ? onClickDetail(prop.node.orgTreeId, prop.node.orgLevel)
                        : item.type === 'DEL'
                        ? onClickDel(prop.node.orgLevel, prop.node.orgTreeId)
                        : null
                    "
                  >
                    <q-item-section avatar>
                      <q-icon :color="item.color" :name="item.icon" />
                    </q-item-section>
                    <q-item-section>{{ item.label }}</q-item-section>
                  </q-item>
                </q-list>
              </q-menu>
            </q-btn>
          </template>

          <template v-slot:default-body="prop">
            <div v-if="prop.node.orgCode">
              <span class="text-grey-13">{{ prop.node.orgCode }}</span>
            </div>
          </template>
        </q-tree>

        <!-- <div class="q-pa-md q-gutter-sm">
          <q-tree :nodes="nodes" node-key="orgRootName" default-expand-all>
            <template v-slot:default-header="prop">
              <div class="row">
                <div class="text-weight-bold text-primary">
                  {{ prop.node.orgRootName }}
                </div>
              </div>
            </template>

            <template v-slot:default-body="prop">
           
            </template>
          </q-tree>
        </div> -->
      </div>
    </div>
  </div>

  <!-- เพิ่มหน่วยงาน -->
  <DialogAgency
    :modal="dialogAgency"
    :close="onClickAgency"
    v-model:orgLevel="orgLevel"
    :fetchDataTree="props.fetchDataTree"
    v-model:actionType="actionType"
    :dataNode="dataNode"
    :edit="edit"
  />

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

<style scoped></style>
