<template>
  <a-tree
    checkable
    :autoExpandParent="autoExpandParent"
    :replaceFields="replaceFields"
    v-model="treeSelect"
    :treeData="treeData"
    @check="treeCheck"
  />
</template>

<script>
/**
 * 多选的树
 */
export default {
  name: "Wtree",
  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(list){
      if(JSON.stringify(this.trees) == "{}"){
        await this.createList();
      }

      let that = this;
      let list2 = new Array();

      list.forEach(id => {
        for(let name in that.trees){
          if(that.trees[name].id == id &&that.trees[name]["isChild"]){
            list2.push(name);
            break;
          }
        }
      });
      this.treeSelect = list2;
    },
    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,e){
      let dataList = new Array();
      e.checkedNodes.forEach(item =>{
        let data = item.data.props;
        if(data.plist){
          data.plist.forEach(item2 =>{
            dataList.push(item2);
          })
        }
        dataList.push(data.id);
      })
      this.$emit("selectChange",dataList);
    }
  },
  created(){
    this.createList();
  }
}
</script>

<style scoped>

</style>
