<!-- 部门树形选择下拉框 -->
<template>
  <ele-tree-select
    clearable
    :value="value || ''"
    :data="treeData"
    label-key="name"
    value-key="id"
    default-expand-all
    :placeholder="placeholder"
    @input="updateValue"
    @change="changeChoose"
    ref="treeSelect"
    v-bind="$attrs"
  />
</template>

<script>
  import { listOrganizations } from '@/api/system/organization';
  export default {
    props: {
      // 选中的数据(v-model)
      value: [Number, String],
      // 提示信息
      placeholder: {
        type: String,
        default: '请选择'
      }
    },
    data() {
      return {
        treeData: []
      };
    },
    created() {
      this.getData();
    },
    methods: {
      async getData(parmas = {}) {
        const data = await listOrganizations(parmas);
        this.treeData = this.$util.toTreeData({
          data: data || [],
          idField: 'id',
          parentIdField: 'parentId'
        });
      },
      /* 更新选中数据 */
      updateValue(value) {
        this.$emit('input', value);
      },
      changeChoose(val) {
        this.$emit(
          'changeGroup',
          val,
          this.$refs.treeSelect.getNodeByValue(val)
        );
      },
      async locateByName(code) {
        await this.getData();
        const res = this.findNodesByNameWithPath(this.treeData, code);

        console.log(res);
        if (!res.length) return;

        const { node, path } = res[0];

        this.$nextTick(() => {
          // 设置选中
          this.updateValue(node.id);
          this.changeChoose(node.id);

          // 展开树路径
          const tree = this.$refs.treeSelect?.$refs?.tree;
          if (!tree) return;

          path.forEach((p) => {
            const treeNode = tree.store.nodesMap[p.id];
            treeNode && treeNode.expand();
          });
        });
      },

      findNodesByNameWithPath(tree, code) {
        const result = [];

        function dfs(list, path = []) {
          list.forEach((node) => {
            const currentPath = [...path, node];

            if (node.groupCode == code) {
              result.push({
                node,
                path: currentPath
              });
            }

            if (node.children?.length) {
              dfs(node.children, currentPath);
            }
          });
        }

        dfs(tree);
        return result;
      }
    }
  };
</script>
