<template>
  <a-config-provider :locale="zh_CN">
    <div>
      <a-tree-select
          style="width: 90%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          v-model:value="searchValue"
          :placeholder="$t('functional-analysis.net.please-select-a-structure')"
          allow-clear
          show-search
          :treeExpandedKeys="expandedKeys"
          :replaceFields="replaceFields"
          :filterTreeNode="filterTreeNode"
          :tree-data="treeData"
          @treeExpand="treeExpand"
          @change="treeSelectChange">
        <template slot="treeDataSlot" slot-scope="node">
          {{ node.name }}
        </template>
      </a-tree-select>
    </div>
  </a-config-provider>
</template>
<script>

import zh_CN from "ant-design-vue/lib/locale-provider/zh_CN";

export default {
  name: "TreeSelect",
  props: {
    treeData: {
      type: Array,
      default: []
    },
    directFlag: {
      type: Number,
      default: undefined // 0：左侧；1：右侧
    },
  },
  watch: {
    treeData: {
      handler(v) {
        // 添加插槽
        this.addScopedSlots(v);
        // 默认展开所有
        this.expandedKeys = [];
        this.defaultExpandedAllKeys(v);
      },
      immediate: true,
    },
  },
  data() {
    return {
      /** 中文组件化 */
      zh_CN,
      searchValue: undefined,
      /** (受控)展开指定的树节点 */
      expandedKeys: [],
      /** 替换 treeNode 中对应参数 */
      replaceFields: {children: 'children', label: 'name', key: 'id', value: 'id'},
    };
  },
  methods: {
    /**
     * 输入项筛选
     * @param inputValue
     * @param treeNode
     */
    filterTreeNode(inputValue, treeNode) {
      return treeNode.data.props.name.includes(inputValue)
    },
    /**
     * 添加插槽
     */
    addScopedSlots(nodes) {
      for (let i = 0, len = nodes.length; i < len; i++) {
        // 通过vue 自带的$set 给每条数据加上一个名为scopedSlots，值为{title: 'node'}，的插槽
        this.$set(nodes[i], "scopedSlots", {title: "treeDataSlot"});
        if (nodes[i].children && nodes[i].children.length > 0) {
          this.addScopedSlots(nodes[i].children);
        }
      }
      return nodes;
    },
    /**
     * 默认展开全部节点
     * @param treeData tree绑定数据
     */
    defaultExpandedAllKeys(treeData) {
      let _that = this;
      for (let i = 0; i < treeData.length; i++) {
        _that.expandedKeys.push(treeData[i].id);
        if (treeData[i].children && treeData[i].children.length > 0) {
          _that.defaultExpandedAllKeys(treeData[i].children);
        }
      }
    },
    /**
     * 图标展开/收起节点时触发
     * @param expandedKeys
     * @param e
     */
    treeExpand(expandedKeys, e) {
      this.expandedKeys = expandedKeys;
    },
    /**
     * 树下拉选择事件
     * @param value
     * @param label
     * @param extra
     */
    treeSelectChange(value, label, extra) {
      this.$emit("treeSelectChange", value, this.directFlag);
    },
  }
};
</script>

<style lang="scss">
.ant-select-tree li {
  margin: 2px 0 !important;
}
</style>
