/**
 * tdesign v0.39.1-alpha.1
 * (c) 2022 tdesign
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var get = require('lodash/get');
var table_utils = require('../utils.js');
var _common_js_log_log = require('../../_common/js/log/log.js');
require('@babel/runtime/helpers/typeof');
require('lodash/isFunction');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var get__default = /*#__PURE__*/_interopDefaultLegacy(get);

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

var TableTreeStore = /*#__PURE__*/function () {
  function TableTreeStore() {
    _classCallCheck__default["default"](this, TableTreeStore);

    _defineProperty__default["default"](this, "treeDataMap", /* @__PURE__ */new Map());

    this.treeDataMap = /* @__PURE__ */new Map();
  }

  _createClass__default["default"](TableTreeStore, [{
    key: "initialTreeStore",
    value: function initialTreeStore(dataSource, columns, keys) {
      var _this$treeDataMap;

      (_this$treeDataMap = this.treeDataMap) === null || _this$treeDataMap === void 0 ? void 0 : _this$treeDataMap.clear();
      initialTreeDataMap(this.treeDataMap, dataSource, columns[0], keys);
    }
  }, {
    key: "toggleExpandData",
    value: function toggleExpandData(p, dataSouce, keys) {
      var rowValue = get__default["default"](p.row, keys.rowKey);
      var r = this.treeDataMap.get(rowValue) || {
        row: p.row,
        rowIndex: p.rowIndex,
        expanded: false
      };
      r.rowIndex = p.rowIndex;
      r.expanded = !r.expanded;
      this.treeDataMap.set(rowValue, r);
      return this.updateExpandRow(r, dataSouce, keys);
    }
  }, {
    key: "updateExpandRow",
    value: function updateExpandRow(changeRow, dataSource, keys) {
      var row = changeRow.row,
          rowIndex = changeRow.rowIndex,
          expanded = changeRow.expanded;
      var treeDataMap = this.treeDataMap;
      var childrenNodes = get__default["default"](row, keys.childrenKey);
      if (!row || !childrenNodes) return;

      if (expanded) {
        updateChildrenRowState(treeDataMap, changeRow, expanded, keys);
        updateRowExpandLength(treeDataMap, row, childrenNodes.length, "expand", keys);
        dataSource.splice.apply(dataSource, [rowIndex + 1, 0].concat(childrenNodes));
      } else {
        updateChildrenRowState(treeDataMap, changeRow, expanded, keys);
        var len = changeRow.expandChildrenLength || childrenNodes.length;
        updateRowExpandLength(treeDataMap, row, -1 * len, "fold", keys);
        dataSource.splice(rowIndex + 1, len);
      }

      updateRowIndex(treeDataMap, dataSource, {
        rowKey: keys.rowKey,
        minRowIndex: rowIndex + 1
      });
      return dataSource;
    }
  }, {
    key: "getData",
    value: function getData(key) {
      return this.treeDataMap.get(key);
    }
  }, {
    key: "updateData",
    value: function updateData(key, newRowData, dataSource, keys) {
      var newKey = get__default["default"](newRowData, keys.rowKey);
      var rowState = this.treeDataMap.get(key);

      if (!rowState || rowState.rowIndex === -1) {
        updateRowData(dataSource, key, newRowData, {
          rowKey: keys.rowKey,
          childrenKey: keys.childrenKey
        });
        return;
      }

      var currentRowIndex = rowState.rowIndex;
      rowState.row = newRowData;
      this.treeDataMap.set(key, rowState);

      if (rowState.parent) {
        var siblings = get__default["default"](rowState.parent.row, keys.childrenKey);
        var index = siblings.findIndex(function (item) {
          return get__default["default"](item, keys.rowKey) === key;
        });
        siblings[index] = newRowData;
      }

      if (key !== newKey) {
        this.treeDataMap.set(newKey, rowState);
        this.treeDataMap["delete"](key);
      } else {
        this.treeDataMap.set(key, rowState);
      }

      return currentRowIndex;
    }
  }, {
    key: "remove",
    value: function remove(key, dataSource, keys) {
      var r = this.treeDataMap.get(key);

      if (r && r.rowIndex >= 0) {
        var removeNumber = (r.expandChildrenLength || 0) + 1;
        dataSource.splice(r.rowIndex, removeNumber);

        if (r.parent) {
          var siblings = get__default["default"](r.parent.row, keys.childrenKey);
          var index = siblings.findIndex(function (item) {
            return get__default["default"](item, keys.rowKey) === key;
          });
          siblings.splice(index, 1);
          updateRowExpandLength(this.treeDataMap, r.parent.row, -1 * removeNumber, "delete", {
            rowKey: keys.rowKey,
            childrenKey: keys.childrenKey
          });
        }

        this.treeDataMap["delete"](key);
        updateRowIndex(this.treeDataMap, dataSource, {
          minRowIndex: r.rowIndex,
          rowKey: keys.rowKey
        });
      } else {
        console.warn("TDesign Table Warn: Do not remove this node, which is not appreared.");
      }

      return dataSource;
    }
  }, {
    key: "appendTo",
    value: function appendTo(key, newData, dataSource, keys) {
      var state = this.treeDataMap.get(key);

      if (!state) {
        console.warn("TDesign Table Warn: ".concat(key, " is not exist."));
        return;
      }

      var newRowValue = get__default["default"](newData, keys.rowKey);

      if (this.treeDataMap.get(newRowValue)) {
        console.warn("TDesign Table Warn: Duplicated Key. ".concat(newRowValue, " is already exists."));
        return;
      }

      var children = get__default["default"](state.row, keys.childrenKey);
      var isShowNewNode = state.expanded || !(children !== null && children !== void 0 && children.length);
      var newState = {
        row: newData,
        level: state.level + 1,
        parent: state,
        path: _toConsumableArray__default["default"](state.path),
        expanded: false,
        expandChildrenLength: 0,
        rowIndex: isShowNewNode ? state.rowIndex + (state.expandChildrenLength || 0) + 1 : -1
      };
      newState.path = newState.path.concat(newState);

      if (children !== null && children !== void 0 && children.length) {
        state.row[keys.childrenKey].push(newData);
      } else {
        state.row[keys.childrenKey] = [newData];
        state.expanded = true;
      }

      this.treeDataMap.set(newRowValue, newState);

      if (isShowNewNode) {
        dataSource.splice(newState.rowIndex, 0, newData);
        updateRowExpandLength(this.treeDataMap, state.row, 1, "insert", {
          rowKey: keys.rowKey,
          childrenKey: keys.childrenKey
        });
        updateRowIndex(this.treeDataMap, dataSource, {
          minRowIndex: newState.rowIndex,
          rowKey: keys.rowKey
        });
      }

      return dataSource;
    }
  }]);

  return TableTreeStore;
}();
function initialTreeDataMap(treeDataMap, dataSource, column, keys) {
  for (var i = 0, len = dataSource.length; i < len; i++) {
    var item = dataSource[i];
    var rowValue = get__default["default"](item, keys.rowKey);
    var state = {
      row: item,
      rowIndex: i,
      expanded: false,
      level: 0,
      expandChildrenLength: 0,
      disabled: table_utils.isRowSelectedDisabled(column, item, i)
    };
    state.path = [state];
    treeDataMap.set(rowValue, state);
    var children = get__default["default"](item, keys.childrenKey);

    if (column.colKey === "row-select" && children !== null && children !== void 0 && children.length) {
      initialTreeDataMap(treeDataMap, children, column, keys);
    }
  }
}
function updateRowExpandLength(treeDataMap, row, distance, type, keys) {
  var tmp = row;

  while (tmp) {
    var _state$parent;

    var state = treeDataMap.get(get__default["default"](tmp, keys.rowKey));
    var expandLen = (state.expandChildrenLength || 0) + distance;
    state.expandChildrenLength = Math.max(0, expandLen);
    tmp = state === null || state === void 0 ? void 0 : (_state$parent = state.parent) === null || _state$parent === void 0 ? void 0 : _state$parent.row;
  }

  if (type === "fold") {
    clearRowExpandLength(treeDataMap, row, keys);
  }
}
function clearRowExpandLength(treeDataMap, row, keys) {
  var children = get__default["default"](row, keys.childrenKey);

  if (children !== null && children !== void 0 && children.length) {
    children.forEach(function (item) {
      var state = treeDataMap.get(get__default["default"](item, keys.rowKey));
      if (!state) return;
      state.expandChildrenLength = 0;
      clearRowExpandLength(treeDataMap, state.row, keys);
    });
  }
}
function updateChildrenRowState(treeDataMap, rowState, expanded, keys) {
  var row = rowState.row,
      _rowState$level = rowState.level,
      level = _rowState$level === void 0 ? 0 : _rowState$level,
      rowIndex = rowState.rowIndex;
  var childrenNodes = get__default["default"](row, keys.childrenKey);
  childrenNodes.forEach(function (item, kidRowIndex) {
    var rowValue = get__default["default"](item, keys.rowKey);
    var index = expanded ? rowIndex + 1 + kidRowIndex : -1;
    var curState = treeDataMap.get(rowValue);

    var newState = _objectSpread(_objectSpread({}, curState), {}, {
      row: item,
      rowIndex: index,
      expanded: false,
      parent: rowState,
      level: level + 1,
      path: []
    });

    newState.path = newState.path.concat(newState);
    treeDataMap.set(rowValue, newState);

    if (!expanded) {
      var children = get__default["default"](item, keys.childrenKey);

      if (children !== null && children !== void 0 && children.length) {
        updateChildrenRowState(treeDataMap, _objectSpread(_objectSpread({}, newState), {}, {
          rowIndex: -1,
          expanded: false
        }), expanded, keys);
      }
    }
  });
}
function updateRowData(data, key, newData, keys) {
  for (var i = 0, len = data.length; i < len; i++) {
    var item = data[i];

    if (get__default["default"](item, keys.rowKey) === key) {
      data[i] = newData;
      return;
    }

    var children = get__default["default"](item, keys.childrenKey) || [];

    if (children !== null && children !== void 0 && children.length) {
      updateRowData(children, key, newData, keys);
    }
  }
}
function updateRowIndex(treeDataMap, dataSource, extra) {
  var start = extra.minRowIndex || 0;
  var end = extra.maxRowIndex || dataSource.length;

  for (var rowIndex = start; rowIndex < end; rowIndex++) {
    var item = dataSource[rowIndex];
    var state = treeDataMap.get(get__default["default"](item, extra.rowKey));

    if (!state) {
      _common_js_log_log["default"].warn("Table", "tree map went wrong");
    }

    state.rowIndex = rowIndex;
  }
}

exports.clearRowExpandLength = clearRowExpandLength;
exports["default"] = TableTreeStore;
exports.initialTreeDataMap = initialTreeDataMap;
exports.updateChildrenRowState = updateChildrenRowState;
exports.updateRowData = updateRowData;
exports.updateRowExpandLength = updateRowExpandLength;
exports.updateRowIndex = updateRowIndex;
//# sourceMappingURL=tree-store.js.map
