<template>
  <div class="tree" :style="{'height':height + 'px','width':width == 0 ? 250 : width + 'px'}">
    <a-tree
      :tree-data="treeData"
      checkable
      :fieldNames="{children: 'children', title: 'pnm', key: 'id'}"
      :autoExpandParent="false"
      ref="treeBox"
      @check="handleCheckChange"
    > </a-tree>
  </div>
</template>

<script>
import request from '../../utils/gw_ajax_request.js';
import { dateFormat } from '../../utils/gw_date';

export default {
  components: {},
  props: ['pid', 'type', 'pidNodes', 'height', 'width'],
  data() {
    return {
      treeData: [],
      code: '45',
      tableDefaultExpandedKeys: [],
      treeProps: {
        title: 'pnm',
        children: 'children',
        key: 'id',
      },
      checkedData: [],
      changedData: [],
    };
  },
  mounted: function () {
    if (this.width == undefined) {
      this.width = '250';
    }
    if (this.height == undefined) {
      this.height = '550';
    }
    this.getLeftTreeData();
  },
  created: () => {
    // console.dir("Init" + this.checkedData);
  },
  watch: {},
  computed: {
    userId: () =>
      localStorage.getItem('userid')
        ? localStorage.getItem('userid')
        : '1098101939614724096',
  },
  methods: {
    // 节点点击事件
    nodeClick: (data) => {
      // alert(data.id);
    },
    // 递归获取选中的元素id
    getCheckedNode: function (data) {
      if (
        data.children == null ||
        data.disabled ||
        data.children.length === 0
      ) {
        return;
      }
      data.children.forEach((element, index) => {
        this.checkedData.push({
          id: element.id,
          pnm: element.pnm,
        });
        this.getCheckedNode(element);
      });
    },
    // 递归获取改变的元素id
    getChangedNode: function (data) {
      if (
        data.children == null ||
        data.disabled ||
        data.children.length === 0
      ) {
        return;
      }
      data.children.forEach((element, index) => {
        this.changedData.push({
          id: element.id,
          pnm: element.pnm,
        });
        this.getChangedNode(element);
      });
    },
    // 选中或取消事件
    handleCheckChange: function (selectedKeys, e) {
      selectedKeys = selectedKeys.concat(e.halfCheckedKeys);
      this.tableDefaultExpandedKeys = selectedKeys;
      var list = [];
      selectedKeys.forEach((item) => {
        list.push({
          id: item,
        });
      });
      this.checkedData = list;
      this.$emit('treeCheckedDataChange', {
        newCheckedArray: this.checkedData,
      });
    },
    // 根据用户id获取左侧树
    getLeftTreeData() {
      this.tableDefaultExpandedKeys = [];
      request
        .get('/dc/organization/base/getAllNode', {
          params: {
            userId: this.userId,
            orgType: this.type,
          },
        })
        .then((res) => {
          const data = res.data;
          const newCheckedData = [];
          data.forEach((ele) => {
            this.tableDefaultExpandedKeys.push(ele.id);
            newCheckedData.push(ele);
            if (ele.pid == null || ele.pid == '') {
              ele.pid = '001';
            }
            if (ele.sttm == null || ele.sttm == '') {
              ele.sttm = '';
            } else {
              ele.sttm = dateFormat(ele.sttm, 'yy-MM-dd');
            }
            if (ele.entm == null || ele.entm == '') {
              ele.entm = '';
            } else {
              ele.entm = dateFormat(ele.entm, 'yy-MM-dd');
            }
          });

          // 处理最低节点增加上层节点
          this.addUpNode(data);
          this.checkedData = newCheckedData;
          //debugger
          this.$emit('treeCheckedDataChange', {
            newCheckedArray: this.checkedData,
            changedItem: this.changedData,
            newStatus: true,
          });
          // 使用新的格式化树方法
          // _self.treeData = _self.getTreesNew(data);
        });
    },
    // 处理最低节点增加上层节点
    async addUpNode(data) {
      // 1.先获取所有id组成的数组并满足id的长度小于12的（12是最低节点）
      // 2.如果都是最低节点，那么就加上上层节点
      const arr = data
        .map((v) => {
          return v.id;
        })
        .filter((v, i) => v.length < 12);
      const ids = data
        .map((v) => {
          return v.pid;
        })
        .join();
      if (arr.length == 0 && ids.length != 0) {
        await request
          .get('/dc/organization/base/getAllNodeById', { params: { id: ids } })
          .then((res) => {
            const dataUp = res.data;
            dataUp.forEach((item, index) => {
              item.disabled = true;
            });
            data = data.concat(dataUp);
          })
          .catch((err) => {});
      }
      this.treeData = await this.getTreesNew(data);
      // console.log(JSON.stringify(this.treeData))
    },
    // 格式化树形数据
    getTrees(list, pId) {
      const items = {};
      // 获取每个节点的直属子节点，*记住是直属，不是所有子节点
      for (let i = 0; i < list.length; i++) {
        const key = list[i].parentId ? list[i].parentId : list[i].pid;
        if (items[key]) {
          items[key].push(list[i]);
        } else {
          items[key] = [];
          items[key].push(list[i]);
        }
      }
      return this.formatTree(items, pId);
    },
    getTreesNew(list) {
      // @wxcwater重写方法 适应多个树
      let highLevelLength = 99; // 预设最大节点id长度，目前最大应该为12，所以设置为99保证正常
      list.forEach((item, index) => {
        item['pidLength'] = item.pid && item.pid != '' ? item.pid.length : 0;
        if (highLevelLength > item.pidLength) {
          highLevelLength = item.pidLength;
        }
      });
      const heightLevelNode = [];
      list.forEach((item, index) => {
        if (highLevelLength >= item.pidLength) {
          heightLevelNode.push(item);
        }
      });
      list.forEach((item, index) => {
        heightLevelNode.forEach((pItem) => {
          this.addTreeNode(pItem, item);
        });
      });
      return heightLevelNode;
    },
    /** 利用递归格式化每个节点**/
    formatTree(items, pId) {
      const result = [];
      if (!items[pId]) {
        return result;
      }
      for (const t of items[pId]) {
        t.children = this.formatTree(items, t.id);
        result.push(t);
      }
      return result;
    },
    addTreeNode: function (treeNode, leafNode) {
      if (!Object.hasOwn(treeNode, 'children')) {
        treeNode['children'] = [];
      }
      if (leafNode.pid == treeNode.id) {
        treeNode.children.push(leafNode);
        return;
      }
      treeNode.children.forEach((item) => {
        this.addTreeNode(item, leafNode);
      });
    },
  },
};
</script>

<style scoped>
  .tree {
    overflow-y: auto;
    overflow-x: auto;
  }

  .a-tree {
    min-width: 100%;
    display: inline-block !important;
  }

  /*滚动条样式*/
  .tree::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  /*正常情况下滑块的样式*/
  .tree::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, .05);
    border-radius: 10px;
    -webkit-box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1);
  }

  /*鼠标悬浮在该类指向的控件上时滑块的样式*/
  .tree:hover::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, .2);
    border-radius: 10px;
    -webkit-box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1);
  }

  /*鼠标悬浮在滑块上时滑块的样式*/
  .tree::-webkit-scrollbar-thumb:hover {
    background-color: rgba(0, 0, 0, .4);
    -webkit-box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1);
  }

  /*正常时候的主干部分*/
  .tree::-webkit-scrollbar-track {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0);
    background-color: white;
  }

  /*鼠标悬浮在滚动条上的主干部分*/
  .tree::-webkit-scrollbar-track:hover {
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .4);
    background-color: rgba(0, 0, 0, .01);
  }
</style>
