<template>
  <div class="bg-white m-4 mr-0 overflow-hidden">
    <a-spin :spinning="loading">
        <!--组织机构树-->
        <a-tree
          v-if="!treeReloading"
          title="分类列表"
          toolbar
          search
          :checkStrictly="true"
          :clickRowToExpand="false"
          :treeData="treeData"
          :replaceFields="{ key: 'id', title: 'name' }"
          :selectedKeys="selectedKeys"
          :expandedKeys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          @select="onSelect"
          @expand="onExpand"
        >
      </a-tree>
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
  import { inject, nextTick, ref ,onMounted} from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { listTree} from './api/productCassification.api';

  const prefixCls = inject('prefixCls');
  const emit = defineEmits(['select']);
  const { createMessage } = useMessage();

  let loading = ref<boolean>(false);
  // 部门树列表数据
  let treeData = ref<any[]>([]);
  // 当前展开的项
  let expandedKeys = ref([]);
  // 当前选中的项
  let selectedKeys = ref<any[]>([]);
  // 是否自动展开父级
  let autoExpandParent = ref<boolean>(true);
  // 用户身份
  let userIdentity = ref<string>('2');
  // 树组件重新加载
  let treeReloading = ref<boolean>(false);
  onMounted(() => {
      loadDepartTreeData();   
  });
  // 加载信息
  async function loadDepartTreeData() {
    loading.value = true;
    await listTree({pageSize:-1})
      .then((res) => {
          if (Array.isArray(res)) {
            treeData.value[0] = {id:'0',name:'基本分类(Basic Classification)',children:[]};
            treeData.value[0].children = res;
            autoExpandParentNode();
          }
      })
      .finally(() => (loading.value = false));
  }

  

  // 自动展开父节点，只展开一级
  function autoExpandParentNode() {
      reloadTree();
      expandedKeys.value = ['0']
  }

  // 重新加载树组件，防止无法默认展开数据
  async function reloadTree() {
    await nextTick();
    treeReloading.value = true;
    await nextTick();
    treeReloading.value = false;
  }

  // 树选择事件
  function onSelect(selKeys, event) {
    if (selKeys.length > 0 && selectedKeys.value[0] !== selKeys[0]) {
      emit('select', selKeys[0]);
    }
  }

  // 树展开事件
  async function onExpand(keys,event) {
        expandedKeys.value = keys;
        autoExpandParent.value = false;
  }
  defineExpose({
    loadDepartTreeData
  });
</script>
<style lang="less" scoped>
  /*升级antd3后，查询框与树贴的太近，样式优化*/
  :deep(.jeecg-tree-header) {
    margin-bottom: 6px;
  }
</style>
