"use strict";

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

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

var _rest = require("@fishx/rest");

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

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

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

var _MBaseComponent2 = _interopRequireDefault(require("../../../composite-comp/dito/components/MBaseComponent"));

var _MagicBox = _interopRequireDefault(require("../../../core/MagicBox"));

var _currencyUtil = require("../../../utils/currencyUtil");

require("./index.module.less");

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

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.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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); Object.defineProperty(Constructor, "prototype", { writable: false }); 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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); 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; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } 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); }

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; }

var formatData = function formatData(list) {
  var res = [];
  list.map(function (item) {
    var data = {};

    if (item.productId) {
      data.name = item.productName;
      data.href = "/offer-detail/".concat(item.offerId);
      data.price = item.preSalesPrice;
      data.costn = item.preMarketPrice;
      data.imgSrc = item.productImageUrl;
    } else {
      data.name = item.offerName;
      data.href = "/offer-detail/".concat(item.offerId);
      data.price = (0, _currencyUtil.formatCurrencyWithSymbol)(item.salesPrice);
      data.costn = (0, _currencyUtil.formatCurrencyWithSymbol)(item.marketPrice);
      data.imgSrc = item.defImg;
    }

    res.push(data);
  });
  return res;
};

var MProductList = /*#__PURE__*/function (_MBaseComponent) {
  _inherits(MProductList, _MBaseComponent);

  var _super = _createSuper(MProductList);

  /**
   * @required
   * React 会根据 type 动态创建组件的实例。
   */
  function MProductList(props) {
    var _this;

    _classCallCheck(this, MProductList);

    _this = _super.call(this, props);
    _this.state = {
      dataList: []
    };
    return _this;
  }

  _createClass(MProductList, [{
    key: "getData",
    value: function () {
      var _getData = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee(params, obj) {
        var data;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!obj.url) {
                  _context.next = 5;
                  break;
                }

                _context.next = 3;
                return (0, _rest.fetch)("".concat(window.MParams.MBaseUrl, "/").concat(obj.url), {
                  method: 'GET',
                  params: params
                });

              case 3:
                data = _context.sent;

                if (data && data instanceof Array) {
                  this.setState({
                    dataList: data
                  });
                }

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

      function getData(_x, _x2) {
        return _getData.apply(this, arguments);
      }

      return getData;
    }()
  }, {
    key: "getDataList",
    value: function getDataList(mProps) {
      if (mProps.selection === 'auto') {
        this.getData({
          sceneCode: '1001',
          recommendType: '1',
          itemType: [],
          topN: '5',
          needFootprint: true
        }, mProps);
      } else {
        this.setState({
          dataList: mProps.productList || []
        });
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this.getDataList(this.props);
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      if (this.props.url !== nextProps.url || this.props.selection !== nextProps.selection || JSON.stringify(nextProps.productList || []) !== JSON.stringify(this.props.productList || [])) {
        this.getDataList(nextProps);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var tempProps = _objectSpread({}, this.props, {
        onComponentClick: this.onComponentClick
      });

      var dataTest = [{
        key: '1',
        imgUrl: _IconBase.defaultImage
      }, {
        key: '2',
        imgUrl: _IconBase.defaultImage
      }, {
        key: '3',
        imgUrl: _IconBase.defaultImage
      }, {
        key: '4',
        imgUrl: _IconBase.defaultImage
      }, {
        key: '5',
        imgUrl: _IconBase.defaultImage
      }];
      return /*#__PURE__*/_react["default"].createElement(_MagicBox["default"], tempProps, /*#__PURE__*/_react["default"].createElement("div", {
        style: tempProps.mode !== 'designer' ? {
          maxWidth: '1200px',
          margin: 'auto'
        } : {}
      }, this.state.dataList && this.state.dataList.length > 0 ? /*#__PURE__*/_react["default"].createElement(_ecommerce.ProductList, {
        clickItem: function clickItem(item) {
          return _this2.clickItem(item.href);
        },
        data: formatData(this.state.dataList),
        showWidth: "100%"
      }) : /*#__PURE__*/_react["default"].createElement(_ecommerce.MultipleBanners, {
        data: dataTest,
        showNum: 5
      })));
    }
  }]);

  return MProductList;
}(_MBaseComponent2["default"]);

exports["default"] = MProductList;

_defineProperty(MProductList, "type", 'MProductList');