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

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 _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 _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 _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 _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 { Tabs } from 'antd-mobile';
import isEqual from 'lodash/isEqual';
import shuffle from 'lodash/shuffle';
import Macy from 'macy';
import React, { Component } from 'react';
import ProductItem from '../../../../../common/ProductItem';
import { ensure, fishFetch } from '../../../../../utils/commonUtil';
import { getMagicStore, setMagicStore } from '../../../../../utils/storeUtil';
import './index.less';
var srcType = {
  INTELLIGENT: 'I',
  SELECT: 'S'
};

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

  var _super = _createSuper(Recommend);

  function Recommend() {
    var _this;

    _classCallCheck(this, Recommend);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));

    _defineProperty(_assertThisInitialized(_this), "_cache", _this.props.mode === 'designer' ? {} : ensure(function () {
      return getMagicStore("recommend_".concat(_this.props.id));
    }, {}));

    _defineProperty(_assertThisInitialized(_this), "state", _objectSpread({
      tabIndex: 0
    }, _this._cache));

    _defineProperty(_assertThisInitialized(_this), "resetProducts", /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(sourceType, params, index) {
        var id, cache, newData, res, _res, _objectSpread2, _cache;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                id = _this.props.id;
                cache = getMagicStore("recommend_".concat(id));

                if (!cache) {
                  _context.next = 7;
                  break;
                }

                if (!("products".concat(index) in cache)) {
                  _context.next = 7;
                  break;
                }

                _this.setState(_defineProperty({}, "products".concat(index), cache["products".concat(index)]), function () {
                  _this.getMacy(".tab-wrap-".concat(id, "-").concat(index));
                });
                /** 如果数据未过期 */


                if (!(cache.endTime > Date.now())) {
                  _context.next = 7;
                  break;
                }

                return _context.abrupt("return");

              case 7:
                newData = [];

                if (!(sourceType === srcType.INTELLIGENT)) {
                  _context.next = 15;
                  break;
                }

                _context.next = 11;
                return fishFetch("".concat(window.MParams.MBaseUrl, "/h5/offers"), {
                  catgIds: '',
                  offerIdList: null,
                  q: '',
                  pageIndex: 1,
                  pageSize: 10,
                  sortType: 1
                }, 'post');

              case 11:
                res = _context.sent;
                newData = _this.setArrayOrder(res.pageInfo.list);
                _context.next = 20;
                break;

              case 15:
                if (!(sourceType === srcType.SELECT)) {
                  _context.next = 20;
                  break;
                }

                _context.next = 18;
                return fishFetch("".concat(window.MParams.MBaseUrl, "/h5/products"), params);

              case 18:
                _res = _context.sent;
                newData = _this.setArrayOrder(_toConsumableArray(_this.dataAdapter(_res.list)));

              case 20:
                if (_this.props.mode === 'renderer') {
                  _cache = getMagicStore("recommend_".concat(id));
                  setMagicStore("recommend_".concat(id), _objectSpread({}, _cache, (_objectSpread2 = {}, _defineProperty(_objectSpread2, "products".concat(index), newData), _defineProperty(_objectSpread2, "endTime", Date.now() + 3 * 60 * 1000), _objectSpread2)));
                }

                _this.setState(_defineProperty({}, "products".concat(index), newData), function () {
                  _this.getMacy(".tab-wrap-".concat(id, "-").concat(index));
                });

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

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

    _defineProperty(_assertThisInitialized(_this), "dataAdapter", function (data) {
      return data.filter(function (f) {
        return f.state === 'A';
      });
    });

    _defineProperty(_assertThisInitialized(_this), "onTabChange", function (tabIndex) {
      if (tabIndex === _this.state.tabIndex) return;

      _this.setState(_defineProperty({
        tabIndex: tabIndex
      }, "products".concat(tabIndex), []));

      var curTab = _this.props.data[tabIndex];

      _this.resetProducts(curTab.source, curTab.params, tabIndex);
    });

    _defineProperty(_assertThisInitialized(_this), "getMacy", function (container) {
      var masonryNew = new Macy({
        container: container,
        // 图像列表容器
        trueOrder: false,
        waitForImages: false,
        useOwnImageLoader: false,
        margin: {
          x: 12,
          y: 12
        },
        // 设计列与列的间距
        columns: 2 // 设置列数

      });
      masonryNew.runOnImageLoad(function () {
        masonryNew.recalculate(true);
      }, true);
    });

    _defineProperty(_assertThisInitialized(_this), "setArrayOrder", function (arr) {
      return _this.props.imgDisplayOrder === 'random' ? shuffle(arr) : arr;
    });

    return _this;
  }

  _createClass(Recommend, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props$data = _slicedToArray(this.props.data, 1),
          first = _this$props$data[0];

      if (first) this.resetProducts(first.source, first.params, 0);
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      var data = nextProps.data;
      var tabIndex = this.state.tabIndex;

      if (!isEqual(data, this.props.data)) {
        var curTab = data[tabIndex];
        this.resetProducts(curTab.source, curTab.params, tabIndex);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          data = _this$props.data,
          id = _this$props.id,
          onClick = _this$props.onClick;
      return /*#__PURE__*/React.createElement("div", {
        className: "recommend-wrap"
      }, /*#__PURE__*/React.createElement(Tabs, {
        onChange: this.onTabChange
      }, data.map(function (tab, index) {
        var _products = _this2.state["products".concat(index)] || [];

        return /*#__PURE__*/React.createElement(Tabs.Tab, {
          title: tab.title,
          key: index
        }, /*#__PURE__*/React.createElement("div", {
          className: "tab-wrap tab-wrap-".concat(id, "-").concat(index)
        }, _products.map(function (item) {
          return /*#__PURE__*/React.createElement(ProductItem, {
            key: item.productId,
            data: item,
            showProgress: false,
            onItemClick: function onItemClick() {
              return onClick("/product/detail/".concat(item.offerId, "?productId=").concat(item.productId));
            }
          });
        })));
      })));
    }
  }]);

  return Recommend;
}(Component);

_defineProperty(Recommend, "defaultProps", {
  data: []
});

export { Recommend as default };