import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import _Array$from from "@babel/runtime-corejs3/core-js-stable/array/from";
import _Symbol from "@babel/runtime-corejs3/core-js-stable/symbol";
import _getIteratorMethod from "@babel/runtime-corejs3/core-js/get-iterator-method";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _createClass from "@babel/runtime-corejs3/helpers/createClass";
import _classCallCheck from "@babel/runtime-corejs3/helpers/classCallCheck";
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof _Symbol && _getIteratorMethod(r) || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { var _context3; if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = _sliceInstanceProperty(_context3 = {}.toString.call(r)).call(_context3, 8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
import _Set from "@babel/runtime-corejs3/core-js-stable/set";
import _Map from "@babel/runtime-corejs3/core-js-stable/map";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
import isLeafNode from '../isLeafNode';
import { arrayUtils } from '../others';
import console from '../console';
var Wrapper = /*#__PURE__*/_createClass(function Wrapper(input) {
  _classCallCheck(this, Wrapper);
  _extends(this, input);
});
var TreeDataHelper = /*#__PURE__*/function () {
  function TreeDataHelper(opts) {
    var _this = this;
    _classCallCheck(this, TreeDataHelper);
    this.isDetached = function (node) {
      var _a, _b, _c;
      return (_c = (_b = (_a = _this.opts).isDetached) === null || _b === void 0 ? void 0 : _b.call(_a, node)) !== null && _c !== void 0 ? _c : false;
    };
    this.opts = opts;
    this.valueSet = new _Set(opts.value);
    this.initWrapperTree();
  }
  return _createClass(TreeDataHelper, [{
    key: "value",
    get: function get() {
      return this.opts.value;
    }
  }, {
    key: "initWrapperTree",
    value: function initWrapperTree() {
      var valueSet = new _Set(this.value);
      this.rootWrapper = new Wrapper({
        root: true,
        children: []
      });
      this.wrapperMap = new _Map();
      var getNodeValue = this.opts.getNodeValue;
      var isDetached = this.isDetached,
        wrapperMap = this.wrapperMap;
      dfs(this.rootWrapper, this.opts.tree, false);
      function dfs(parentWrapper, nodes, inheritParentChecked) {
        // allChildrenChecked 先默认设置为 true
        // dfs 过程中可能会更新 allChildrenChecked
        parentWrapper.allChildrenChecked = true;
        if (process.env.NODE_ENV !== 'production') {
          if (nodes.every(isDetached)) {
            console.warn('TreeDataHelper 检测到部分节点的下所有子节点均为 detached 状态，这将导致该节点变为「无效节点」', parentWrapper.node);
          }
        }
        var _iterator = _createForOfIteratorHelper(nodes),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var node = _step.value;
            var detached = isDetached(node);
            var exactChecked = valueSet.has(getNodeValue(node));
            if (exactChecked && !detached) {
              parentWrapper.anyDescendentsChecked = true;
            }
            var parentChecked = !detached && inheritParentChecked;
            var checked = exactChecked || parentChecked;
            var wrapper = new Wrapper({
              parent: parentWrapper,
              node: node,
              checked: checked,
              exactChecked: exactChecked,
              parentChecked: parentChecked,
              anyDescendentsChecked: checked,
              detached: detached
            });
            wrapperMap.set(getNodeValue(node), wrapper);
            parentWrapper.children.push(wrapper);
            if (!isLeafNode(node)) {
              wrapper.children = [];
              dfs(wrapper, node.children, checked);
              if (wrapper.anyDescendentsChecked && !detached) {
                parentWrapper.anyDescendentsChecked = true;
              }
              if (wrapper.allChildrenChecked) {
                wrapper.checked = true;
                // 当一个节点因为「子节点被全选」而变为 checked 时，我们需要更新子节点的 parentChecked 字段
                var _iterator2 = _createForOfIteratorHelper(wrapper.children),
                  _step2;
                try {
                  for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                    var child = _step2.value;
                    if (!child.detached) {
                      child.parentChecked = true;
                    }
                  }
                } catch (err) {
                  _iterator2.e(err);
                } finally {
                  _iterator2.f();
                }
              }
            }
            if (!wrapper.checked && !detached) {
              parentWrapper.allChildrenChecked = false;
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }
    }
  }, {
    key: "isIndeterminate",
    value: function isIndeterminate(nodeValue) {
      var wrapper = this.wrapperMap.get(nodeValue);
      return !wrapper.checked && wrapper.anyDescendentsChecked;
    }
  }, {
    key: "isChecked",
    value: function isChecked(nodeValue) {
      var wrapper = this.wrapperMap.get(nodeValue);
      return wrapper.checked;
    }
  }, {
    key: "getValueAfterCheck",
    value: function getValueAfterCheck(nodeValue) {
      if (this.isChecked(nodeValue)) {
        return this.getCleanValue();
      }
      var nextValue = arrayUtils.merge(this.value, [nodeValue]);
      return new TreeDataHelper(_extends(_extends({}, this.opts), {
        value: nextValue
      })).getCleanValue();
    }
  }, {
    key: "getValueAfterUncheck",
    value: function getValueAfterUncheck(nodeValue) {
      var _context;
      if (!this.isChecked(nodeValue)) {
        return this.getCleanValue();
      }
      var wrapper = this.wrapperMap.get(nodeValue);
      var getNodeValue = this.opts.getNodeValue;
      var appendArray = getAppendArray(wrapper);
      var removeSet = getRemoveSet(wrapper);
      var nextValue = arrayUtils.diff(_concatInstanceProperty(_context = this.value).call(_context, appendArray), removeSet);
      return new TreeDataHelper(_extends(_extends({}, this.opts), {
        value: nextValue
      })).getCleanValue();
      function getAppendArray(startWrapper) {
        var result = [];
        var current = startWrapper;
        while (current.parentChecked && !current.detached) {
          var _iterator3 = _createForOfIteratorHelper(current.parent.children),
            _step3;
          try {
            for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
              var sibling = _step3.value;
              if (sibling === current || sibling.exactChecked || sibling.detached) {
                continue;
              }
              result.push(getNodeValue(sibling.node));
            }
          } catch (err) {
            _iterator3.e(err);
          } finally {
            _iterator3.f();
          }
          current = current.parent;
        }
        return result;
      }
      function getRemoveSet(startWrapper) {
        var result = new _Set();
        var wrapper = startWrapper;
        // 不断向上收集选中的父节点
        while (true) {
          result.add(getNodeValue(wrapper.node));
          if (wrapper.detached || !wrapper.parentChecked) {
            break;
          }
          wrapper = wrapper.parent;
        }
        function dfs(wrappers) {
          if (wrappers == null) {
            return;
          }
          var _iterator4 = _createForOfIteratorHelper(wrappers),
            _step4;
          try {
            for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
              var _wrapper = _step4.value;
              if (_wrapper.detached || !_wrapper.checked) {
                continue;
              }
              result.add(getNodeValue(_wrapper.node));
              if (!isLeafNode(_wrapper) && _wrapper.anyDescendentsChecked) {
                dfs(_wrapper.children);
              }
            }
          } catch (err) {
            _iterator4.e(err);
          } finally {
            _iterator4.f();
          }
        }
        // 收集所有的子孙节点
        dfs(startWrapper.children);
        return result;
      }
    }
  }, {
    key: "getValueAfterToggle",
    value: function getValueAfterToggle(nodeValue) {
      if (this.isChecked(nodeValue)) {
        return this.getValueAfterUncheck(nodeValue);
      } else {
        return this.getValueAfterCheck(nodeValue);
      }
    }
  }, {
    key: "getNode",
    value: function getNode(nodeValue) {
      var _a;
      return (_a = this.wrapperMap.get(nodeValue)) === null || _a === void 0 ? void 0 : _a.node;
    }
  }, {
    key: "getCleanValue",
    value: function getCleanValue() {
      var _context2,
        _this2 = this;
      var _this$opts = this.opts,
        checkedStrategy = _this$opts.checkedStrategy,
        getNodeValue = _this$opts.getNodeValue;
      var result = _filterInstanceProperty(_context2 = this.value).call(_context2, function (nodeValue) {
        return !_this2.wrapperMap.has(nodeValue);
      });
      dfs(this.rootWrapper.children);
      return result;
      function dfs(wrappers) {
        var _iterator5 = _createForOfIteratorHelper(wrappers),
          _step5;
        try {
          for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
            var wrapper = _step5.value;
            if (wrapper.checked) {
              if (checkedStrategy === 'all') {
                result.push(getNodeValue(wrapper.node));
              } else if (checkedStrategy === 'parent') {
                if (!wrapper.parentChecked) {
                  result.push(getNodeValue(wrapper.node));
                }
              } else {
                // checkedStrategy === 'child'
                if (isLeafNode(wrapper)) {
                  result.push(getNodeValue(wrapper.node));
                }
              }
            }
            if (!isLeafNode(wrapper)) {
              dfs(wrapper.children);
            }
          }
        } catch (err) {
          _iterator5.e(err);
        } finally {
          _iterator5.f();
        }
      }
    }
  }]);
}();
export { TreeDataHelper as default };