"use strict";

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

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

var _fishx = require("fishx");

var _propTypes = _interopRequireDefault(require("prop-types"));

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

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

var _commonUtil = require("../../../utils/commonUtil");

var _getLocale = require("../../../utils/getLocale");

var _storeUtil = require("../../../utils/storeUtil");

var _MBaseComponent2 = _interopRequireDefault(require("../../MBaseComponent"));

var _flashSale = _interopRequireDefault(require("../components/flash-sale"));

require("./index.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 = 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 _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 _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 _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 _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 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); 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); }

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 initialData = [{
  imgUrl: 'https://s3.ax1x.com/2020/12/21/rwtM24.png',
  offerName: 'Meet hotel',
  des: 'Product Name more and more more Product Name more and more more ',
  id: 1,
  salesPrice: '199.00',
  marketPrice: '200.00',
  salePercent: 0
}, {
  imgUrl: 'https://s3.ax1x.com/2020/12/21/rwtM24.png',
  offerName: 'Product Name more and more more Product Name more and more more',
  des: 'Product Name more and more more Product Name more and more more ',
  id: 2,
  salesPrice: '199.09',
  marketPrice: '200.00',
  salePercent: 30
}, {
  imgUrl: 'https://s3.ax1x.com/2020/12/21/rwtM24.png',
  offerName: 'Eat the week',
  des: 'Product Name more and more more Product Name more and more more ',
  id: 3,
  salesPrice: '199.09',
  marketPrice: '200.00',
  salePercent: 60
}];

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

  var _super = _createSuper(MFlashSale);

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

    _classCallCheck(this, MFlashSale);

    _this = _super.call(this, props);
    _this.state = {
      flashSales: _this.props.mode === 'designer' ? initialData : (0, _commonUtil.ensure)(function () {
        return (0, _storeUtil.getMagicStore)("flashSale_".concat(_this.props.id));
      }, []),
      expDate: '',
      title: 'Flash Sale',
      nowTime: '',
      loading: false
    };
    return _this;
  }

  _createClass(MFlashSale, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.props.sourceUrl) {
        var source = this.props.sourceUrl.split(';');
        this.getNextFlashSale({
          excludeExpireCmp: true
        }, source);
      }
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      if (this.props.sourceUrl !== nextProps.sourceUrl) {
        var source = nextProps.sourceUrl.split(';');
        this.getNextFlashSale({
          excludeExpireCmp: true
        }, source);
      }
    }
  }, {
    key: "getNextFlashSale",
    value: function () {
      var _getNextFlashSale = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee2(params, source) {
        var _this2 = this;

        var data, now, start, end, getFlashData;
        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.prev = 0;
                _context2.next = 3;
                return (0, _fishx.fetch)("".concat(window.MParams.HUrl, "/").concat(source[0]), {
                  method: 'GET',
                  params: params
                });

              case 3:
                data = _context2.sent;

                if (data.length > 0) {
                  now = data[0].now && new Date(data[0].now.replace(/-/g, '/')).getTime();
                  start = data[0].effDate && new Date(data[0].effDate.replace(/-/g, '/')).getTime();
                  end = data[0].expDate && new Date(data[0].expDate.replace(/-/g, '/')).getTime();

                  getFlashData = /*#__PURE__*/function () {
                    var _ref = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee(pageSize) {
                      var res, result;
                      return _regenerator["default"].wrap(function _callee$(_context) {
                        while (1) {
                          switch (_context.prev = _context.next) {
                            case 0:
                              _context.next = 2;
                              return _this2.getFlashSale({
                                campaignId: data[0] && data[0].campaignId,
                                sortBy: 'C',
                                pageIndex: 1,
                                pageSize: pageSize
                              }, source);

                            case 2:
                              res = _context.sent;

                              if (res.list) {
                                _context.next = 5;
                                break;
                              }

                              return _context.abrupt("return", 0);

                            case 5:
                              result = res.list.map(function (item) {
                                // href 供点击商品时跳转到详情页
                                item.href = "/product/detail/".concat(item.offerId, "?productId=").concat(item.sppProductId);
                                item.imgUrl = item.imgUrl;
                                item.offerName = item.productName;
                                item.salesPrice = item.specialPrice;
                                item.marketPrice = item.marketPrice;
                                item.imgUrlContent = item.imgUrlContent;
                                item.labels = item.labels;
                                item.salePercent = item.salePercent / 100 || 0;
                                return item;
                              });
                              /** 当加载了 30条数据后 就不显示loading */
                              // let loading = false;
                              // if (res.total > 5) {
                              //   loading = true;
                              // }
                              // if (pageSize > 5) {
                              //   loading = false;
                              // }

                              if (_this2.props.mode === 'renderer') {
                                (0, _storeUtil.setMagicStore)("flashSale_".concat(_this2.props.id), _toConsumableArray(result));
                              }

                              _this2.setState({
                                expDate: now < start ? start : end,
                                nowTime: now,
                                title: now < start ? 'Next Deal Will Start' : 'Flash Sale',
                                // expDate: data[0] && data[0].expDate && new Date(data[0].expDate.replace(/-/g, '/')).getTime(),
                                flashSales: _toConsumableArray(result),
                                loading: false
                              });

                              return _context.abrupt("return", res.total);

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

                    return function getFlashData(_x3) {
                      return _ref.apply(this, arguments);
                    };
                  }();

                  getFlashData(30); // getFlashData(5).then(total => {
                  //   if (total > 5) {
                  //     setTimeout(() => {
                  //       getFlashData(30);
                  //     });
                  //   }
                  // });
                }

                _context2.next = 10;
                break;

              case 7:
                _context2.prev = 7;
                _context2.t0 = _context2["catch"](0);
                console.error(_context2.t0);

              case 10:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, null, [[0, 7]]);
      }));

      function getNextFlashSale(_x, _x2) {
        return _getNextFlashSale.apply(this, arguments);
      }

      return getNextFlashSale;
    }()
  }, {
    key: "getFlashSale",
    value: function () {
      var _getFlashSale = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee3(params, source) {
        return _regenerator["default"].wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                return _context3.abrupt("return", (0, _fishx.fetch)("".concat(window.MParams.HUrl, "/").concat(source[1]), {
                  method: 'GET',
                  params: params
                }));

              case 1:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }));

      function getFlashSale(_x4, _x5) {
        return _getFlashSale.apply(this, arguments);
      }

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

      var tempProps = _objectSpread({}, this.props, {
        isLeaf: true,
        onComponentClick: this.onComponentClick,
        style: {// background: '#fff',
        }
      });

      var loading = this.state.loading;
      var locale = (0, _getLocale.getComponentLocale)(this.props, this.context, 'MFlashSale', function () {
        return require('./locale/en_US');
      });
      return /*#__PURE__*/_react["default"].createElement(_MagicBox["default"], tempProps, /*#__PURE__*/_react["default"].createElement(_flashSale["default"], {
        loading: loading,
        rightTxt: locale.SEE_ALL,
        data: this.state.flashSales,
        title: this.state.title,
        nowTime: this.state.nowTime,
        endTime: this.state.expDate,
        onEndClick: function onEndClick() {
          _this3.clickItem('/spike');
        },
        onItemClick: function onItemClick(item) {
          _this3.clickItem(item.href);
        }
      }));
    }
  }]);

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

exports["default"] = MFlashSale;

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

_defineProperty(MFlashSale, "contextTypes", {
  antLocale: _propTypes["default"].object
});