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

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

import Fishx from '@fishx/core';
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 './index.less';
var PAGE_SIZE = 10;
var sourceType = {
  AI: 'A',
  SELECT: 'S'
};

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

  var _super = _createSuper(ProductList);

  function ProductList() {
    var _this;

    _classCallCheck(this, ProductList);

    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), "state", {
      list: ensure(function () {
        return getMagicStore("productList_".concat(_this.props.id)).list;
      }, []),
      total: 0,
      pageIndex: 1,
      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), "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), "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,
              labels: item.labels
            });
          }
        });
      }

      return newData;
    });

    _defineProperty(_assertThisInitialized(_this), "getProductsList", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      var source,
          prodIds,
          _this$props,
          id,
          mode,
          res,
          _list,
          _args = arguments;

      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              source = _args.length > 0 && _args[0] !== undefined ? _args[0] : _this.props.source;
              prodIds = _args.length > 1 && _args[1] !== undefined ? _args[1] : _this.props.prodIds;
              _context.prev = 2;
              _this$props = _this.props, id = _this$props.id, mode = _this$props.mode;

              _this.setState({
                loading: true
              });

              _context.next = 7;
              return fishFetch('/h5/products', {
                products: prodIds
              }, 'GET');

            case 7:
              res = _context.sent;
              _list = _this.dataAdapter(res.list);

              _this.setState({
                list: _list,
                loading: false
              }, function () {
                _this.getMacy();

                if (mode === 'renderer') {
                  setMagicStore("productList_".concat(id), {
                    source: source,
                    prodIds: prodIds,
                    list: _this.state.list,
                    endTime: Date.now() + 3 * 60 * 1000
                  });
                }
              });

              _context.next = 15;
              break;

            case 12:
              _context.prev = 12;
              _context.t0 = _context["catch"](2);

              _this.setState({
                loading: false
              });

            case 15:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[2, 12]]);
    })));

    _defineProperty(_assertThisInitialized(_this), "getRecommendList", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
      var source,
          recommendValue,
          type,
          _this$props2,
          id,
          mode,
          pageIndex,
          res,
          _args2 = arguments;

      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              source = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : _this.props.source;
              recommendValue = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : _this.props.recommendValue;
              type = _args2.length > 2 ? _args2[2] : undefined;
              _context2.prev = 3;
              _this$props2 = _this.props, id = _this$props2.id, mode = _this$props2.mode;
              pageIndex = _this.state.pageIndex;
              _this.lock = true;

              _this.setState({
                loading: true
              });

              _this.pageScrollTop = _this.scrollTarget.scrollTop;
              _context2.next = 11;
              return fishFetch('/h5/offers', {
                pageIndex: pageIndex,
                pageSize: PAGE_SIZE,
                sortType: '1',
                intelligentType: recommendValue.intelligentType,
                intelligentValue: recommendValue.intelligentValue.join(','),
                aggregation: false
              }, 'POST');

            case 11:
              res = _context2.sent;

              _this.setState(function (state) {
                return {
                  list: (state.pageIndex === 1 || type === 'empty' ? [] : state.list).concat(res.pageInfo.list),
                  total: Math.min(res.pageInfo.total, 100),
                  pageIndex: state.pageIndex + 1,
                  loading: false
                };
              }, function () {
                _this.getMacy();

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

                  _this.scrollTarget.scrollTo(0, _this.pageScrollTop === 0 ? 0 : _this.pageScrollTop + 160);
                });

                if (mode === 'renderer') {
                  setMagicStore("productList_".concat(id), {
                    source: source,
                    recommendValue: recommendValue,
                    list: _this.state.list,
                    pageIndex: _this.state.pageIndex,
                    total: _this.state.total,
                    endTime: Date.now() + 3 * 60 * 1000
                  });
                }
              });

              _context2.next = 18;
              break;

            case 15:
              _context2.prev = 15;
              _context2.t0 = _context2["catch"](3);

              _this.setState({
                loading: false
              });

            case 18:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[3, 15]]);
    })));

    _defineProperty(_assertThisInitialized(_this), "getMacy", function () {
      var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.props.type;
      var list = _this.state.list;

      if (list.length > 0) {
        if (_this.masonry) {
          _this.masonry = null;
        }

        var masonryNew = new Macy({
          container: ".pro_list_".concat(_this.random),
          // 图像列表容器
          trueOrder: false,
          waitForImages: false,
          useOwnImageLoader: false,
          margin: {
            x: 12,
            y: 12
          },
          // 设计列与列的间距
          columns: type === 0 ? 2 : 1 // 设置列数

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

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

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

      _this.getRecommendList();
    });

    _defineProperty(_assertThisInitialized(_this), "onScroll", function (e) {
      // 智能推荐时才支持滚动分页，自选商品不分页
      if (_this.props.source === sourceType.AI && !_this.lock) {
        var productListDom = document.querySelector('.pro_list'); // 组件高度初始高度超过屏幕，并且到达组件底部可继续滚动时调用

        if (productListDom.clientHeight + productListDom.offsetTop > e.target.clientHeight && productListDom.clientHeight + productListDom.offsetTop < e.target.clientHeight + e.target.scrollTop) {
          _this.refreshNext();
        }
      }
    });

    return _this;
  }

  _createClass(ProductList, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      this.getMacy();
      this.scrollTarget = document.querySelector('#scroll-view-content-wrap') || document.querySelector('.scrollbars > div') || window;
      this.scrollTarget.addEventListener('scroll', this.onScroll);
      var _this$props3 = this.props,
          source = _this$props3.source,
          prodIds = _this$props3.prodIds,
          recommendValue = _this$props3.recommendValue,
          id = _this$props3.id;
      var cache = getMagicStore("productList_".concat(id));

      if (cache) {
        /** 如果数据未过期并且入参相同 */
        if (cache.endTime > Date.now()) {
          if (JSON.stringify({
            source: source,
            recommendValue: recommendValue
          }) === JSON.stringify({
            source: cache.source,
            recommendValue: cache.recommendValue
          }) && source === sourceType.AI) {
            this.setState({
              list: cache.list,
              pageIndex: cache.pageIndex || 1,
              total: cache.total
            }, function () {
              return _this2.getMacy();
            });
          }

          if (JSON.stringify({
            source: source,
            prodIds: prodIds
          }) === JSON.stringify({
            source: cache.source,
            prodIds: cache.prodIds
          }) && source === sourceType.SELECT) {
            this.setState({
              list: cache.list
            }, function () {
              return _this2.getMacy();
            });
          }

          return;
        }
      }

      if (source === sourceType.AI) {
        this.getRecommendList();
      } else {
        this.getProductsList();
      }
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      var _this3 = this;

      var _this$props4 = this.props,
          source = _this$props4.source,
          prodIds = _this$props4.prodIds,
          recommendValue = _this$props4.recommendValue,
          type = _this$props4.type;

      if (nextProps.source !== source) {
        if (nextProps.source === sourceType.AI) {
          this.setState({
            pageIndex: 1
          }, function () {
            _this3.getRecommendList(nextProps.source, nextProps.recommendValue, 'empty');
          });
        } else {
          this.getProductsList(nextProps.source, nextProps.prodIds);
        }

        return;
      }

      if (nextProps.prodIds !== prodIds) this.getProductsList(nextProps.source, nextProps.prodIds);

      if (JSON.stringify(nextProps.recommendValue) !== JSON.stringify(recommendValue)) {
        this.setState({
          pageIndex: 1
        }, function () {
          _this3.getRecommendList(nextProps.source, nextProps.recommendValue, 'empty');
        });
      }

      if (nextProps.type !== type) {
        this.getMacy(nextProps.type);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.scrollTarget.addEventListener('scroll', this.onScroll);
    }
  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var _this$state2 = this.state,
          list = _this$state2.list,
          loading = _this$state2.loading;
      var type = this.props.type;
      return /*#__PURE__*/React.createElement("div", {
        className: "pro_list_wrap"
      }, /*#__PURE__*/React.createElement("div", {
        className: "pro_list pro_list_".concat(this.random)
      }, list.map(function (item, i) {
        return /*#__PURE__*/React.createElement("div", {
          className: type === 0 ? 'col_2' : 'col_1'
        }, /*#__PURE__*/React.createElement(ProductItem, {
          key: "prod.title-".concat(i),
          data: item,
          width: "100%",
          onItemClick: _this4.onProdClick
        }));
      })), loading && /*#__PURE__*/React.createElement("div", {
        className: "loading"
      }, /*#__PURE__*/React.createElement("img", {
        src: loadingImg,
        alt: ""
      })));
    }
  }]);

  return ProductList;
}(Component);

export { ProductList as default };