<template>
  <div class="tree-wrapper">
    <!-- <ele-modal
      width="800px"
      :visible.sync="showEditFlag"
      :close-on-click-modal="false"
      custom-class="ele-dialog-form"
      append-to-body
      @close="cancel"
      title="使用对象"
    > -->
    <!-- <el-tree
        :data="treeList"
        :props="defaultProps"
        v-loading="treeLoading"
        :node-key="nodeKey"
        show-checkbox
        ref="tree"
        :expand-on-click-node="false"
        @check-change="handleNodeClick"
        v-bind="$attrs"
        :check-strictly="true"
        :default-expand-all="defaultExpandAll"
      >
      </el-tree> -->
    <tree-transfer
      :from_data="treeList"
      :to_data="selection"
      :defaultProps="defaultProps"
      height="540px"
      node_key="id"
      pid="parentId"
      @add-btn="add"
      @remove-btn="remove"
      :title="['对象', '已选对象']"
    >
    </tree-transfer>
    <!-- <template v-slot:footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save"> 确认 </el-button>
      </template>
    </ele-modal> -->
  </div>
</template>
  
  <script>
import { getTreeByPid } from '@/api/classifyManage';
import { getDocTreeListAPI } from '@/api/businessCode';
import treeTransfer from 'el-tree-transfer'; // 引入
export default {
  data() {
    return {
      defaultProps: { children: 'children', label: 'name' },
      treeList: [],
      treeLoading: false,
      selection: []
    };
  },
  components: {
    treeTransfer
  },

  methods: {
    init(selection) {
      this.selection = selection;
      this.getTreeData();
    },
    // 监听穿梭框组件添加
    add(fromData, toData, obj) {
      // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
      // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
      console.log('fromData:', fromData);
      console.log('toData:', toData);
      console.log('obj:', obj);
    },
    // 监听穿梭框组件移除
    remove(fromData, toData, obj) {
      // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
      // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
      console.log('fromData:', fromData);
      console.log('toData:', toData);
      console.log('obj:', obj);
    },
    // 获取树结构数据
    async getTreeData() {
      try {
        this.treeLoading = true;
        const res = await getTreeByPid(0);
        let res1 = await getDocTreeListAPI({ type: '0' });
        this.treeLoading = false;
        let treeList = [];
        if (res?.code === '0') {
          this.filterDoc(res1);
          treeList = [
            ...res.data
              .map((item) => {
                item.parentId = 0;
                return item;
              })
              .filter((item) => ['9', '1'].includes(item.id)),
            ...res1
          ];
          let rightIds = this.getRightDataIds(this.selection, []);
          this.treeList = this.filterLeftData(treeList, rightIds, []);
        }
      } catch (error) {}
      this.treeLoading = false;
    },
    getRightDataIds(list, rightIds) {
      for (let rightItem of list) {
        rightIds.push(rightItem.id);
        if (rightItem.children && rightItem.children.length) {
          this.getRightDataIds(rightItem.children, rightIds);
        }
      }
      return rightIds;
    },
    filterDoc(data) {
      data.forEach((item) => {
        item['children'] = item.sonDirectoryList;
        delete item.sonDirectoryList
        if (item.parentId == 0) {
          item.parentId = 0;
          item.name = '文档';
        }
        if (item['children'].length > 0) {
          this.filterDoc(item['children']);
        }
      });
    },
    filterLeftData(list, rightIds, newList) {
      // console.log(rightIds)
      // list.forEach(leftItem=>{
      //   if(rightIds.includes(leftItem.id)){
      //     leftItem
      //     newList.push(leftItem)
      //   }
      // })
      for (let leftItem of list) {
        if (rightIds.includes(leftItem.id)) {
          if (leftItem.children && leftItem.children.length) {
            let insetBool = false;
            for (let child of leftItem.children) {
              if (!rightIds.includes(child.id)) insetBool = true;
            }
            if (insetBool) {
              let jsonItem = JSON.parse(JSON.stringify(leftItem));
              jsonItem.children = [];
              newList.push(jsonItem);
              this.filterLeftData(
                leftItem.children,
                rightIds,
                jsonItem.children
              );
            }
          }
        } else {
          let jsonItem = JSON.parse(JSON.stringify(leftItem));
          newList.push(jsonItem);
        }
      }
      return newList;
    },
    getList() {
      return this.selection;
    }
  }
};
</script>
  
  <style lang="scss" scoped>
.tree-wrapper {
  width: 100%;
  height: 100%;
  overflow: auto;

  :deep(.el-tree) {
    display: inline-block;
    min-width: 100%;
  }
}
</style>
  