import _extends from "@babel/runtime/helpers/extends";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { useMemo, useState, useCallback, useContext } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import { observer } from 'mobx-react-lite';
import { FieldType, SortOrder } from 'choerodon-ui/pro/lib/data-set/enum';
import pick from 'lodash/pick';
import Icon from '../../../../es/icon';
import Popover from '../../../../es/popover';
import Tag from '../../../../es/tag';
import { warning } from 'choerodon-ui/dataset/utils';
import DataSet from '../../data-set/DataSet';
import Select from '../../select';
import SelectBox from '../../select-box';
import Button from '../../button';
import { FuncType, ButtonColor } from '../../button/interface';
import { $l } from '../../locale-context';
import BoardContext from '../../board/BoardContext';
var Option = SelectBox.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 = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      visible = _useState2[0],
      setVisible = _useState2[1];

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

  var _useContext = useContext(BoardContext),
      customizedDS = _useContext.customizedDS,
      saveCustomized = _useContext.saveCustomized,
      customizedCode = _useContext.customizedCode,
      getConfig = _useContext.getConfig;

  var customizedLoad = getConfig('customizedLoad');
  var sortFieldOptions = 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({
      autoQuery: false,
      autoCreate: false,
      paging: false,
      fields: [{
        name: 'value',
        type: FieldType.string
      }, {
        name: 'meaning',
        type: FieldType.string
      }],
      data: sortFieldData
    });
  }, [fields, sortableFieldNames]);
  var sortDS = 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 || SortOrder.asc
        });
      }
    });
    return new DataSet({
      forceValidate: true,
      autoQuery: false,
      autoCreate: true,
      paging: false,
      fields: [{
        name: 'sortName',
        type: FieldType.string,
        options: sortFieldOptions
      }, {
        name: 'order',
        type: FieldType.string,
        defaultValue: 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 = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var res, dataJson;
    return _regeneratorRuntime.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 ? pick(JSON.parse(res.dataJson), ['columns', 'combineSort', 'defaultFlag', 'height', 'heightDiff', 'viewName']) : {};
              sortDS.loadData(dataJson.combineSort);
              customizedDS.current.set({
                objectVersionNumber: res.objectVersionNumber,
                dataJson: dataJson
              });
            } catch (error) {
              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 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(result) {
        var records, sortInfo, isDefault, res;
        return _regeneratorRuntime.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 = 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.createElement(Draggable, {
      draggableId: String(key),
      index: record.index
    }, function (pro, snapshot) {
      return /*#__PURE__*/React.createElement("span", _extends({
        ref: pro.innerRef
      }, pro.draggableProps, {
        className: "".concat(sortPrefixCls, "-list-item").concat(snapshot.isDragging ? " ".concat(sortPrefixCls, "-list-item-dragging") : '')
      }), /*#__PURE__*/React.createElement("span", _extends({}, pro.dragHandleProps, {
        className: "".concat(sortPrefixCls, "-list-item-drag")
      }), /*#__PURE__*/React.createElement(Icon, {
        type: "baseline-drag_indicator"
      })), /*#__PURE__*/React.createElement("span", {
        className: "".concat(sortPrefixCls, "-list-item-index")
      }, /*#__PURE__*/React.createElement(Tag, null, index + 1)), /*#__PURE__*/React.createElement(Select, {
        placeholder: $l('Table', 'please_select_column'),
        className: "".concat(sortPrefixCls, "-list-item-sortName"),
        record: record,
        name: "sortName",
        optionsFilter: optionsFilter,
        notFoundContent: $l('Table', 'no_save_filter'),
        clearButton: false
      }), /*#__PURE__*/React.createElement(SelectBox, {
        record: record,
        name: "order",
        className: "".concat(sortPrefixCls, "-list-item-sortOrder")
      }, /*#__PURE__*/React.createElement(Option, {
        value: SortOrder.asc
      }, $l('Table', 'ascending')), /*#__PURE__*/React.createElement(Option, {
        value: SortOrder.desc
      }, $l('Table', 'descending'))), /*#__PURE__*/React.createElement(Button, {
        className: "".concat(sortPrefixCls, "-list-item-delete"),
        icon: 'delete_black-o',
        funcType: FuncType.link,
        color: ButtonColor.primary,
        onClick: function onClick() {
          return sortDS["delete"](record, false);
        }
      }));
    });
  };

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

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

  return /*#__PURE__*/React.createElement(Popover, {
    trigger: "click",
    overlayClassName: "".concat(sortPrefixCls, "-popover"),
    title: $l('Table', 'custom_sort'),
    content: popupContent,
    visible: visible,
    onVisibleChange: onVisibleChange,
    placement: "bottomLeft"
  }, /*#__PURE__*/React.createElement(Button, {
    icon: "paixu-xia",
    funcType: FuncType.link,
    color: ButtonColor.primary,
    className: "".concat(sortPrefixCls, "-trigger-button")
  }));
};

CombineSort.displayName = 'CombineSort';
export default observer(CombineSort);
//# sourceMappingURL=CombineSort.js.map
