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

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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

import Fishx from '@fishx/core';
import isEqual from 'lodash/isEqual';
import shuffle from 'lodash/shuffle';
import Macy from 'macy';
import React, { Component } from 'react';
import loadingImg from '../../../../assets/imgs/loading.png';
import { fishFetch, ensure } from '../../../../utils/commonUtil';
import { getMagicStore, setMagicStore } from '../../../../utils/storeUtil';
import ProductItem from '../common/ProductItem';
import Tabs from '../tabs';
import './index.less';
var PAGE_SIZE = 10;
var srcType = {
  AI: 'A',
  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 === 'render' ? ensure(function () {
      return getMagicStore("recommend_".concat(_this.props.id));
    }, {}) : {});

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

    _defineProperty(_assertThisInitialized(_this), "lock", false);

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

    _defineProperty(_assertThisInitialized(_this), "pageScrollTop", 0);

    _defineProperty(_assertThisInitialized(_this), "random", parseInt(Math.random() * 100, 10));

    _defineProperty(_assertThisInitialized(_this), "refreshNext", function () {
      _this.lock = true;
      var tabIndex = _this.state.tabIndex;

      var _this$state$ = _this.state["products".concat(tabIndex)],
          pageIndex = _this$state$.pageIndex,
          total = _this$state$.total;

      if ((pageIndex - 1) * PAGE_SIZE > total) {
        return;
      }

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

      _this.getRecommendList(currentTab.source, currentTab.params, tabIndex);
    });

    _defineProperty(_assertThisInitialized(_this), "handleScroll", function (e) {
      var recommendDom = document.querySelector('.new-cylon-recommend');

      if (_this.props.mode === 'renderer') {
        /* 滚动条距离 */
        var scrollDistance = _this.scrollTarget === window ? document.documentElement.scrollTop || document.body.scrollTop : _this.scrollTarget.scrollTop;
        /* tab元素 */

        var tabEle = document.querySelector('.am-tabs-tab-bar-wrap');

        if (scrollDistance >= recommendDom.offsetTop) {
          document.querySelector('.am-tabs-content-wrap').style.paddingTop = "".concat(tabEle.clientHeight, "px");
          tabEle.setAttribute('style', 'position:fixed;top:0;width:100%;z-index:1');
        } else {
          document.querySelector('.am-tabs-content-wrap').style.paddingTop = '0';
          tabEle.setAttribute('style', 'top:0;width:100%');
        }
      }

      var currentTab = _this.props.data[_this.state.tabIndex]; // 智能推荐时才支持滚动分页，自选商品不分页

      if (currentTab.source === srcType.AI && !_this.lock) {
        // 组件高度初始高度超过屏幕，并且到达组件底部可继续滚动时调用
        if (recommendDom.clientHeight + recommendDom.offsetTop > e.target.clientHeight && recommendDom.clientHeight + recommendDom.offsetTop < e.target.clientHeight + e.target.scrollTop) {
          _this.refreshNext();
        }
      }
    });

    _defineProperty(_assertThisInitialized(_this), "dataAdapter", function (data) {
      var newData = [];

      if (data && data.length > 0) {
        data.forEach(function (item) {
          if (item.state === 'A') {
            newData.push({
              offerId: item.offerId,
              offerName: item.offerName,
              salesPrice: item.salesPrice,
              marketPrice: item.marketPrice,
              specialPrice: item.specialPrice,
              discountPercent: item.discountPercent || 0,
              evaluationAvg: item.evaluationAvg,
              evaluationCnt: item.evaluationCnt,
              market: 'WhaleCloud',
              imgUrl: item.defImg || item.productImageUrl,
              sppType: item.sppType,
              promotType: item.promotType,
              productId: item.productId,
              productImageUrlContent: item.productImageUrlContent,
              imgUrlContent: item.imgUrlContent,
              labels: item.labels
            });
          }
        });
      }

      return newData;
    });

    _defineProperty(_assertThisInitialized(_this), "resetProducts", /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(source, params, index, type) {
        var cache;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                cache = getMagicStore("recommend_".concat(_this.props.id));

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

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

                _this.setState(_defineProperty({}, "products".concat(index), {
                  list: cache["products".concat(index)].list,
                  pageIndex: cache["products".concat(index)].pageIndex || 1,
                  total: cache["products".concat(index)].total || 0
                }), function () {
                  _this.getMacy(".prodWrap".concat(index, "_").concat(_this.random));
                });
                /** 如果数据未过期 */


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

                return _context.abrupt("return");

              case 6:
                setTimeout(function () {
                  if (source === srcType.AI) {
                    _this.getRecommendList(source, params, index, type);
                  } else {
                    _this.getProductsList(source, params, index);
                  }
                });

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

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

    _defineProperty(_assertThisInitialized(_this), "getProductsList", /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(source, params, index) {
        var _this$setState2, _this$props, id, mode, res, _list;

        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.prev = 0;
                _this$props = _this.props, id = _this$props.id, mode = _this$props.mode;

                _this.setState({
                  loading: true
                });

                _context2.next = 5;
                return fishFetch('/h5/products', {
                  products: params.products
                }, 'GET');

              case 5:
                res = _context2.sent;
                _list = _this.setArrayOrder(_toConsumableArray(_this.dataAdapter(res.list)));

                _this.setState((_this$setState2 = {}, _defineProperty(_this$setState2, "products".concat(index), {
                  list: _list
                }), _defineProperty(_this$setState2, "loading", false), _this$setState2), function () {
                  _this.getMacy(".prodWrap".concat(index, "_").concat(_this.random));

                  if (mode === 'renderer') {
                    var _objectSpread2;

                    var _cache = getMagicStore("recommend_".concat(id));

                    setMagicStore("recommend_".concat(id), _objectSpread({}, _cache, (_objectSpread2 = {}, _defineProperty(_objectSpread2, "products".concat(index), {
                      list: _list
                    }), _defineProperty(_objectSpread2, "endTime", Date.now() + 3 * 60 * 1000), _objectSpread2)));
                  }
                });

                _context2.next = 13;
                break;

              case 10:
                _context2.prev = 10;
                _context2.t0 = _context2["catch"](0);

                _this.setState({
                  loading: false
                });

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

      return function (_x5, _x6, _x7) {
        return _ref2.apply(this, arguments);
      };
    }());

    _defineProperty(_assertThisInitialized(_this), "getRecommendList", /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(source, params, index, type) {
        var _this$props2, id, mode, pageIndex, res;

        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.prev = 0;
                _this$props2 = _this.props, id = _this$props2.id, mode = _this$props2.mode;
                _this.lock = true;

                _this.setState({
                  loading: true
                });

                _this.pageScrollTop = _this.scrollTarget.scrollTop;
                pageIndex = type === 'empty' ? 1 : ensure(function () {
                  return _this.state["products".concat(index)].pageIndex;
                }, 1);
                _context3.next = 8;
                return fishFetch('/h5/offers', {
                  pageIndex: pageIndex,
                  pageSize: PAGE_SIZE,
                  sortType: '1',
                  intelligentType: params.intelligentType,
                  intelligentValue: params.intelligentValue.join(','),
                  aggregation: false
                }, 'POST');

              case 8:
                res = _context3.sent;

                _this.setState(function (state) {
                  var _ref4;

                  return _ref4 = {}, _defineProperty(_ref4, "products".concat(index), {
                    list: (ensure(function () {
                      return state["products".concat(index)].pageIndex;
                    }, 1) === 1 || type === 'empty' ? [] : state["products".concat(index)].list).concat(res.pageInfo.list),
                    total: Math.min(res.pageInfo.total, 100),
                    pageIndex: type === 'empty' ? 2 : ensure(function () {
                      return state["products".concat(index)].pageIndex;
                    }, 1) + 1
                  }), _defineProperty(_ref4, "loading", false), _ref4;
                }, function () {
                  _this.getMacy(".prodWrap".concat(index, "_").concat(_this.random));

                  setTimeout(function () {
                    _this.lock = false;

                    _this.scrollTarget.scrollTo(0, _this.pageScrollTop);
                  });

                  if (mode === 'renderer') {
                    var _objectSpread3;

                    var _cache = getMagicStore("recommend_".concat(id));

                    setMagicStore("recommend_".concat(id), _objectSpread({}, _cache, (_objectSpread3 = {}, _defineProperty(_objectSpread3, "products".concat(index), _this.state["products".concat(index)]), _defineProperty(_objectSpread3, "endTime", Date.now() + 3 * 60 * 1000), _objectSpread3)));
                  }
                });

                _context3.next = 15;
                break;

              case 12:
                _context3.prev = 12;
                _context3.t0 = _context3["catch"](0);

                _this.setState({
                  loading: false
                });

              case 15:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, null, [[0, 12]]);
      }));

      return function (_x8, _x9, _x10, _x11) {
        return _ref3.apply(this, arguments);
      };
    }());

    _defineProperty(_assertThisInitialized(_this), "getTabSource", function (data) {
      return data.map(function (obj, i) {
        if (obj.icon) {
          return _objectSpread({}, obj, {
            index: i,
            title: /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("img", {
              className: "tabIcon",
              src: obj.icon,
              alt: ""
            }), " ", /*#__PURE__*/React.createElement("div", null, obj.title))
          });
        }

        return _objectSpread({}, obj, {
          index: i
        });
      });
    });

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

      _this.setState(_defineProperty({
        tabIndex: value.index
      }, "products".concat(value.index), {
        list: [],
        pageIndex: 1,
        total: 0
      }), function () {
        _this.resetProducts(value.source, value.params, value.index);
      });

      document.querySelector('.new-cylon-recommend').scrollIntoView({
        behavior: 'smooth'
      });
    });

    _defineProperty(_assertThisInitialized(_this), "onProdClick", function (data) {
      var onItemClick = _this.props.onItemClick;

      if (onItemClick) {
        onItemClick(data);
      } else {
        Fishx.history.push("/product/detail/".concat(data.offerId, "?productId=").concat(data.productId));
      }
    });

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

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

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

      return arr;
    });

    return _this;
  }

  _createClass(Recommend, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.scrollTarget = document.querySelector('#scroll-view-content-wrap') || document.querySelector('.scrollbars > div') || window;
      if (this.props.data.length === 0) return;

      var _this$props$data = _slicedToArray(this.props.data, 1),
          first = _this$props$data[0];

      this.resetProducts(first.source, first.params, 0);
      this.scrollTarget.addEventListener('scroll', this.handleScroll);
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      var _this2 = this;

      var data = nextProps.data;
      var tabIndex = this.state.tabIndex;

      if (data.length === 0) {
        this.scrollTarget.removeEventListener('scroll', this.handleScroll);
        return;
      }

      if (!isEqual(data, this.props.data)) {
        var curTab = data[tabIndex];
        this.setState(_defineProperty({}, "products".concat(tabIndex), {
          list: [],
          pageIndex: 1,
          total: 0
        }), function () {
          _this2.resetProducts(curTab.source, curTab.params, tabIndex, 'empty');
        });
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.scrollTarget.removeEventListener('scroll', this.handleScroll);
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props3 = this.props,
          prefixCls = _this$props3.prefixCls,
          _this$props3$data = _this$props3.data,
          data = _this$props3$data === void 0 ? [] : _this$props3$data;
      var loading = this.state.loading;
      var divide = data.length < 4 ? data.length : 4;
      return /*#__PURE__*/React.createElement("div", {
        className: prefixCls
      }, /*#__PURE__*/React.createElement(Tabs, {
        initialPage: 0,
        tabs: this.getTabSource(data),
        swipeable: false,
        renderTabBar: function renderTabBar(props) {
          return /*#__PURE__*/React.createElement(Tabs.DefaultTabBar, _extends({}, props, {
            page: divide
          }));
        },
        onTabClick: this.onTabChange,
        animated: true
      }, data.map(function (v, i) {
        var _products = ensure(function () {
          return _this3.state["products".concat(i)].list;
        }, []);

        return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
          className: "prodWrap prodWrap".concat(i, "_").concat(_this3.random),
          "data-id": "prodWrap-".concat(i)
        }, _products.map(function (prod, index) {
          return /*#__PURE__*/React.createElement("div", {
            className: "productItem"
          }, /*#__PURE__*/React.createElement(ProductItem, {
            key: "prod.title-".concat(index),
            data: prod,
            width: "100%",
            onItemClick: _this3.onProdClick
          }));
        })), loading && /*#__PURE__*/React.createElement("div", {
          className: "loading"
        }, /*#__PURE__*/React.createElement("img", {
          src: loadingImg,
          alt: ""
        })));
      })));
    }
  }]);

  return Recommend;
}(Component);

_defineProperty(Recommend, "defaultProps", {
  prefixCls: 'new-cylon-recommend',
  data: []
});

export { Recommend as default };