"use strict";

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

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

var _classnames = _interopRequireDefault(require("classnames"));

var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));

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 _carousel = _interopRequireDefault(require("../components/carousel"));

var _image = _interopRequireDefault(require("./images/image1.png"));

var _image2 = _interopRequireDefault(require("./images/image2.png"));

var _image3 = _interopRequireDefault(require("./images/image3.png"));

var _zeroSaleBgImg = _interopRequireDefault(require("./images/zeroSaleBgImg.png"));

require("./index.less");

var _TimeClock = _interopRequireDefault(require("./TimeClock"));

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 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 demoData = {
  posterList: [{
    postImage: _zeroSaleBgImg["default"],
    href: null,
    imageList: [_image["default"], _image2["default"], _image3["default"]]
  }]
}; // const posterList = [{}, {}, {}, {}];

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

  var _super = _createSuper(MZeroSale);

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

    _classCallCheck(this, MZeroSale);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "state", {
      imageIndex: 0,
      ready: false
    });

    _defineProperty(_assertThisInitialized(_this), "imageTimer", null);

    _defineProperty(_assertThisInitialized(_this), "posterList", []);

    _defineProperty(_assertThisInitialized(_this), "timerClockRef", _react["default"].createRef());

    _defineProperty(_assertThisInitialized(_this), "getInit", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
      var campaignList;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return (0, _commonUtil.fishFetch)('/h5/winner/specials/list');

            case 2:
              campaignList = _context.sent;

              /** 查找有效的活动 */
              _this.posterList = (0, _commonUtil.ensure)(function () {
                return _this.props.posterList.filter(function (p) {
                  var findOne = campaignList.find(function (c) {
                    return c.campaignId === p.campaignId && c.cmpState === 'B';
                  });
                  p.campaign = findOne;
                  return findOne;
                });
              }, []);

              if (_this.props.mode === 'renderer') {
                (0, _storeUtil.setMagicStore)("zeroSale_".concat(_this.props.id), _this.posterList);
              }

              _this.setState({
                ready: true
              });
              /** 中间图片轮播 */


              _this.imageTimer = setInterval(function () {
                _this.setState({
                  imageIndex: _this.state.imageIndex + 1
                });
              }, 2000);

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

    _defineProperty(_assertThisInitialized(_this), "calcLastTime", function () {
      _this.timerClockRef.current.calcLastTime();
    });

    if (props.mode === 'renderer') {
      var cache = (0, _storeUtil.getMagicStore)("zeroSale_".concat(_this.props.id));

      if (cache) {
        _this.posterList = cache;

        _this.setState({
          ready: true
        });
      }
    }

    return _this;
  }

  _createClass(MZeroSale, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.getInit();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.imageTimer && clearInterval(this.imageTimer);
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var locale = (0, _getLocale.getComponentLocale)(this.props, this.context, 'MZeroSale', function () {
        return require('./locale/en_US');
      });

      var _posterList = (0, _isEmpty["default"])(this.posterList || []) ? demoData.posterList : this.posterList;

      if (this.props.mode === 'renderer') {
        _posterList = this.posterList || [];
      }

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

      var posterList = tempProps.posterList;
      var _this$state = this.state,
          ready = _this$state.ready,
          imageIndex = _this$state.imageIndex;
      if (!ready) return null;
      return /*#__PURE__*/_react["default"].createElement(_MagicBox["default"], tempProps, /*#__PURE__*/_react["default"].createElement("div", {
        className: "zero-sale-wrap"
      }, /*#__PURE__*/_react["default"].createElement(_carousel["default"], {
        autoplay: true,
        infinite: true,
        autoplayInterval: 5000,
        dots: posterList.length > 1
      }, posterList.map(function (poster, i) {
        return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("div", {
          key: i,
          className: "poster-wrap",
          onClick: function onClick() {
            if (poster.campaignId) {
              _this2.clickItem("specialMission-".concat(poster.campaignId));
            }
          },
          style: {
            backgroundImage: "url(".concat(poster.postImage, ")")
          }
        }, /*#__PURE__*/_react["default"].createElement("div", {
          className: "poster-timer"
        }, /*#__PURE__*/_react["default"].createElement(_TimeClock["default"], {
          locale: locale,
          ref: _this2.timerClockRef,
          data: poster.campaign
        })), /*#__PURE__*/_react["default"].createElement("div", {
          className: "image-wrap"
        }, /*#__PURE__*/_react["default"].createElement("div", {
          className: "item-wrap"
        }, poster.imageList.map(function (img, index) {
          return /*#__PURE__*/_react["default"].createElement("div", {
            key: index,
            className: (0, _classnames["default"])('wrap-item', {
              active: imageIndex % poster.imageList.length === index
            })
          }, /*#__PURE__*/_react["default"].createElement("img", {
            src: img,
            alt: ""
          }));
        })))));
      }))));
    }
  }]);

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

exports["default"] = MZeroSale;

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

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