<template>
  <div class="departmentTree-box" :style="{ width: width, height: '100%', }">
    <div class="depar_foot">
      <el-tree ref="treeRef" class="filter-tree" :props="endProps" node-key="id" :default-expanded-keys="expandKeys"
        @node-click="nodeClick" :data="treeData" highlight-current :current-node-key="nodeobj.id"
        :check-on-click-node="false">
        <template #default="{ node }">
          <span class="prefix" :class="{ 'is-leaf': node.isLeaf }"> <img :src="getImgUrl('img/zzjgli.png')"
              alt=""></span>
          <span>{{ node.label }}</span>
        </template>
      </el-tree>
    </div>
  </div>
</template>

<script setup>
import { getImgUrl } from "@/utils/tools.js"
import { ref, defineProps, defineEmits, watch, watchEffect, onMounted, reactive, nextTick } from "vue";
import { getApi } from "@/api/tobAcco_api.js";
const props = defineProps({
  multiple: {
    default: false,
    type: Boolean
  },
  filterable: {
    default: true,
    type: Boolean
  },
  modelValue: {
    type: String
  },
});
const endProps = {
  children: "children",
  value: "id",
  label: "name",
  isLeaf: "leaf"
};
const treeRef = ref(null);
const nodeobj = reactive({
  id: undefined
})
/** 默认展开的节点 */
const expandKeys = ref([]);
const treeDataAll = ref([]);
const treeData = ref([]);
const width = ref();
const emits = defineEmits(["update:modelValue", "change"]);
onMounted(() => { getTreeData() });
//防抖处理
watch(() => treeData.value.length, () => {
  if (treeData.value?.length > 0) {
    const root = treeData.value[0];
    expandLastLevel(root, 0);
  }
})

function expandLastLevel(node, level) {
  if (level === 0) {
    node.expanded = true;
  } else if (node.children && node.children.length > 0) {
    node.children.forEach((child) => {
      expandLastLevel(child, level - 1);
    });
  }
}
/**获取默认展开的节点，展开第一个的第一个的第一个的第一个 */
function getExpandFirstArr(arr, expandArr) {
  arr = Array.isArray(arr) ? arr : []
  let first = arr[0]
  if (first) {
    if (first.children?.length > 0) {
      expandArr.push(first.id)
      return getExpandFirstArr(first.children, expandArr)
    } else {
      return expandArr
    }
  } else {
    return expandArr
  }
}
function getFirstAndFirstId(arr) {
  if (!arr?.[0]) return ''
  return arr[0]?.children?.length ? getFirstAndFirstId(arr[0].children) : arr[0]
}
//获取部门数据
function getTreeData() {
  getApi({}, '/mosty-jcgl/fxdy/tree').then(async (res) => {
    if (res) {
      treeData.value = Array.isArray(res) ? res : [];
      expandKeys.value = getExpandFirstArr(treeData.value, [])
      const firstItem = getFirstAndFirstId(treeData.value)
      nodeobj.id = firstItem.id
      const lev1 = treeData.value[0]
      // treeRef.value.setCurrentKey(firstItem.id)
      // 添加这行代码：设置当前选中节点以实现高亮
      nextTick(() => {
        treeRef.value.setCurrentKey(firstItem.id)
      })
      emits("update:modelValue", firstItem.id);
      emits("change", firstItem.id, firstItem, lev1);
    }
  });
}

const getLev1Node = (nodeObj) => {
  return nodeObj?.parent?.parent ? getLev1Node(nodeObj.parent) : nodeObj.data
}

const nodeClick = (node, nodeObj) => {

  const id = node.id;
  nodeobj.id = node.id
  /** 获取它第一级的节点 */
  const lev1 = getLev1Node(nodeObj)

  emits("update:modelValue", id);
  emits("change", id, node, lev1);
};
</script>

<style lang="scss" scoped>
.depar_hear {
  height: 32px;
}

.prefix {
  margin-right: 5px;
}

.depar_foot {
  overflow: auto;
}

.departmentTree-box {
  height: 80vh;
}
</style>
