<template>
  <a-tree
    :autoExpandParent="autoExpandParent"
    :replaceFields="replaceFields"
    :selectedKeys.sync="treeSelect"
    :expandedKeys.sync="treeSelect"
    :treeData="treeData"
    @select="treeCheck"
  />
</template>

<script>
/**
 * 多选的树
 */
export default {
  name: "Wonetree",
  props:{
    createFun:{
      type: Function,
      required: true
    },
    //是否自动展开父节点
    autoExpandParent:{
      type:Boolean,
      default(){
        return true;
      }
    },
    replaceFields:{
      type:Object,
      default(){
        return {children:'children', title:'title', key:'key' }
      }
    },
    valueName:{
      type:String,
      default:"name"
    }

  },
  data(){
    return {
      treeSelect:"",
      treeData:[],
      trees:{}
    }
  },
  methods:{
    createList() {
      return new Promise(resolve => {
        this.createFun().then(res =>{
          this.treeData = this.toTree(res);
          resolve()
        })
      })

    },
    async setValue(id){
      if(JSON.stringify(this.trees) == "{}"){
        await this.createList();
      }
      for(let name in this.trees){
        if(this.trees[name].id == id){
          this.treeSelect = [name];
          break;
        }
      }
    },
    toTree(list, text,plist) {
      if (!text) {
        text = '0-'
      }

      let list2 = new Array();
      for (let i = 0; i < list.length; i++) {
        let item = list[i]
        item['key'] = text + i
        item['value'] = text + i
        item['title'] = item[this.valueName];//item['name']
        if(plist){
          item['plist'] = plist
        }else{
          plist = new Array();
        }
        if (item.children) {
          let plist2 = JSON.parse(JSON.stringify(plist));
          plist2.push(item.id);
          item.children = this.toTree(item.children, text + i + '-',plist2)
        }else{
          item["isChild"] = true;
        }
        this.trees[text + i] = item
        list2.push(item)
      }
      return list2
    },
    treeCheck(checkedKeys){
      let id = this.trees[checkedKeys[0]].id;
      this.$emit("select",{id});
    }
  },
  created(){
    this.createList();
  }
}
</script>

<style scoped>

</style>
