"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.default = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _treeNode = _interopRequireDefault(require("./tree-node"));

var _utils = require("./utils.js");

var ROOT_ID = '-11';

var __vue_render__ = function __vue_render__() {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _vm.visibleTree ? _c('tree-node', {
    attrs: {
      "expandedList": _vm.expandedList,
      "checkedList": _vm.checkedList,
      "tree-data": _vm.treeData,
      "checkedId": _vm.checkedId,
      "id": _vm.id,
      "multiple": _vm.multiple
    },
    on: {
      "nodeClick": _vm.nodeClick,
      "nodeChecked": _vm.nodeChecked,
      "getItemCheckedStatus": _vm.getItemCheckedStatus
    },
    scopedSlots: _vm._u([{
      key: "treeNode",
      fn: function fn(ref) {
        var node = ref.node;
        var attrs = ref.attrs;
        return [_vm._t("treeNode", null, {
          "node": node,
          "attrs": attrs
        })];
      }
    }], null, true)
  }) : _vm._e();
};

var __vue_staticRenderFns__ = [];
var _default2 = {
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__,
  name: 'tree',
  components: {
    treeNode: _treeNode.default
  },
  props: {
    defaultCheckedKeys: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    treeId: {
      type: String,
      default: ''
    },
    defaultExpandedKeys: {
      type: Array,
      default: function _default() {
        return [];
      }
    },
    options: {
      type: Object
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data: function data() {
    this.treeData = []; // 树的数据不做响应式，减少性能开销

    return {
      checkedId: '',
      visibleTree: false,
      expandedList: [],
      checkedList: [],
      id: this.treeId
    };
  },
  created: function created() {
    this.openTree();
  },
  destroyed: function destroyed() {
    this.expandedList = [];
    this.checkedList = [];
  },
  watch: {
    checkedList: function checkedList() {
      this.multiple && this.$emit('node-checked', this.checkedList, this.treeData);
    }
  },
  methods: {
    getItemCheckedStatus: function getItemCheckedStatus(id) {
      var item = this.checkedList.find(function (ele) {
        return ele.id === id;
      });

      var _ref = item || {},
          checked = _ref.checked;

      return checked;
    },

    /*
      多选时，当选中顶级节点时，仅勾上展开的checkbox 否则由于数据太多会形成内存溢出 整棵树平铺出来为 8000+的长度数组
    */
    nodeChecked: function nodeChecked(item) {
      var _this = this;

      var that = this;
      item.checked = !item.checked;

      var _ref2 = item || {},
          id = _ref2.id,
          checked = _ref2.checked,
          _ref2$children = _ref2.children,
          children = _ref2$children === void 0 ? [] : _ref2$children,
          parentId = _ref2.parentId;

      var hasChildren = (0, _utils.hasArrLength)(children);
      var curIndex = this.checkedList.findIndex(function (ele) {
        return ele.id === id;
      });

      if (item.checked) {
        curIndex === -1 && this.checkedList.push({
          id: id,
          checked: checked
        }); // 如果存在子集，那么子集也全部勾上 递归勾上子集

        if (hasChildren) {
          var iter = function iter(item) {
            var id = item.id,
                itemChildren = item.children;
            item.checked = true;
            var itemIndex = that.checkedList.findIndex(function (x) {
              return x.id === id;
            });
            itemIndex === -1 && that.checkedList.push({
              id: id,
              checked: true
            }); // 如果展开了父级展开了才添加进去否则不做计算

            var isExpandSelf = that.expandedList.findIndex(function (expandedId) {
              return expandedId === id;
            });
            isExpandSelf > -1 && (0, _utils.hasArrLength)(itemChildren) && item.children.forEach(iter);
          };

          children.forEach(iter);
        }
      } else {
        curIndex > -1 && this.checkedList.splice(curIndex, 1);

        if (hasChildren) {
          var deleteFn = function deleteFn(data) {
            data.checked = false;
            var id = data.id,
                childChildren = data.children;

            var index = _this.checkedList.findIndex(function (ele) {
              return ele.id === id;
            });

            index > -1 && _this.checkedList.splice(index, 1);
            (0, _utils.hasArrLength)(childChildren) && data.children.forEach(deleteFn);
          };

          children.forEach(deleteFn);
        }
      }

      var setParentStatus = function setParentStatus(parentId) {
        var parentNode = (0, _utils.deepSearch)(parentId, _this.treeData);

        var parentNodeIndex = _this.checkedList.findIndex(function (ele) {
          return ele.id === parentId;
        });

        if (parentNode && (0, _utils.hasArrLength)(parentNode.children)) {
          var isAllChecked = parentNode.children.every(function (x) {
            return x.checked;
          });

          if (isAllChecked) {
            parentNode.checked = true;
            parentNodeIndex === -1 && _this.checkedList.push({
              checked: true,
              id: parentId
            });
          } else {
            parentNode.checked = false;

            var index = _this.checkedList.findIndex(function (item) {
              return item.id === parentId;
            });

            index > -1 && _this.checkedList.splice(index, 1);
          }
        }

        if (parentNode && parentNode.parentId) {
          setParentStatus(parentNode.parentId);
        }
      }; // 处理父级


      setParentStatus(parentId);
    },

    /*
      点击节点事件
     */
    nodeClick: function nodeClick(item) {
      var _this2 = this;

      this.checkedId = item.id;
      item.expanded = !item.expanded;
      var isExit = this.expandedList.findIndex(function (id) {
        return id === item.id;
      });

      if (item.expanded) {
        isExit === -1 && this.expandedList.push(item.id);
      } else {
        isExit > -1 && this.expandedList.splice(isExit, 1);
      }

      var isChecked = this.checkedList.findIndex(function (x) {
        return x.id === item.id;
      });
      var hasChildren = (0, _utils.hasArrLength)(item.children);

      if (hasChildren) {
        if (isChecked > -1) {
          // 如果父级展开时被选择， 那么子集也应该选中
          var iter = function iter(item) {
            var id = item.id,
                itemChildren = item.children;
            item.checked = true;

            var itemIndex = _this2.checkedList.findIndex(function (x) {
              return x.id === id;
            });

            itemIndex === -1 && _this2.checkedList.push({
              id: id,
              checked: true // item

            }); // 如果展开了父级展开了才添加进去否则不做计算

            var isExpand = _this2.checkedList.findIndex(function (expandedId) {
              return expandedId === item.parentId;
            });

            isExpand > -1 && (0, _utils.hasArrLength)(itemChildren) && item.children.forEach(iter);
          };

          item.children.forEach(iter);
        }
      }

      this.$emit('node-click', item);
    },

    /*
      hr.department.refactoring.get
      查询选中节点的路径
    */
    queryNodeDetail: function queryNodeDetail(id) {
      var _this3 = this;

      return (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
        var res;
        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.prev = 0;

                if (id) {
                  _context.next = 3;
                  break;
                }

                return _context.abrupt("return", {});

              case 3:
                _context.next = 5;
                return _this3.$http('hr.department.refactoring.get', 10179, {
                  id: id
                }, {
                  timeout: 30000
                });

              case 5:
                res = _context.sent;
                return _context.abrupt("return", res);

              case 9:
                _context.prev = 9;
                _context.t0 = _context["catch"](0);
                return _context.abrupt("return", {});

              case 12:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[0, 9]]);
      }))();
    },
    destroyedStatus: function destroyedStatus() {
      this.expandedList = [];
    },

    /*
      tree数据查询
    */
    queryTreeData: function queryTreeData() {
      var _this4 = this;

      return (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2() {
        var data;
        return _regenerator.default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                if (!(_this4.treeData && _this4.treeData.length)) {
                  _context2.next = 4;
                  break;
                }

                return _context2.abrupt("return", _this4.treeData);

              case 4:
                _this4.visibleTree = false;
                _this4.expandedList = [];
                _context2.next = 8;
                return _this4.$http('hr.department.refactoring.getSimplifyTreeWithAuth', 10179, {}, {
                  timeout: 30000
                });

              case 8:
                data = _context2.sent;
                return _context2.abrupt("return", data);

              case 10:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }))();
    },

    /*
      1. 打开弹窗时判断是否加载（有本地缓存的数据）如果没有再次查询数据
      2. 回显。滚动定位， 颜色标识
    */
    openTree: function openTree() {
      var _this5 = this;

      return (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee3() {
        var data;
        return _regenerator.default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _this5.expandedList = [];
                _context3.next = 3;
                return _this5.queryTreeData();

              case 3:
                data = _context3.sent;
                data && _this5.processingTreeData(data);

                if (_this5.multiple) {
                  _context3.next = 15;
                  break;
                }

                if (!_this5.defaultCheckedKeys.length) {
                  _context3.next = 12;
                  break;
                }

                if (!(_this5.defaultCheckedKeys[0] === _this5.checkedId)) {
                  _context3.next = 10;
                  break;
                }

                // 可能滚动过，但是没选择
                _this5.scrollToNode(_this5.defaultCheckedKeys[0]);

                return _context3.abrupt("return");

              case 10:
                _context3.next = 13;
                break;

              case 12:
                _this5.resetNodeStatus();

              case 13:
                _context3.next = 16;
                break;

              case 15:
                setTimeout(function () {
                  _this5.defaultCheckedKeys.forEach(function (id) {
                    var isExit = _this5.checkedList.findIndex(function (ele) {
                      return ele.id === id;
                    }); // 如果存在就不在添加了，减少递归次数


                    if (isExit === -1) {
                      var node = (0, _utils.deepSearch)(id, _this5.treeData);

                      _this5.nodeChecked(node);
                    }
                  });
                }, 200);

              case 16:
                _this5.$emit('updateTreeData', _this5.treeData);

              case 17:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }))();
    },
    // 滚动到指定的位置
    scrollToNode: function scrollToNode(id) {
      var _this6 = this;

      this.$nextTick(function () {
        var val = '#node' + id + _this6.treeId; // 可能存在多棵树的时候，这个时候需要添加唯一的标识，不然无法滚动到对应的节点，ID可能出现重复

        var dom = document.querySelector(val); // 没有就滚到第一个

        dom && (0, _utils.scrollParentToElement)(dom);
      });
    },
    resetNodeStatus: function resetNodeStatus() {
      // 如果不存在则滚动到顶级节点 并重置状态
      this.checkedId = '';
      this.expandedList = [];
      var id = this.treeData[0].id;
      this.treeData.forEach(function iter(ele) {
        // 其它的收起
        ele.expanded = ele.id === id;
        ele.checked = false;
        ele.children && ele.children.forEach(iter);
      }); // 滚动定位

      this.scrollToNode(ROOT_ID);
      this.$emit('node-click', null);
      this.$emit('updateTreeData', this.treeData);
    },

    /*
      设置某个节点的状态（包含父节点）
     */
    setNodeStatus: function setNodeStatus(id) {
      var _this7 = this;

      var node;
      this.checkedId = id;

      var iter = function iter(ele) {
        if (ele.id === id) {
          ele.expanded = true;
          node = ele;
        }

        if ((0, _utils.hasArrLength)(ele.children)) {
          ele.children.forEach(iter);
        }
      };

      this.treeData.forEach(iter); // 父级展开

      var fn = function fn(node) {
        _this7.treeData.forEach(function iter(x) {
          if (x.id === node.parentId) {
            x.expanded = true;
            fn(x);
          }

          if ((0, _utils.hasArrLength)(x.children)) {
            x.children.forEach(iter);
          }
        });
      };

      node && node.parentId && fn(node); // 滚动定位

      this.scrollToNode(id);
      node = null;
    },

    /*
      数据处理，添加expand
    */
    processingTreeData: function processingTreeData(res) {
      if (!res || !res.id) {
        return [];
      }

      var obj = (0, _extends2.default)({}, res, {
        expanded: true,
        checked: false
      });

      var fn = function fn(data, parentIdList) {
        if (!(0, _utils.hasArrLength)(data)) {
          return data;
        }

        data.forEach(function (ele) {
          ele.expanded = false;
          ele.checked = false;
          ele.parentIdList = [].concat(new Set(parentIdList));

          if ((0, _utils.hasArrLength)(ele.children)) {
            ele.children = fn(ele.children, [].concat(parentIdList, [ele.id]));
          }
        });
        return data;
      };

      obj.children = fn(obj.children, [obj.id]);
      this.treeData = [obj];
      obj = null;
      this.visibleTree = true;
    }
  }
};
exports.default = _default2;