"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

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

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

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

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

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

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

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

var _reactBeautifulDnd = require("react-beautiful-dnd");

var _mobxReactLite = require("mobx-react-lite");

var _enum = require("choerodon-ui/pro/lib/data-set/enum");

var _pick = _interopRequireDefault(require("lodash/pick"));

var _icon = _interopRequireDefault(require("../../../../lib/icon"));

var _popover = _interopRequireDefault(require("../../../../lib/popover"));

var _tag = _interopRequireDefault(require("../../../../lib/tag"));

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

var _DataSet = _interopRequireDefault(require("../../data-set/DataSet"));

var _select = _interopRequireDefault(require("../../select"));

var _selectBox = _interopRequireDefault(require("../../select-box"));

var _button = _interopRequireDefault(require("../../button"));

var _interface = require("../../button/interface");

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

var _BoardContext = _interopRequireDefault(require("../../board/BoardContext"));

var Option = _selectBox["default"].Option;

var CombineSort = function CombineSort(props) {
  var dataSet = props.dataSet,
      prefixCls = props.prefixCls,
      sortableFieldNames = props.sortableFieldNames;
  var fields = dataSet.fields,
      combineSort = dataSet.props.combineSort;

  var _useState = (0, _react.useState)(false),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      visible = _useState2[0],
      setVisible = _useState2[1];

  var sortPrefixCls = "".concat(prefixCls, "-combine-sort");

  var _useContext = (0, _react.useContext)(_BoardContext["default"]),
      customizedDS = _useContext.customizedDS,
      saveCustomized = _useContext.saveCustomized,
      customizedCode = _useContext.customizedCode,
      getConfig = _useContext.getConfig;

  var customizedLoad = getConfig('customizedLoad');
  var sortFieldOptions = (0, _react.useMemo)(function () {
    var sortFieldData = [];

    if (fields && sortableFieldNames && sortableFieldNames.length > 0) {
      fields.forEach(function (field) {
        if (sortableFieldNames.includes(field.name)) {
          sortFieldData.push({
            value: field.name,
            meaning: field.get('label') || field.name
          });
        }
      });
    }

    return new _DataSet["default"]({
      autoQuery: false,
      autoCreate: false,
      paging: false,
      fields: [{
        name: 'value',
        type: _enum.FieldType.string
      }, {
        name: 'meaning',
        type: _enum.FieldType.string
      }],
      data: sortFieldData
    });
  }, [fields, sortableFieldNames]);
  var sortDS = (0, _react.useMemo)(function () {
    var _dataSet$combineSortF = dataSet.combineSortFieldNames,
        combineSortFieldNames = _dataSet$combineSortF === void 0 ? new Map() : _dataSet$combineSortF;
    var data = [];
    combineSortFieldNames.forEach(function (sortOrder, fieldName) {
      var record = sortFieldOptions.find(function (record) {
        return record.get('value') === fieldName;
      });

      if (record) {
        var field = dataSet.getField(fieldName);
        data.push({
          sortName: fieldName,
          order: sortOrder || field && field.order || _enum.SortOrder.asc
        });
      }
    });
    return new _DataSet["default"]({
      forceValidate: true,
      autoQuery: false,
      autoCreate: true,
      paging: false,
      fields: [{
        name: 'sortName',
        type: _enum.FieldType.string,
        options: sortFieldOptions
      }, {
        name: 'order',
        type: _enum.FieldType.string,
        defaultValue: _enum.SortOrder.asc
      }],
      data: data,
      events: {
        update: function update(_ref) {
          var dataSet = _ref.dataSet;

          if (customizedDS && customizedDS.current) {
            customizedDS.current.set('combineSort', dataSet.toData());
          }
        },
        remove: function remove(_ref2) {
          var dataSet = _ref2.dataSet;

          if (customizedDS && customizedDS.current) {
            customizedDS.current.set('combineSort', dataSet.toData());
          }
        }
      }
    });
  }, [sortFieldOptions, dataSet, dataSet.combineSortFieldNames, visible]); // 加载 board 组件非初始列表视图下的多列排序数据及objectVersionNumber

  var loadDetail = (0, _react.useCallback)( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
    var res, dataJson;
    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (!(customizedDS && customizedDS.current && customizedDS.current.get('id') !== '__DEFAULT__')) {
              _context.next = 5;
              break;
            }

            _context.next = 3;
            return customizedLoad(customizedCode, 'Board', {
              type: 'detail',
              id: customizedDS.current.get('id')
            });

          case 3:
            res = _context.sent;

            try {
              dataJson = res.dataJson ? (0, _pick["default"])(JSON.parse(res.dataJson), ['columns', 'combineSort', 'defaultFlag', 'height', 'heightDiff', 'viewName']) : {};
              sortDS.loadData(dataJson.combineSort);
              customizedDS.current.set({
                objectVersionNumber: res.objectVersionNumber,
                dataJson: dataJson
              });
            } catch (error) {
              (0, _utils.warning)(false, error.message);
            }

          case 5:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  })), []);

  var optionsFilter = function optionsFilter(record) {
    return sortDS.every(function (sortRecord) {
      return sortRecord.get('sortName') !== record.get('value');
    });
  };

  var onVisibleChange = function onVisibleChange(visible) {
    if (!visible) {
      sortDS.reset();
    }

    setVisible(visible);

    if (visible) {
      loadDetail();
    }
  };

  var handleCancel = function handleCancel() {
    sortDS.reset();
    setVisible(false);
  };

  var handleConfirm = function handleConfirm() {
    sortDS.validate().then( /*#__PURE__*/function () {
      var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(result) {
        var records, sortInfo, isDefault, res;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                if (!result) {
                  _context2.next = 12;
                  break;
                }

                records = sortDS.filter(function (r) {
                  return r.get('sortName') && r.get('order');
                });
                sortInfo = new Map();
                records.forEach(function (record) {
                  sortInfo.set(record.get('sortName'), record.get('order'));
                });
                isDefault = customizedDS && customizedDS.current ? customizedDS.current.get('id') === '__DEFAULT__' : true;

                if (!(customizedDS && customizedDS.current && !isDefault)) {
                  _context2.next = 10;
                  break;
                }

                _context2.next = 8;
                return saveCustomized(customizedDS.current.toData());

              case 8:
                res = _context2.sent;
                customizedDS.current.set('objectVersionNumber', res.objectVersionNumber);

              case 10:
                dataSet.sort(sortInfo);
                setVisible(false);

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

      return function (_x) {
        return _ref4.apply(this, arguments);
      };
    }());
  };

  var onDragEnd = (0, _react.useCallback)(function (result) {
    if (result.destination) {
      sortDS.move(result.source.index, result.destination.index);
    }
  }, [sortDS.data]);

  var SortDragItem = function SortDragItem(_ref5) {
    var record = _ref5.record,
        index = _ref5.index;
    var key = record.key;
    return /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.Draggable, {
      draggableId: String(key),
      index: record.index
    }, function (pro, snapshot) {
      return /*#__PURE__*/_react["default"].createElement("span", (0, _extends2["default"])({
        ref: pro.innerRef
      }, pro.draggableProps, {
        className: "".concat(sortPrefixCls, "-list-item").concat(snapshot.isDragging ? " ".concat(sortPrefixCls, "-list-item-dragging") : '')
      }), /*#__PURE__*/_react["default"].createElement("span", (0, _extends2["default"])({}, pro.dragHandleProps, {
        className: "".concat(sortPrefixCls, "-list-item-drag")
      }), /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "baseline-drag_indicator"
      })), /*#__PURE__*/_react["default"].createElement("span", {
        className: "".concat(sortPrefixCls, "-list-item-index")
      }, /*#__PURE__*/_react["default"].createElement(_tag["default"], null, index + 1)), /*#__PURE__*/_react["default"].createElement(_select["default"], {
        placeholder: (0, _localeContext.$l)('Table', 'please_select_column'),
        className: "".concat(sortPrefixCls, "-list-item-sortName"),
        record: record,
        name: "sortName",
        optionsFilter: optionsFilter,
        notFoundContent: (0, _localeContext.$l)('Table', 'no_save_filter'),
        clearButton: false
      }), /*#__PURE__*/_react["default"].createElement(_selectBox["default"], {
        record: record,
        name: "order",
        className: "".concat(sortPrefixCls, "-list-item-sortOrder")
      }, /*#__PURE__*/_react["default"].createElement(Option, {
        value: _enum.SortOrder.asc
      }, (0, _localeContext.$l)('Table', 'ascending')), /*#__PURE__*/_react["default"].createElement(Option, {
        value: _enum.SortOrder.desc
      }, (0, _localeContext.$l)('Table', 'descending'))), /*#__PURE__*/_react["default"].createElement(_button["default"], {
        className: "".concat(sortPrefixCls, "-list-item-delete"),
        icon: 'delete_black-o',
        funcType: _interface.FuncType.link,
        color: _interface.ButtonColor.primary,
        onClick: function onClick() {
          return sortDS["delete"](record, false);
        }
      }));
    });
  };

  var popupContent = (0, _react.useMemo)(function () {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(sortPrefixCls, "-content")
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(sortPrefixCls, "-body")
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(sortPrefixCls, "-list-container")
    }, /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.DragDropContext, {
      onDragEnd: onDragEnd
    }, /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.Droppable, {
      droppableId: "combine-sort",
      direction: "vertical"
    }, function (provided) {
      return /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
        ref: provided.innerRef
      }, provided.droppableProps, {
        className: "".concat(sortPrefixCls, "-list")
      }), sortDS.map(function (record, index) {
        var key = record.key;
        return /*#__PURE__*/_react["default"].createElement(SortDragItem, {
          key: key,
          record: record,
          index: index
        });
      }), provided.placeholder);
    }))), /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(sortPrefixCls, "-add-button")
    }, /*#__PURE__*/_react["default"].createElement(_button["default"], {
      funcType: _interface.FuncType.link,
      icon: "add",
      onClick: function onClick() {
        return sortDS.create();
      },
      color: _interface.ButtonColor.primary,
      disabled: sortDS.length >= sortFieldOptions.length
    }, (0, _localeContext.$l)('Table', 'add_sort')))), /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(sortPrefixCls, "-footer")
    }, /*#__PURE__*/_react["default"].createElement(_button["default"], {
      onClick: handleCancel
    }, (0, _localeContext.$l)('Modal', 'cancel')), /*#__PURE__*/_react["default"].createElement(_button["default"], {
      onClick: handleConfirm,
      color: _interface.ButtonColor.primary
    }, (0, _localeContext.$l)('Modal', 'ok'))));
  }, [onDragEnd, sortFieldOptions.data, sortDS.data]);

  if (!combineSort || !sortableFieldNames || sortableFieldNames.length === 0) {
    return null;
  }

  return /*#__PURE__*/_react["default"].createElement(_popover["default"], {
    trigger: "click",
    overlayClassName: "".concat(sortPrefixCls, "-popover"),
    title: (0, _localeContext.$l)('Table', 'custom_sort'),
    content: popupContent,
    visible: visible,
    onVisibleChange: onVisibleChange,
    placement: "bottomLeft"
  }, /*#__PURE__*/_react["default"].createElement(_button["default"], {
    icon: "paixu-xia",
    funcType: _interface.FuncType.link,
    color: _interface.ButtonColor.primary,
    className: "".concat(sortPrefixCls, "-trigger-button")
  }));
};

CombineSort.displayName = 'CombineSort';

var _default = (0, _mobxReactLite.observer)(CombineSort);

exports["default"] = _default;
//# sourceMappingURL=CombineSort.js.map
