"use strict";

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

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

var _fdx = require("@whalecloud/fdx");

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

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

var _index = _interopRequireDefault(require("../components/AddImgLink/index"));

var _index2 = _interopRequireDefault(require("../components/BottomButton/index"));

var _index3 = _interopRequireDefault(require("../components/CommonStyle/index"));

var _index4 = _interopRequireDefault(require("../components/ProductList/index"));

var _index5 = _interopRequireDefault(require("../components/ProductModal/index"));

var _MPropertiesBaseComponent = _interopRequireDefault(require("../MPropertiesBaseComponent"));

require("./index.less");

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

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.push.apply(ownKeys, 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); Object.defineProperty(Constructor, "prototype", { writable: false }); 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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); 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; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } 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; }

var MScorllProperties = /*#__PURE__*/function (_MPropertiesBaseCompo) {
  _inherits(MScorllProperties, _MPropertiesBaseCompo);

  var _super = _createSuper(MScorllProperties);

  function MScorllProperties(_props) {
    var _this;

    _classCallCheck(this, MScorllProperties);

    _this = _super.call(this, _props);

    _defineProperty(_assertThisInitialized(_this), "resetProps", function (props) {
      _this.setState(_objectSpread({}, props, {
        imgList: props.imgList ? props.imgList : [],
        productList: props.productList ? props.productList : [],
        imageLocation: props.imageLocation ? props.imageLocation : 'Left',
        slidingMode: props.slidingMode ? props.slidingMode : 'Manual',
        commonConfig: props.commonConfig ? props.commonConfig : {}
      }));
    });

    _defineProperty(_assertThisInitialized(_this), "init", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
      var info, _autoProductList;

      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return (0, _commonUtil.fishFetch)('/h5/offers', {
                campaignType: '4',
                offerIdList: null,
                pageIndex: 1,
                pageSize: 15,
                q: '',
                sortType: '2'
              }, 'POST');

            case 2:
              info = _context.sent;
              _autoProductList = info.pageInfo.list.map(function (m) {
                m.productName = m.offerName;
                m.productImageUrl = m.imgUrl;
                return m;
              });

              _this.setState({
                autoProductList: _autoProductList
              });

              if (_this.state.slidingMode === 'Auto') {
                _this.setState({
                  newProductList: _autoProductList
                });
              }

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

    _defineProperty(_assertThisInitialized(_this), "closeModal", function () {
      _this.setState({
        visible: false
      });
    });

    _defineProperty(_assertThisInitialized(_this), "showModal", function () {
      _this.setState({
        visible: true
      });
    });

    _defineProperty(_assertThisInitialized(_this), "handleModalSave", function (list) {
      _this.setState({
        productList: list,
        newProductList: list
      });
    });

    _defineProperty(_assertThisInitialized(_this), "delProImg", function (index) {
      // eslint-disable-next-line react/no-access-state-in-setstate
      var arr = JSON.parse(JSON.stringify(_this.state.newProductList));
      arr.splice(index, 1);

      _this.setState({
        newProductList: arr
      });

      if (_this.state.slidingMode === 'Auto') {
        _this.setState({
          autoProductList: arr
        });
      } else {
        _this.setState({
          productList: arr
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "itemProUp", function (index) {
      var arr = JSON.parse(JSON.stringify(_this.state.newProductList));
      var _ref2 = [arr[index - 1], arr[index]];
      arr[index] = _ref2[0];
      arr[index - 1] = _ref2[1];

      _this.setState({
        newProductList: arr
      });

      if (_this.state.slidingMode === 'Auto') {
        _this.setState({
          autoProductList: arr
        });
      } else {
        _this.setState({
          productList: arr
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "itemProDown", function (index) {
      var arr = JSON.parse(JSON.stringify(_this.state.newProductList));
      var _ref3 = [arr[index], arr[index + 1]];
      arr[index + 1] = _ref3[0];
      arr[index] = _ref3[1];

      _this.setState({
        newProductList: arr
      });

      if (_this.state.slidingMode === 'Auto') {
        _this.setState({
          autoProductList: arr
        });
      } else {
        _this.setState({
          productList: arr
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onSave", function () {
      var evt = new Event('property-update', {
        bubbles: false
      });
      var productIds = [];
      _this.state.newProductList && _this.state.newProductList.forEach(function (v) {
        productIds.push(v.productId);
      });
      var _state = {
        imgList: _this.state.imgList,
        visible: _this.state.visible,
        imageLocation: _this.state.imageLocation,
        slidingMode: _this.state.slidingMode,
        sourceUrl: _this.state.sourceUrl,
        style: _this.state.style,
        productList: _this.state.slidingMode === 'Auto' ? [] : _this.state.productList
      };
      evt.data = _objectSpread({}, _this.props, _state, {
        productIds: productIds.join(',')
      });
      window.document.dispatchEvent(evt);
    });

    _defineProperty(_assertThisInitialized(_this), "uploadImgUrl", function (index, url) {
      var arr = JSON.parse(JSON.stringify(_this.state.imgList));
      arr[index].imgUrl = url;

      _this.setState({
        imgList: arr
      });
    });

    _defineProperty(_assertThisInitialized(_this), "setImgLink", function (index, value) {
      var arr = JSON.parse(JSON.stringify(_this.state.imgList));
      arr[index].link = value;

      _this.setState({
        imgList: arr
      });
    });

    _defineProperty(_assertThisInitialized(_this), "addNewItem", function () {
      _this.setState({
        imgList: [].concat(_toConsumableArray(_this.state.imgList), [{}])
      });
    });

    _defineProperty(_assertThisInitialized(_this), "previewImg", function (url) {
      window.open(url);
    });

    _defineProperty(_assertThisInitialized(_this), "delImg", function (index) {
      var arr = JSON.parse(JSON.stringify(_this.state.imgList));
      arr[index].imgUrl = '';

      _this.setState({
        imgList: arr
      });
    });

    _defineProperty(_assertThisInitialized(_this), "itemUp", function (index) {
      var arr = JSON.parse(JSON.stringify(_this.state.imgList));
      var _ref4 = [arr[index - 1], arr[index]];
      arr[index] = _ref4[0];
      arr[index - 1] = _ref4[1];

      _this.setState({
        imgList: arr
      });
    });

    _defineProperty(_assertThisInitialized(_this), "itemDown", function (index) {
      var arr = JSON.parse(JSON.stringify(_this.state.imgList));
      var _ref5 = [arr[index], arr[index + 1]];
      arr[index + 1] = _ref5[0];
      arr[index] = _ref5[1];

      _this.setState({
        imgList: arr
      });
    });

    _defineProperty(_assertThisInitialized(_this), "delItem", function (index) {
      var arr = JSON.parse(JSON.stringify(_this.state.imgList));
      arr.splice(index, 1);

      _this.setState({
        imgList: arr
      });
    });

    _defineProperty(_assertThisInitialized(_this), "onChangeSlidingMode", /*#__PURE__*/function () {
      var _ref6 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee2(mode) {
        var _this$state, autoProductList, productList;

        return _regenerator["default"].wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _this$state = _this.state, autoProductList = _this$state.autoProductList, productList = _this$state.productList;

                _this.setState({
                  slidingMode: mode,
                  newProductList: mode === 'Auto' ? autoProductList : productList
                });

              case 2:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));

      return function (_x) {
        return _ref6.apply(this, arguments);
      };
    }());

    _this.state = _objectSpread({
      imgList: [],
      productList: [],
      autoProductList: [],
      newProductList: [],
      visible: false,
      imageLocation: 'Left',
      slidingMode: 'Manual',
      sourceUrl: '',
      commonConfig: {}
    }, _props);
    return _this;
  }

  _createClass(MScorllProperties, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.init();

      if (this.state.slidingMode !== 'Auto') {
        this.setState({
          newProductList: this.state.productList
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$state2 = this.state,
          newProductList = _this$state2.newProductList,
          visible = _this$state2.visible,
          slidingMode = _this$state2.slidingMode;
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: "mScorllWrap"
      }, /*#__PURE__*/_react["default"].createElement(_index3["default"], {
        data: this.state.commonConfig,
        onChange: function onChange(data) {
          _this2.state.commonConfig = data;
        }
      }), /*#__PURE__*/_react["default"].createElement("div", {
        className: "addBut"
      }, /*#__PURE__*/_react["default"].createElement(_index["default"], {
        hasTip: false,
        maxCount: 1,
        setImgLink: this.setImgLink,
        imgList: this.state.imgList,
        uploadImgUrl: this.uploadImgUrl,
        addNewItem: this.addNewItem,
        previewImg: this.previewImg,
        delImg: this.delImg,
        itemUp: this.itemUp,
        itemDown: this.itemDown,
        delItem: this.delItem,
        renderer: this.props.renderer
      })), /*#__PURE__*/_react["default"].createElement(_fdx.Form, {
        layout: "vertical"
      }, /*#__PURE__*/_react["default"].createElement(_fdx.Form.Item, {
        label: "Product Selection"
      }, /*#__PURE__*/_react["default"].createElement(_fdx.Radio.Group, {
        value: slidingMode,
        onChange: function onChange(e) {
          return _this2.onChangeSlidingMode(e.target.value);
        }
      }, /*#__PURE__*/_react["default"].createElement(_fdx.Radio, {
        value: "Auto"
      }, "Auto"), /*#__PURE__*/_react["default"].createElement(_fdx.Radio, {
        value: "Manual"
      }, "Manual")))), slidingMode === 'Auto' ? /*#__PURE__*/_react["default"].createElement("div", null) // <div className="autoProList">
      //   <ProductList productList={newProductList} delImg={this.delProImg} itemUp={this.itemProUp} itemDown={this.itemProDown} />
      // </div>
      : /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_fdx.Row, {
        className: "imgTitle",
        type: "flex",
        justify: "space-between"
      }, /*#__PURE__*/_react["default"].createElement("div", null, "Select Product "), /*#__PURE__*/_react["default"].createElement("div", null, newProductList.length, "/30")), /*#__PURE__*/_react["default"].createElement(_index4["default"], {
        productList: newProductList,
        delImg: this.delProImg,
        itemUp: this.itemProUp,
        itemDown: this.itemProDown
      }), /*#__PURE__*/_react["default"].createElement("div", {
        className: "addBut"
      }, /*#__PURE__*/_react["default"].createElement(_fdx.Button, {
        style: {
          width: '100%'
        },
        onClick: function onClick() {
          _this2.showModal();
        }
      }, /*#__PURE__*/_react["default"].createElement(_fdx.Icon, {
        type: "plus"
      }), " Add Product"))), /*#__PURE__*/_react["default"].createElement(_index5["default"], {
        type: "groupBuy",
        maxSelect: 30,
        defaultList: newProductList,
        handleModalSave: this.handleModalSave,
        closeModal: this.closeModal,
        visible: visible
      }), /*#__PURE__*/_react["default"].createElement(_index2["default"], {
        onSaveClick: this.onSave
      }));
    }
  }]);

  return MScorllProperties;
}(_MPropertiesBaseComponent["default"]);

exports["default"] = MScorllProperties;