"use strict";

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

var _ecommerce = require("@whalecloud/ecommerce");

var _fdx = require("@whalecloud/fdx");

var _isEqual = _interopRequireDefault(require("lodash/isEqual"));

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

var _reactDnd = require("react-dnd");

var _uuid = require("uuid");

var _IconBase = require("../../assets/IconBase64");

require("./index.less");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? Object(arguments[i]) : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var iconObj = {
  MRowIcon: _IconBase.MRowIcon,
  MColIcon: _IconBase.MColIcon,
  MRowCol2Icon: _IconBase.MRowCol2Icon,
  MRowCol3Icon: _IconBase.MRowCol3Icon,
  MRowCol4Icon: _IconBase.MRowCol4Icon,
  MImgIcon: _IconBase.MImgIcon,
  GalaryTemplate4Icon: _IconBase.GalaryTemplate4Icon,
  MCatalogMenuIcon: _IconBase.MCatalogMenuIcon,
  MTextIcon: _IconBase.MTextIcon,
  MVideoIcon: _IconBase.MVideoIcon,
  MCarouselIcon: _IconBase.MCarouselIcon,
  MCardIcon: _IconBase.MCardIcon,
  MScrollIcon: _IconBase.MScrollIcon,
  MMultipleBannersIcon: _IconBase.MMultipleBannersIcon,
  MProductListIcon: _IconBase.MProductListIcon,
  MFlashSalesIcon: _IconBase.MScrollIcon,
  MBannerIcon: _IconBase.MBannerIcon,
  MFlashSaleIcon: _IconBase.MFlashSaleIcon,
  MFlashServiceIcon: _IconBase.MFlashServiceIcon,
  MIconGridIcon: _IconBase.MIconGridIcon,
  MPageTitleIcon: _IconBase.MPageTitleIcon,
  MGroupParticipantsIcon: _IconBase.MGroupParticipantsIcon,
  MRecommendIcon: _IconBase.MRecommendIcon,
  MSearchBarIcon: _IconBase.MSearchBarIcon,
  MGroupIcon: _IconBase.MGroupIcon,
  MGroupGoodsIcon: _IconBase.MGroupGoodsIcon,
  MImgAreaIcon: _IconBase.MImgAreaIcon,
  MMProductListIcon: _IconBase.MMProductListIcon,
  MCouponListIcon: _IconBase.MCouponListIcon,
  MZeroSaleIcon: _IconBase.MZeroSaleIcon,
  MCarouselSearchBarIcon: _IconBase.MCarouselSearchBarIcon,
  MProductAdvertiseIcon: _IconBase.MProductAdvertiseIcon
};

var IconContainer = /*#__PURE__*/function (_Component) {
  _inherits(IconContainer, _Component);

  var _super = _createSuper(IconContainer);

  function IconContainer() {
    _classCallCheck(this, IconContainer);

    return _super.apply(this, arguments);
  }

  _createClass(IconContainer, [{
    key: "render",
    value: function render() {
      return /*#__PURE__*/_react["default"].createElement(_fdx.Collapse.Panel, {
        header: this.props.title
      }, this.props.children);
    }
  }]);

  return IconContainer;
}(_react.Component);

function DraggableIcon(_ref) {
  var className = _ref.className,
      id = _ref.id,
      type = _ref.type,
      title = _ref.title,
      icon = _ref.icon,
      initParam = _ref.initParam;

  var _useDrag = (0, _reactDnd.useDrag)({
    item: {
      type: type,
      id: id,
      title: title,
      initParam: initParam
    },
    // 如果需要在左侧边栏的图标上配置更多自定义参数，全部写在 initParam 中，会被自动传递给 onDrop 函数
    collect: function collect(monitor) {
      return {
        isDragging: monitor.isDragging()
      };
    }
  }),
      _useDrag2 = _slicedToArray(_useDrag, 3),
      isDragging = _useDrag2[0].isDragging,
      drag = _useDrag2[1],
      preview = _useDrag2[2];

  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_reactDnd.DragPreviewImage, {
    connect: preview,
    src: _IconBase.boxImage
  }), /*#__PURE__*/_react["default"].createElement("div", {
    ref: drag((0, _react.useRef)(null)),
    className: "draggableIcon ".concat(className)
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: icon,
    alt: ""
  }), /*#__PURE__*/_react["default"].createElement("p", null, title)));
}

var SideBar = /*#__PURE__*/function (_Component2) {
  _inherits(SideBar, _Component2);

  var _super2 = _createSuper(SideBar);

  function SideBar(props) {
    var _this;

    _classCallCheck(this, SideBar);

    _this = _super2.call(this, props);
    _this.state = {
      leftSiderBarConfig: props.leftSiderBarConfig,
      activeKey: props.leftSiderBarConfig && props.leftSiderBarConfig[0] ? props.showIntro ? ["category-".concat(props.leftSiderBarConfig[0].category), 'category-Banner'] : ["category-".concat(props.leftSiderBarConfig[0].category)] : []
    };
    return _this;
  }

  _createClass(SideBar, [{
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      if (!(0, _isEqual["default"])(nextProps.leftSiderBarConfig, this.state.leftSiderBarConfig)) {
        this.setState(_objectSpread({}, this.state, {
          leftSiderBarConfig: _toConsumableArray(nextProps.leftSiderBarConfig)
        }));

        if (nextProps.leftSiderBarConfig && nextProps.leftSiderBarConfig[0]) {
          this.setState({
            activeKey: nextProps.showIntro ? ["category-".concat(nextProps.leftSiderBarConfig[0].category), 'category-Banner'] : ["category-".concat(nextProps.leftSiderBarConfig[0].category)]
          });
        }
      }
    }
  }, {
    key: "renderCollapsePanels",
    value: function renderCollapsePanels() {
      var Meta = _fdx.Card.Meta;
      var panels = [];
      var elements = {}; // 以 category 为维度归类。如果没有传入图标，采用 magic-box 内置的默认图标

      this.state.leftSiderBarConfig.map(function (conf) {
        if (!conf.icon) {
          conf.icon = iconObj["".concat(conf.type, "Icon")] ? iconObj["".concat(conf.type, "Icon")] : _IconBase.DefaultIcon;
        }

        if (!elements[conf.category]) {
          elements[conf.category] = [];
        }

        elements[conf.category].push(conf);
        return true;
      });

      var _loop = function _loop(p) {
        var items = elements[p];

        var tag =
        /*#__PURE__*/
        // <IconContainer key={'category-' + p} title={p}>
        _react["default"].createElement(_fdx.Collapse.Panel, {
          header: "".concat(p, "(").concat(items.length, ")"),
          key: "category-".concat(p)
        }, items.map(function (conf, index) {
          return /*#__PURE__*/_react["default"].createElement(DraggableIcon, {
            className: "category-".concat(p, "-").concat(index),
            id: (0, _uuid.v4)(),
            type: conf.type,
            key: "icon-".concat(index),
            icon: conf.icon,
            title: conf.label,
            initParam: conf.initParam ? JSON.parse(conf.initParam) : ''
          });
        })) // </IconContainer>
        ;

        panels.push(tag);
      };

      for (var p in elements) {
        _loop(p);
      }

      return panels;
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      return /*#__PURE__*/_react["default"].createElement("div", {
        className: "sideBar"
      }, /*#__PURE__*/_react["default"].createElement(_ecommerce.Scrollbars, {
        autoHide: true,
        thumbSize: 200
      }, /*#__PURE__*/_react["default"].createElement(_fdx.Card, {
        bordered: false,
        title: "Components"
      }, /*#__PURE__*/_react["default"].createElement(_fdx.Collapse, {
        activeKey: this.state.activeKey,
        accordion: false,
        onChange: function onChange(v) {
          _this2.setState({
            activeKey: v || ''
          });
        }
      }, this.renderCollapsePanels()))));
    }
  }]);

  return SideBar;
}(_react.Component);

exports["default"] = SideBar;