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 { fetch } from 'fishx';
import isArray from 'lodash/isArray';
import isEqual from 'lodash/isEqual';
import shuffle from 'lodash/shuffle';
import Macy from 'macy';
import React, { Component } from 'react';
import { ensure } from '../../../../utils/commonUtil';
import { getMagicStore, setMagicStore } from '../../../../utils/storeUtil';
import ProductItem from '../common/ProductItem';
import Tabs from '../tabs';
import './index.less';
var srcType = {
  INTELLIGENT: 'I',
  SELECT: 'S'
};
/* h5或设计器 */

var ele = document.querySelector('#scroll-view-content-wrap') || window;

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), "handleScroll", function () {
      /* 滚动条距离 */
      var scrollDistance = ele === window ? document.documentElement.scrollTop || document.body.scrollTop : ele.scrollTop;
      /* 元素距离顶部距离 */

      var distance = document.querySelector('.new-cylon-recommend').offsetTop;
      /* tab元素 */

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

      if (scrollDistance >= distance) {
        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%');
      }
    });

    _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(sourceType, params, index) {
        var cache, newData, res, _res, _objectSpread2, _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), cache["products".concat(index)]), function () {
                  _this.getMacy(".prodWrap".concat(index));
                });
                /** 如果数据未过期 */


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

                return _context.abrupt("return");

              case 6:
                newData = [];

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

                _context.next = 10;
                return fetch('/h5/offers/recommend/offers', {
                  params: {
                    needFootprint: true,
                    sceneCode: 1001,
                    recommendType: 1
                  }
                });

              case 10:
                res = _context.sent;
                newData = _this.setArrayOrder(_toConsumableArray(_this.dataAdapter(res)));
                _context.next = 19;
                break;

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

                _context.next = 17;
                return fetch('/h5/products', {
                  params: params
                });

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

              case 19:
                if (_this.props.mode === 'renderer') {
                  _cache = getMagicStore("recommend_".concat(_this.props.id));
                  setMagicStore("recommend_".concat(_this.props.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(".prodWrap".concat(index));
                });

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

      return function (_x, _x2, _x3) {
        return _ref.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), []));

      _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() {
      var data = this.props.data;

      var _data = _slicedToArray(data, 1),
          first = _data[0];

      this.resetProducts(first.source, first.params, 0);
      ele.addEventListener('scroll', this.handleScroll);
    }
  }, {
    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: "componentWillUnmount",
    value: function componentWillUnmount() {
      ele.removeEventListener('scroll', this.handleScroll);
    }
    /* 监听滚动 */

  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          prefixCls = _this$props.prefixCls,
          _this$props$data = _this$props.data,
          data = _this$props$data === void 0 ? [] : _this$props$data;
      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 = _this2.state["products".concat(i)] || [];

        return /*#__PURE__*/React.createElement("div", {
          className: "prodWrap prodWrap".concat(i),
          "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: _this2.onProdClick
          }));
        }));
      })));
    }
  }]);

  return Recommend;
}(Component);

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

export { Recommend as default };