import _regeneratorRuntime from "@babel/runtime/regenerator";

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

import PropTypes from 'prop-types';
import CountDown from '../../../../common/CountDown';
import { ensure, fishFetch } from '../../../../utils/commonUtil';
import { newDate } from '../../../../utils/dateUtil';
import { getComponentLocale } from '../../../../utils/getLocale';
import { getMagicStore, setMagicStore } from '../../../../utils/storeUtil';
import MBaseComponent from '../MBaseComponent';
import FlashSale from './flash-sale';
import defImg1 from './imgs/defImg1.png';
import defImg2 from './imgs/defImg2.png';
import defImg3 from './imgs/defImg3.png';

var React = require('react');

var defaultData = [{
  imgUrlContent: {
    url: defImg1
  },
  offerName: 'DITO STARTER PACK + 3GB Data',
  salesPrice: 49,
  marketPrice: 100,
  discountPercent: 51,
  salePercent: 5000
}, {
  imgUrlContent: {
    url: defImg2
  },
  offerName: 'DITO Level Up 99 x 365 days',
  salesPrice: 594,
  marketPrice: 1188,
  discountPercent: 50,
  salePercent: 5000
}, {
  imgUrlContent: {
    url: defImg3
  },
  offerName: 'DITO Level-Up Pack 99 7GB',
  salesPrice: 99,
  marketPrice: 138,
  discountPercent: 28,
  salePercent: 5000
}];

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

  var _super = _createSuper(MComponent);

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

    _classCallCheck(this, MComponent);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "init", function () {
      var sourceUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.props.sourceUrl || '';

      if (sourceUrl) {
        var source = sourceUrl.split(';');

        _this.getNextFlashSale(source);
      }
    });

    _this.state = {
      data: _this.props.mode === 'designer' ? defaultData : ensure(function () {
        return getMagicStore("flashSale_".concat(_this.props.id));
      }, []),
      title: 'Flash Sale',
      now: '',
      effDate: '',
      expDate: '',
      isWill: '',
      loading: false
    };
    return _this;
  }

  _createClass(MComponent, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.init();
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      // if (nextProps.sourceUrl !== this.props.sourceUrl) this.init(nextProps.sourceUrl);
      this.init(nextProps.sourceUrl);
    }
  }, {
    key: "getNextFlashSale",
    value: function () {
      var _getNextFlashSale = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(source) {
        var _this2 = this;

        var data, getFlashData;
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.prev = 0;
                this.setState({
                  loading: true
                });
                _context2.next = 4;
                return fishFetch("".concat(window.MParams.MBaseUrl, "/h5/").concat(source[0]), {
                  excludeExpireCmp: true
                });

              case 4:
                data = _context2.sent;
                this.setState({
                  loading: false
                });

                if (!(data.length > 0)) {
                  _context2.next = 11;
                  break;
                }

                getFlashData = /*#__PURE__*/function () {
                  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(pageSize) {
                    var res;
                    return _regeneratorRuntime.wrap(function _callee$(_context) {
                      while (1) {
                        switch (_context.prev = _context.next) {
                          case 0:
                            _context.next = 2;
                            return fishFetch("".concat(window.MParams.MBaseUrl, "/h5/").concat(source[1]), {
                              campaignId: data[0] && data[0].campaignId,
                              sortBy: 'C',
                              pageIndex: 1,
                              pageSize: pageSize
                            });

                          case 2:
                            res = _context.sent;

                            if (!(_this2.props.mode === 'designer' && (!res.list || res.list.length === 0))) {
                              _context.next = 5;
                              break;
                            }

                            return _context.abrupt("return");

                          case 5:
                            if (_this2.props.mode === 'renderer') {
                              setMagicStore("flashSale_".concat(_this2.props.id), _toConsumableArray(res.list || []));
                            }

                            _this2.setState({
                              now: +newDate(data[0].now),
                              effDate: +newDate(data[0].effDate),
                              expDate: +newDate(data[0].expDate),
                              isWill: data[0].cmpState === 'A',
                              // A活动即将开始, B活动正在进行
                              data: _toConsumableArray(res.list || [])
                            });

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

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

                getFlashData(30);
                _context2.next = 14;
                break;

              case 11:
                if (!(this.props.mode === 'designer')) {
                  _context2.next = 13;
                  break;
                }

                return _context2.abrupt("return");

              case 13:
                this.setState({
                  data: []
                });

              case 14:
                _context2.next = 20;
                break;

              case 16:
                _context2.prev = 16;
                _context2.t0 = _context2["catch"](0);
                this.setState({
                  loading: false
                });
                console.error(_context2.t0);

              case 20:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this, [[0, 16]]);
      }));

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

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

      var _this$props = this.props,
          pageModuleName = _this$props.pageModuleName,
          commonConfig = _this$props.commonConfig;
      var _this$state = this.state,
          loading = _this$state.loading,
          data = _this$state.data,
          title = _this$state.title,
          effDate = _this$state.effDate,
          expDate = _this$state.expDate,
          now = _this$state.now,
          isWill = _this$state.isWill;
      var locale = getComponentLocale(this.props, this.context, 'MFlashSale', function () {
        return require('./locale/en_US');
      });

      var renderCountDown = function renderCountDown() {
        return /*#__PURE__*/React.createElement(CountDown, {
          effDate: effDate,
          expDate: expDate,
          now: now,
          refresh: _this3.init
        });
      };

      return /*#__PURE__*/React.createElement("div", {
        id: pageModuleName,
        style: commonConfig,
        onClick: this.onComponentClick
      }, /*#__PURE__*/React.createElement(FlashSale, {
        loading: loading,
        rightTxt: locale.SHOP_MORE,
        data: data,
        title: title,
        isWill: isWill,
        onClick: this.clickItem,
        renderCountDown: renderCountDown
      }));
    }
  }]);

  return MComponent;
}(MBaseComponent);

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

_defineProperty(MComponent, "contextTypes", {
  antLocale: PropTypes.object
});

export { MComponent as default };