"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = index;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _core = _interopRequireDefault(require("@fishx/core"));

var _fishx = require("fishx");

var _isArray = _interopRequireDefault(require("lodash/isArray"));

var _macy = _interopRequireDefault(require("macy"));

var _react = _interopRequireWildcard(require("react"));

var _commonUtil = require("../../../../utils/commonUtil");

var _storeUtil = require("../../../../utils/storeUtil");

var _ProductItem = _interopRequireDefault(require("../common/ProductItem"));

require("./index.less");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

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

var debug = require('debug')('worker:productList');

var dataAdapter = function dataAdapter(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;
};

var getProducts = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee(sourceType, products, id, mode) {
    var cache, res, list, _res, _list;

    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            cache = (0, _storeUtil.getMagicStore)("productList_".concat(id));

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

            if (!(JSON.stringify({
              sourceType: sourceType,
              products: products
            }) === JSON.stringify({
              sourceType: cache.sourceType,
              products: cache.products
            }))) {
              _context.next = 6;
              break;
            }

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

            return _context.abrupt("return", cache.list);

          case 6:
            if (!(sourceType === 'I')) {
              _context.next = 13;
              break;
            }

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

          case 9:
            res = _context.sent;
            list = dataAdapter(res);

            if (mode === 'renderer') {
              (0, _storeUtil.setMagicStore)("productList_".concat(id), {
                sourceType: sourceType,
                products: products,
                list: list,
                endTime: Date.now() + 3 * 60 * 1000
              });
            }

            return _context.abrupt("return", list);

          case 13:
            if (!(sourceType === 'S')) {
              _context.next = 20;
              break;
            }

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

          case 16:
            _res = _context.sent;
            _list = dataAdapter((0, _isArray["default"])(_res) ? _res : _res.list);

            if (mode === 'renderer') {
              (0, _storeUtil.setMagicStore)("productList_".concat(id), {
                sourceType: sourceType,
                products: products,
                list: _list,
                endTime: Date.now() + 3 * 60 * 1000
              });
            }

            return _context.abrupt("return", _list);

          case 20:
            _context.next = 25;
            break;

          case 22:
            _context.prev = 22;
            _context.t0 = _context["catch"](0);
            debug(_context.t0);

          case 25:
            return _context.abrupt("return", []);

          case 26:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 22]]);
  }));

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

function index(props) {
  var id = props.id,
      prodIds = props.prodIds,
      source = props.source,
      _props$type = props.type,
      type = _props$type === void 0 ? 0 : _props$type,
      onItemClick = props.onItemClick,
      mode = props.mode,
      proList = props.proList;

  var _useState = (0, _react.useState)(mode === 'designer' ? proList : (0, _commonUtil.ensure)(function () {
    return (0, _storeUtil.getMagicStore)("productList_".concat(id)).list;
  }, [])),
      _useState2 = _slicedToArray(_useState, 2),
      list = _useState2[0],
      setList = _useState2[1];

  var randomNum = Math.round(Math.random() * 100); // const resetProducts = (sourceType, products) => {
  //   if (sourceType === 'I') {
  //     fetch('/h5/offers/recommend/offers', {
  //       params: {
  //         needFootprint: true,
  //         sceneCode: 1001,
  //         recommendType: 1,
  //       },
  //     }).then(res => {
  //       setList(dataAdapter(res));
  //     });
  //   } else if (sourceType === 'S') {
  //     fetch('/h5/products', { params: { products } }).then(res => {
  //       setList(dataAdapter(isArray(res) ? res : res.list));
  //     });
  //   }
  // };

  var onProdClick = function onProdClick(data) {
    if (onItemClick) {
      onItemClick(data);
    } else {
      _core["default"].history.push("/product/detail/".concat(data.offerId, "?productId=").concat(data.productId));
    }
  };

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

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

  (0, _react.useEffect)(function () {
    // resetProducts(source, prodIds);
    getProducts(source, prodIds, id, mode).then(function (newList) {
      return setList(newList);
    });
  }, [prodIds]);
  (0, _react.useEffect)(function () {
    getMacy(".pro_list_".concat(randomNum));
  }, [list]);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "pro_list_wrap"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(type === 0 ? 'pro_list_column' : 'pro_list_row', " pro_list_").concat(randomNum)
  }, list.map(function (v, i) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: "productItem"
    }, /*#__PURE__*/_react["default"].createElement(_ProductItem["default"], {
      key: "prod.title-".concat(i),
      data: v,
      width: "100%",
      onItemClick: onProdClick
    }));
  })));
}