"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
exports.getRowSelection = getRowSelection;
exports.mergeDefaultProps = mergeDefaultProps;

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

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

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

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

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

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

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

var _tslib = require("tslib");

var _react = _interopRequireDefault(require("react"));

var _mobx = require("mobx");

var _isString = _interopRequireDefault(require("lodash/isString"));

var _isNumber = _interopRequireDefault(require("lodash/isNumber"));

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _isUndefined = _interopRequireDefault(require("lodash/isUndefined"));

var _sortBy = _interopRequireDefault(require("lodash/sortBy"));

var _debounce = _interopRequireDefault(require("lodash/debounce"));

var _isNil = _interopRequireDefault(require("lodash/isNil"));

var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject"));

var _dataset = require("choerodon-ui/dataset");

var _enum = require("../../../lib/_util/enum");

var _UnitConvertor = require("../../../lib/_util/UnitConvertor");

var _CustomizationColumnHeader = _interopRequireDefault(require("./customization-settings/CustomizationColumnHeader"));

var _customizationSettings = _interopRequireDefault(require("./customization-settings"));

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

var _Column = _interopRequireDefault(require("./Column"));

var _autobind = _interopRequireDefault(require("../_util/autobind"));

var _localeContext = require("../locale-context");

var _enum2 = require("../table/enum");

function getRowSelection(props) {
  return props.rowSelection || {};
}

function mergeDefaultProps(originalColumns, customizedColumns) {
  var parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  var defaultKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [0];
  var columnSort = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
    left: 0,
    center: 0,
    right: 0
  };
  var columns = [];
  var leftColumns = [];
  var rightColumns = [];
  originalColumns.forEach(function (column) {
    if ((0, _isPlainObject["default"])(column)) {
      var newColumn = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _Column["default"].defaultProps), column);

      if ((0, _isNil["default"])((0, _utils.getColumnKey)(newColumn))) {
        newColumn.key = "anonymous-".concat(defaultKey[0]++);
      }

      var children = newColumn.children;

      if (customizedColumns) {
        var customized = customizedColumns[(0, _utils.getColumnKey)(newColumn).toString()];

        if (customized) {
          var width = customized.width;

          if (width && _dataset.math.isBigNumber(width)) {
            customized.width = width.toNumber();
          }

          (0, _extends2["default"])(newColumn, customized);
        }
      }

      if (parent) {
        newColumn.fixed = parent.fixed;
      }

      if (children) {
        // @ts-ignore
        var childrenColumns = mergeDefaultProps(children, customizedColumns, newColumn, defaultKey);
        newColumn.children = childrenColumns;
      }

      if (parent || !newColumn.fixed) {
        if (newColumn.sort === undefined) {
          newColumn.sort = columnSort.center;
        }

        columnSort.center++;
        columns.push(newColumn);
      } else if (newColumn.fixed === true || newColumn.fixed === _enum2.ColumnLock.left) {
        if (newColumn.sort === undefined) {
          newColumn.sort = columnSort.left;
        }

        columnSort.left++;
        leftColumns.push(newColumn);
      } else {
        if (newColumn.sort === undefined) {
          newColumn.sort = columnSort.right;
        }

        columnSort.right++;
        rightColumns.push(newColumn);
      }
    }
  }, []);

  if (parent) {
    return (0, _sortBy["default"])(columns, function (_ref) {
      var sort = _ref.sort;
      return sort;
    });
  }

  return [].concat((0, _toConsumableArray2["default"])((0, _sortBy["default"])(leftColumns, function (_ref2) {
    var sort = _ref2.sort;
    return sort;
  })), (0, _toConsumableArray2["default"])((0, _sortBy["default"])(columns, function (_ref3) {
    var sort = _ref3.sort;
    return sort;
  })), (0, _toConsumableArray2["default"])((0, _sortBy["default"])(rightColumns, function (_ref4) {
    var sort = _ref4.sort;
    return sort;
  })));
}

var TableStore = /*#__PURE__*/function () {
  function TableStore(node) {
    var _this = this;

    (0, _classCallCheck2["default"])(this, TableStore);
    this.highlightRowIndexs = [];
    this.checkboxPropsCache = {};
    this.saveCustomizedDebounce = (0, _debounce["default"])(this.saveCustomized, 1000);

    this.setCheckboxPropsCache = function (cache) {
      return _this.checkboxPropsCache = cache;
    };

    (0, _mobx.runInAction)(function () {
      _this.node = node;
      _this.rowZIndex = [];
      _this.customizedActiveKey = ['columns'];
      _this.tempCustomized = {
        columns: {}
      };
      _this.customized = {
        columns: {}
      };
      _this.selectedRowKeys = getRowSelection(_this.node.props).selectedRowKeys || [];
      _this.selectionDirty = false;

      if (_this.customizable) {
        _this.loadCustomized().then(_this.handleLoadCustomized);
      }
    });
  }

  (0, _createClass2["default"])(TableStore, [{
    key: "queryBar",
    get: function get() {
      return this.node.props.queryBar;
    }
    /**
     * 表头支持编辑
     */

  }, {
    key: "columnTitleEditable",
    get: function get() {
      if ('columnTitleEditable' in this.node.props) {
        return this.node.props.columnTitleEditable;
      }

      return this.getConfig('performanceTableColumnTitleEditable') === true;
    }
  }, {
    key: "dataSet",
    get: function get() {
      var queryBar = this.queryBar;

      if (queryBar) {
        return queryBar.dataSet;
      }
    }
  }, {
    key: "tableColumnResizeTrigger",
    get: function get() {
      return this.getConfig('tableColumnResizeTrigger');
    } // @computed
    // get selectedRowKeys(): string[] {
    //   const { queryBar } = this.node.props;
    //   return queryBar && queryBar.dataSet;
    // }

  }, {
    key: "loadCustomized",
    value: function () {
      var _loadCustomized = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
        var _this2 = this;

        var customizedCode, tableCustomizedLoad, customized;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                customizedCode = this.node.props.customizedCode;

                if (!(this.customizable && customizedCode)) {
                  _context.next = 12;
                  break;
                }

                tableCustomizedLoad = this.getConfig('tableCustomizedLoad') || this.getConfig('customizedLoad');
                (0, _mobx.runInAction)(function () {
                  _this2.loading = true;
                });
                _context.prev = 4;
                _context.next = 7;
                return tableCustomizedLoad(customizedCode, 'PerformanceTable');

              case 7:
                customized = _context.sent;
                (0, _mobx.runInAction)(function () {
                  _this2.customized = (0, _objectSpread2["default"])({
                    columns: {}
                  }, customized);
                });

              case 9:
                _context.prev = 9;
                (0, _mobx.runInAction)(function () {
                  _this2.loading = false;
                });
                return _context.finish(9);

              case 12:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this, [[4,, 9, 12]]);
      }));

      function loadCustomized() {
        return _loadCustomized.apply(this, arguments);
      }

      return loadCustomized;
    }()
  }, {
    key: "updateProps",
    value: function updateProps(props, node) {
      this.node = node;
      this.originalColumns = props.columns;
      this.originalChildren = props.children;

      if (this.customizable && props.columns) {
        this.loadCustomized().then(this.handleLoadCustomized);
      }
    }
  }, {
    key: "prefixCls",
    get: function get() {
      var classPrefix = this.node.props.classPrefix;
      return classPrefix;
    }
  }, {
    key: "proPrefixCls",
    get: function get() {
      return this.node.context.getProPrefixCls('table');
    }
  }, {
    key: "columnHideable",
    get: function get() {
      if ('columnHideable' in this.node.props) {
        return this.node.props.columnHideable;
      }

      return this.getConfig('performanceTableColumnHideable') !== false;
    }
  }, {
    key: "customizable",
    get: function get() {
      var customizedCode = this.node.props.customizedCode;

      if (customizedCode && (this.columnTitleEditable || this.columnDraggable || this.columnHideable)) {
        if ('customizable' in this.node.props) {
          return this.node.props.customizable;
        }

        return this.getConfig('performanceTableCustomizable') || this.node.context.getCustomizable('PerformanceTable');
      }

      return false;
    }
  }, {
    key: "autoHeight",
    get: function get() {
      var autoHeight = this.node.props.autoHeight;

      if ((0, _isUndefined["default"])(autoHeight)) {
        var config = this.getConfig('performanceTableAutoHeight');

        if ((0, _isObject["default"])(config)) {
          return (0, _objectSpread2["default"])({
            type: _enum2.TableAutoHeightType.minHeight,
            diff: 0
          }, config);
        }

        return !!config;
      } else if ((0, _isObject["default"])(autoHeight)) {
        return {
          type: autoHeight.type || _enum2.TableAutoHeightType.minHeight,
          diff: autoHeight.diff || 0
        };
      }

      return !!autoHeight;
    }
  }, {
    key: "heightType",
    get: function get() {
      var tempHeightType = (0, _mobx.get)(this.tempCustomized, 'heightType');

      if (tempHeightType !== undefined) {
        return tempHeightType;
      }

      var heightType = this.customized.heightType;

      if (heightType !== undefined) {
        return heightType;
      }

      return this.originalHeightType;
    }
  }, {
    key: "originalHeightType",
    get: function get() {
      var _this$node$props = this.node.props,
          height = _this$node$props.height,
          autoHeight = _this$node$props.autoHeight;

      if (autoHeight) {
        return _enum2.TableHeightType.flex;
      }

      if (height) {
        if ((0, _isString["default"])(height) && (0, _UnitConvertor.isCalcSize)(height)) {
          return _enum2.TableHeightType.flex;
        }

        if ((0, _isNumber["default"])((0, _UnitConvertor.toPx)(height))) {
          return _enum2.TableHeightType.fixed;
        }
      }

      return _enum2.TableHeightType.auto;
    }
  }, {
    key: "openCustomizationModal",
    value: function openCustomizationModal(modal) {
      var customizedCode = this.node.props.customizedCode;
      var modalProps = {
        drawer: true,
        size: _enum.Size.small,
        title: (0, _localeContext.$l)('Table', 'customization_settings'),
        children: /*#__PURE__*/_react["default"].createElement(_customizationSettings["default"], null),
        bodyStyle: {
          overflow: 'hidden auto',
          padding: 0
        }
      };

      if (customizedCode) {
        modalProps.okText = (0, _localeContext.$l)('Table', 'save_button');
      }

      modal.open(modalProps);
    }
  }, {
    key: "customizedColumnHeader",
    value: function customizedColumnHeader() {
      return /*#__PURE__*/_react["default"].createElement(_CustomizationColumnHeader["default"], {
        onHeaderClick: this.openCustomizationModal
      });
    }
  }, {
    key: "initColumns",
    value: function initColumns() {
      var customized = this.customized,
          customizable = this.customizable;
      var _this$node$props$colu = this.node.props.columns,
          columns = _this$node$props$colu === void 0 ? [] : _this$node$props$colu;
      var customizedColumns = customizable ? customized.columns : undefined;
      this.originalColumns = mergeDefaultProps(columns, customizedColumns);
      this.node._cacheCells = null;
      this.node.forceUpdate();
    }
  }, {
    key: "handleLoadCustomized",
    value: function handleLoadCustomized() {
      this.initColumns();
    }
  }, {
    key: "changeCustomizedColumnValue",
    value: function changeCustomizedColumnValue(columnKey, value) {
      var columns = this.customized.columns;
      var oldCustomized = (0, _mobx.get)(columns, columnKey);
      (0, _mobx.set)(columns, columnKey, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, oldCustomized), value));
      this.saveCustomizedDebounce();
    }
  }, {
    key: "saveCustomized",
    value: function saveCustomized(customized) {
      if (this.customizable) {
        var customizedCode = this.node.props.customizedCode;

        if (customized) {
          this.customized = customized;
        }

        this.node.forceUpdate();

        if (customizedCode) {
          var tableCustomizedSave = this.getConfig('tableCustomizedSave') || this.getConfig('customizedSave');
          tableCustomizedSave(customizedCode, this.customized, 'PerformanceTable');
        }
      }
    }
  }, {
    key: "columnDraggable",
    get: function get() {
      if ('columnDraggable' in this.node.props) {
        return this.node.props.columnDraggable;
      }

      return this.getConfig('performanceTableColumnDraggable') === true;
    }
  }, {
    key: "getConfig",
    value: function getConfig(key) {
      return this.node.context.getConfig(key);
    }
  }]);
  return TableStore;
}();

exports["default"] = TableStore;
(0, _tslib.__decorate)([_mobx.observable], TableStore.prototype, "props", void 0);
(0, _tslib.__decorate)([_mobx.observable], TableStore.prototype, "originalColumns", void 0);
(0, _tslib.__decorate)([_mobx.observable], TableStore.prototype, "customizedActiveKey", void 0);
(0, _tslib.__decorate)([_mobx.observable], TableStore.prototype, "tempCustomized", void 0);
(0, _tslib.__decorate)([_mobx.observable], TableStore.prototype, "customized", void 0);
(0, _tslib.__decorate)([_mobx.observable], TableStore.prototype, "totalHeight", void 0);
(0, _tslib.__decorate)([_mobx.observable], TableStore.prototype, "height", void 0);
(0, _tslib.__decorate)([_mobx.observable], TableStore.prototype, "loading", void 0);
(0, _tslib.__decorate)([_mobx.observable], TableStore.prototype, "rowZIndex", void 0);
(0, _tslib.__decorate)([_mobx.observable], TableStore.prototype, "selectedRowKeys", void 0);
(0, _tslib.__decorate)([_mobx.computed], TableStore.prototype, "columnTitleEditable", null);
(0, _tslib.__decorate)([_mobx.action], TableStore.prototype, "updateProps", null);
(0, _tslib.__decorate)([_mobx.computed], TableStore.prototype, "prefixCls", null);
(0, _tslib.__decorate)([_mobx.computed], TableStore.prototype, "proPrefixCls", null);
(0, _tslib.__decorate)([_mobx.computed], TableStore.prototype, "columnHideable", null);
(0, _tslib.__decorate)([_mobx.computed], TableStore.prototype, "customizable", null);
(0, _tslib.__decorate)([_mobx.computed], TableStore.prototype, "autoHeight", null);
(0, _tslib.__decorate)([_mobx.computed], TableStore.prototype, "heightType", null);
(0, _tslib.__decorate)([_mobx.computed], TableStore.prototype, "originalHeightType", null);
(0, _tslib.__decorate)([_autobind["default"], _mobx.action], TableStore.prototype, "openCustomizationModal", null);
(0, _tslib.__decorate)([_autobind["default"]], TableStore.prototype, "customizedColumnHeader", null);
(0, _tslib.__decorate)([_mobx.action], TableStore.prototype, "initColumns", null);
(0, _tslib.__decorate)([_autobind["default"], _mobx.action], TableStore.prototype, "handleLoadCustomized", null);
(0, _tslib.__decorate)([_mobx.action], TableStore.prototype, "changeCustomizedColumnValue", null);
(0, _tslib.__decorate)([_mobx.action], TableStore.prototype, "saveCustomized", null);
(0, _tslib.__decorate)([_mobx.computed], TableStore.prototype, "columnDraggable", null);
(0, _tslib.__decorate)([_autobind["default"]], TableStore.prototype, "getConfig", null);
//# sourceMappingURL=TableStore.js.map
