"use strict";

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

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

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

require("./index.less");

var _mobx = require("@/components/mobx");

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

var _components = require("../../../../../meta-comp/components");

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

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

var _coreUtil = require("../../../../../utils/coreUtil");

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

var __extends = void 0 && (void 0).__extends || function () {
  var _extendStatics = function extendStatics(d, b) {
    _extendStatics = Object.setPrototypeOf || {
      __proto__: []
    } instanceof Array && function (d, b) {
      d.__proto__ = b;
    } || function (d, b) {
      for (var p in b) {
        if (b.hasOwnProperty(p)) d[p] = b[p];
      }
    };

    return _extendStatics(d, b);
  };

  return function (d, b) {
    _extendStatics(d, b);

    function __() {
      this.constructor = d;
    }

    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
}();

var __assign = void 0 && (void 0).__assign || function () {
  __assign = Object.assign || function (t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];

      for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
      }
    }

    return t;
  };

  return __assign.apply(this, arguments);
};

var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }

  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }

    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }

    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }

    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};

var __generator = void 0 && (void 0).__generator || function (thisArg, body) {
  var _ = {
    label: 0,
    sent: function sent() {
      if (t[0] & 1) throw t[1];
      return t[1];
    },
    trys: [],
    ops: []
  },
      f,
      y,
      t,
      g;
  return g = {
    next: verb(0),
    "throw": verb(1),
    "return": verb(2)
  }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
    return this;
  }), g;

  function verb(n) {
    return function (v) {
      return step([n, v]);
    };
  }

  function step(op) {
    if (f) throw new TypeError("Generator is already executing.");

    while (_) {
      try {
        if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
        if (y = 0, t) op = [op[0] & 2, t.value];

        switch (op[0]) {
          case 0:
          case 1:
            t = op;
            break;

          case 4:
            _.label++;
            return {
              value: op[1],
              done: false
            };

          case 5:
            _.label++;
            y = op[1];
            op = [0];
            continue;

          case 7:
            op = _.ops.pop();

            _.trys.pop();

            continue;

          default:
            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _ = 0;
              continue;
            }

            if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
              _.label = op[1];
              break;
            }

            if (op[0] === 6 && _.label < t[1]) {
              _.label = t[1];
              t = op;
              break;
            }

            if (t && _.label < t[2]) {
              _.label = t[2];

              _.ops.push(op);

              break;
            }

            if (t[2]) _.ops.pop();

            _.trys.pop();

            continue;
        }

        op = body.call(thisArg, _);
      } catch (e) {
        op = [6, e];
        y = 0;
      } finally {
        f = t = 0;
      }
    }

    if (op[0] & 5) throw op[1];
    return {
      value: op[0] ? op[1] : void 0,
      done: true
    };
  }
};

var __spreadArrays = void 0 && (void 0).__spreadArrays || function () {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) {
    s += arguments[i].length;
  }

  for (var r = Array(s), k = 0, i = 0; i < il; i++) {
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) {
      r[k] = a[j];
    }
  }

  return r;
};

var RecommendMobile =
/** @class */
function (_super) {
  __extends(RecommendMobile, _super);

  function RecommendMobile() {
    var _this = _super !== null && _super.apply(this, arguments) || this;

    _this.preData = {};
    _this._cache = (0, _coreUtil.isDesignMode)() ? {} : (0, _commonUtil.ensure)(function () {
      return (0, _storeUtil.getMagicStore)("recommend_" + _this.props.panelProps.id);
    }, {});
    _this.state = __assign({
      tabIndex: 0,
      tabLeft: 0,
      tabWidth: 0
    }, _this._cache);

    _this.getTabBarActiveColor = function (_panelProps) {
      var tabIndex = _this.state.tabIndex;
      return (0, _commonUtil.ensure)(function () {
        return _panelProps.groupSource[tabIndex].hover.groupName.content.color;
      }, '#1890ff');
    };

    _this.getProductList = function (index) {
      return __awaiter(_this, void 0, void 0, function () {
        var recommendId, cache, sourceType, ids, newData, res, res, e_1, _cache;

        var _a, _b, _c;

        var _this = this;

        return __generator(this, function (_d) {
          switch (_d.label) {
            case 0:
              recommendId = this.props.panelProps.id;

              if (!(0, _coreUtil.isDesignMode)()) {
                cache = (0, _storeUtil.getMagicStore)("recommend_" + recommendId);

                if (cache) {
                  if ("products" + index in cache) {
                    this.setState((_a = {}, _a["products" + index] = cache["products" + index], _a), function () {
                      _this.getMacy('.tab-item-container');
                    });
                    /** 如果数据未过期 */

                    if (cache.endTime > Date.now()) return [2
                    /*return*/
                    ];
                  }
                }
              }

              sourceType = (0, _commonUtil.ensure)(function () {
                return _this.props.panelProps.groupSource[index].sourceType;
              }, 'recommend');
              ids = (0, _commonUtil.ensure)(function () {
                return _this.props.panelProps.groupSource[index].prodIds;
              }, '');
              newData = [];
              _d.label = 1;

            case 1:
              _d.trys.push([1, 6,, 7]);

              if (!(sourceType === 'select')) return [3
              /*break*/
              , 3];

              if (!ids) {
                return [2
                /*return*/
                ];
              }

              return [4
              /*yield*/
              , (0, _commonUtil.commonFetch)(window.magicDesign.MBaseUrl + "/h5/products", {
                products: ids,
                state: 'A'
              }, 'GET')];

            case 2:
              res = _d.sent();
              newData = __spreadArrays(res.list);
              return [3
              /*break*/
              , 5];

            case 3:
              return [4
              /*yield*/
              , (0, _commonUtil.commonFetch)(window.magicDesign.MBaseUrl + "/h5/offers", {
                pageIndex: 1,
                pageSize: 30,
                sortType: '1',
                intelligentType: 'ALL',
                aggregation: false,
                q: ''
              }, 'POST')];

            case 4:
              res = _d.sent();
              newData = __spreadArrays(res.pageInfo.list);
              _d.label = 5;

            case 5:
              return [3
              /*break*/
              , 7];

            case 6:
              e_1 = _d.sent();
              newData = [];
              return [3
              /*break*/
              , 7];

            case 7:
              if (!(0, _coreUtil.isDesignMode)()) {
                _cache = (0, _storeUtil.getMagicStore)("recommend_" + recommendId);
                (0, _storeUtil.setMagicStore)("recommend_" + recommendId, __assign(__assign({}, _cache), (_b = {}, _b["products" + index] = newData, _b.endTime = Date.now() + 3 * 60 * 1000, _b)));
              }

              this.setState((_c = {}, _c["products" + index] = newData, _c), function () {
                _this.getMacy('.tab-item-container');
              });
              return [2
              /*return*/
              ];
          }
        });
      });
    };

    _this.getMacy = function (container) {
      var masonryNew = new _macy["default"]({
        container: container,
        trueOrder: false,
        waitForImages: false,
        useOwnImageLoader: false,
        margin: {
          x: 12,
          y: 12
        },
        columns: 2
      });
      masonryNew.runOnImageLoad(function () {
        masonryNew.recalculate(true);
      }, true);
    };

    _this.onTabChange = function (tabIndex) {
      var _a;

      var panelProps = _this.props.panelProps;
      if (tabIndex === _this.state.tabIndex) return;

      _this.setState((_a = {
        tabIndex: tabIndex
      }, _a["products" + tabIndex] = [], _a));

      var curTab = panelProps.groupSource[tabIndex];
      if (curTab.prodIds === '') return;

      _this.getProductList(tabIndex);
    };

    _this.getBackgroundStyle = function () {
      var panelProps = _this.props.panelProps;
      var bgStyle = {};

      if (panelProps.background.bgType === 'color') {
        bgStyle = {
          backgroundColor: (0, _commonUtil.getColorRgba)(panelProps.background.color || '#fff', panelProps.background.opacity / 100 || 1)
        };
      } else {
        bgStyle = {
          background: "url(" + panelProps.background.image + ") no-repeat center",
          backgroundSize: '100%'
        };
      }

      return bgStyle;
    };

    _this.onTabClick = function (e, index) {
      var tabLeft = e.currentTarget.offsetLeft;
      var tabWidth = e.currentTarget.offsetWidth;
      e.currentTarget.scrollIntoView(false);

      _this.getProductList(index);

      _this.setState({
        tabLeft: tabLeft,
        tabWidth: tabWidth,
        tabIndex: index
      }, function () {
        _this.getMacy('.tab-item-container');
      });
    };

    return _this;
  }

  RecommendMobile.prototype.componentDidMount = function () {
    var tabIndex = this.state.tabIndex;
    this.getProductList(tabIndex);
    var initTabDom = document.querySelector('.tab-select-wrap .tabTitle:nth-child(1)');
    var tabLeft = initTabDom.offsetLeft;
    var tabWidth = initTabDom.offsetWidth;
    this.setState({
      tabLeft: tabLeft,
      tabWidth: tabWidth
    });
  };

  RecommendMobile.prototype.componentWillReceiveProps = function () {
    var tabIndex = this.state.tabIndex;
    var tabGroupInfo = this.props.panelProps.groupSource[tabIndex];

    if (JSON.stringify(tabGroupInfo) === this.preData) {
      return;
    }

    this.preData = JSON.stringify(tabGroupInfo);
    this.getProductList(tabIndex);
  };

  RecommendMobile.prototype.render = function () {
    var _this = this;

    var panelProps = this.props.panelProps;
    var _a = this.state,
        tabIndex = _a.tabIndex,
        tabLeft = _a.tabLeft,
        tabWidth = _a.tabWidth;
    var bgStyle = this.getBackgroundStyle();
    var products = this.state["products" + tabIndex] || [];
    var isDivide = panelProps.groupSource.length <= 3;
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: "m-recommend-mobile",
      style: bgStyle
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "tab-select-wrap"
    }, panelProps.groupSource.map(function (tab, index) {
      var _image = index == tabIndex && tab.hover.open && tab.hover.image.open ? tab.hover.image : tab.image;

      var _groupName = index == tabIndex && tab.hover.open && tab.hover.groupName.open ? tab.hover.groupName : tab.groupName;

      return /*#__PURE__*/_react["default"].createElement("div", {
        className: "tabTitle",
        onClick: function onClick(e) {
          _this.onTabClick(e, index);

          _mobx.store.setState({
            clickedGroup: tab.id,
            clickedFloor: _mobx.store.getFloorIdByGroupId(tab.id)
          });
        },
        style: {
          flex: ~~isDivide
        }
      }, tab.image.open && _image && /*#__PURE__*/_react["default"].createElement(_components.MetaImage, {
        data: _image
      }), tab.groupName.open && /*#__PURE__*/_react["default"].createElement(_components.MetaText, {
        data: _groupName,
        onTextInput: function onTextInput(text) {
          tab.hover.groupName.text = text;
          tab.groupName.text = text;
        }
      }));
    }), /*#__PURE__*/_react["default"].createElement("div", {
      className: "active-line",
      style: {
        width: tabWidth,
        transform: "translateX(" + tabLeft + "px)",
        background: this.getTabBarActiveColor(panelProps)
      }
    })), /*#__PURE__*/_react["default"].createElement("div", {
      className: "tab-item-container"
    }, products.map(function (item) {
      return /*#__PURE__*/_react["default"].createElement(_ProductItem["default"], {
        key: item.productId,
        data: item,
        onItemClick: function onItemClick() {
          var _a;

          return (0, _coreUtil.clickUrl)("/product/detail/" + item.offerId + "?productId=" + ((_a = item.sppProductId) !== null && _a !== void 0 ? _a : ''));
        },
        panelProps: panelProps.content,
        showProgress: false
      });
    })));
  };

  RecommendMobile.defaultProps = {
    panelProps: {}
  };
  return RecommendMobile;
}(_react["default"].Component);

var _default = RecommendMobile;
exports["default"] = _default;