"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

var _antd = require("antd");

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

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

var _Iconfont = _interopRequireDefault(require("../Iconfont"));

var _currencyUtil = require("../../utils/currencyUtil");

require("./index.less");

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

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

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 precision = (0, _currencyUtil.getPrecision)();

var formatData = function formatData(list) {
  list.map(function (item) {
    item.preSalesPrice = (0, _currencyUtil.formatCurrencyWithSymbol)(item.salesPrice);
    item.preMarketPrice = (0, _currencyUtil.formatCurrencyWithSymbol)(item.marketPrice);
  });
  return list;
};

var promType = {
  FLASH_SALE: '2',
  GROUP_BUY: '4'
};
var Option = _antd.Select.Option,
    OptGroup = _antd.Select.OptGroup;
var InputGroup = _antd.Input.Group;

var ProductModal = function ProductModal(props) {
  var handleModalSave = props.handleModalSave,
      closeModal = props.closeModal,
      visible = props.visible,
      _a = props.defaultList,
      defaultList = _a === void 0 ? [] : _a,
      _b = props.maxSelect,
      maxSelect = _b === void 0 ? 20 : _b;

  var _c = (0, _react.useState)(defaultList),
      selectedList = _c[0],
      setSelectedList = _c[1];

  var _d = (0, _react.useState)([]),
      catgsList = _d[0],
      setCatgsList = _d[1];

  var _e = (0, _react.useState)([]),
      brandsList = _e[0],
      setBrandsList = _e[1];

  var _f = (0, _react.useState)([]),
      labelData = _f[0],
      setLabelData = _f[1];

  var _g = (0, _react.useState)([]),
      selBrandsList = _g[0],
      setSelBrandsList = _g[1];

  var _h = (0, _react.useState)([]),
      selCatgsList = _h[0],
      setSelCatgsList = _h[1];

  var _j = (0, _react.useState)({}),
      selLabelData = _j[0],
      setSelLabelData = _j[1];

  var _k = (0, _react.useState)(''),
      productName = _k[0],
      setProductName = _k[1];

  var _l = (0, _react.useState)(''),
      productCode = _l[0],
      setProductCode = _l[1];

  var _m = (0, _react.useState)(''),
      minPrice = _m[0],
      setMinPrice = _m[1];

  var _o = (0, _react.useState)(''),
      maxPrice = _o[0],
      setMaxPrice = _o[1];

  var _p = (0, _react.useState)([]),
      promotions = _p[0],
      setPromotions = _p[1];

  var _q = (0, _react.useState)([]),
      goodsList = _q[0],
      setGoodsList = _q[1];

  var _r = (0, _react.useState)(false),
      loading = _r[0],
      setLoading = _r[1];

  var _s = (0, _react.useState)(defaultList.map(function (v) {
    return v.productId;
  })),
      selectedRowKeys = _s[0],
      setSelectedRowKeys = _s[1];

  var rowSelection = {
    selectedRowKeys: selectedRowKeys,
    onSelect: function onSelect(record, selected, selectedRows) {
      if (selected) {
        if (selectedList.length === maxSelect) {
          _antd.message.warning("Max " + maxSelect);

          return;
        }

        if (selectedList.length < maxSelect) {
          setSelectedList(__spreadArrays(selectedList, formatData([record])));
        }
      } else {
        setSelectedList(selectedList.filter(function (v) {
          return v.productId !== record.productId;
        }));
      }

      setSelectedRowKeys(selectedRows.map(function (v) {
        return v === null || v === void 0 ? void 0 : v.productId;
      }));
    },
    getCheckboxProps: function getCheckboxProps(record) {
      return {
        name: record.name
      };
    }
  };

  var _t = (0, _react.useState)({
    pageSize: 20,
    current: 1,
    total: 0
  }),
      paginationParams = _t[0],
      setPaginationParams = _t[1];

  var delSelectedItem = function delSelectedItem(index) {
    console.log(selectedRowKeys, index, 2223);
    var rowKeys = JSON.parse(JSON.stringify(selectedRowKeys));
    rowKeys.splice(index, 1);
    setSelectedRowKeys(rowKeys);
    var rows = JSON.parse(JSON.stringify(selectedList));
    rows.splice(index, 1);
    setSelectedList(rows);
  }; // 请求商品列表


  var queryGoods = function queryGoods(data) {
    return __awaiter(void 0, void 0, void 0, function () {
      var res;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            return [4
            /*yield*/
            , (0, _commonUtil.commonFetch)(window.magicDesign.MBaseUrl + "/products", data, 'GET')];

          case 1:
            res = _a.sent();
            setLoading(false);
            paginationParams.total = res.total;
            setPaginationParams(paginationParams);
            setGoodsList(res.list || []);
            return [2
            /*return*/
            ];
        }
      });
    });
  }; // 请求类目


  var queryOfferCatgs = function queryOfferCatgs() {
    return __awaiter(void 0, void 0, void 0, function () {
      var res, arr;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            return [4
            /*yield*/
            , (0, _commonUtil.commonFetch)(window.magicDesign.MBaseUrl + "/h5/offers/catgs", {}, 'GET')];

          case 1:
            res = _a.sent();
            arr = [];
            res.forEach(function (f) {
              if (f.children) arr.push.apply(arr, f.children);
            });
            setCatgsList(arr);
            return [2
            /*return*/
            ];
        }
      });
    });
  }; // 请求品牌


  var queryBrands = function queryBrands() {
    return __awaiter(void 0, void 0, void 0, function () {
      var res;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            return [4
            /*yield*/
            , (0, _commonUtil.commonFetch)(window.magicDesign.MBaseUrl + "/offerdiscatgs/brands", {}, 'GET')];

          case 1:
            res = _a.sent();
            setBrandsList(res);
            return [2
            /*return*/
            ];
        }
      });
    });
  }; // 请求标签


  var queryLabel = function queryLabel() {
    return __awaiter(void 0, void 0, void 0, function () {
      var res;
      return __generator(this, function (_a) {
        switch (_a.label) {
          case 0:
            return [4
            /*yield*/
            , (0, _commonUtil.commonFetch)(window.magicDesign.MBaseUrl + "/labels/list", {}, 'GET')];

          case 1:
            res = _a.sent();
            setLabelData(res);
            return [2
            /*return*/
            ];
        }
      });
    });
  };

  (0, _react.useEffect)(function () {
    queryOfferCatgs();
    queryBrands();
    queryLabel();
  }, []);
  (0, _react.useEffect)(function () {
    setSelectedList(defaultList);
    setSelectedRowKeys(defaultList.map(function (v) {
      return v.productId;
    }));

    if (props.type === 'groupBuy') {
      setPromotions(promType.GROUP_BUY);
    }
  }, [visible]);

  var reset = function reset() {
    setSelBrandsList([]);
    setSelCatgsList([]);
    setSelLabelData([]);
    setProductName('');
    setProductCode('');
    setMinPrice('');
    setMaxPrice('');
    setPromotions(props.type === 'groupBuy' ? promType.GROUP_BUY : null);
  };

  var columns = [{
    title: 'Image',
    dataIndex: 'productImageUrl',
    key: 'productImageUrl',
    render: function render(productImageUrl) {
      return /*#__PURE__*/_react["default"].createElement("span", {
        className: "proImg",
        style: {
          backgroundImage: "url(" + productImageUrl + ")"
        }
      });
    },
    width: 90
  }, {
    title: 'Product Name',
    dataIndex: 'productName',
    key: 'productName',
    render: function render(text, record) {
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
        className: "proName"
      }, record.productName), /*#__PURE__*/_react["default"].createElement("span", {
        className: "proCode"
      }, record.productCode));
    },
    width: 130
  }, {
    title: 'SKU',
    dataIndex: 'attrValues',
    key: 'attrValues',
    ellipsis: true
  }, {
    title: 'Price',
    dataIndex: 'salesPrice',
    key: 'salesPrice',
    render: function render(text, record) {
      return /*#__PURE__*/_react["default"].createElement("span", null, (0, _currencyUtil.formatCurrencyWithSymbol)(record.specialPriceProd ? record.specialPriceProd.specialPrice : record.salesPrice));
    }
  }, {
    title: 'Brand',
    dataIndex: 'brandName',
    key: 'brandName',
    ellipsis: true
  }, {
    title: 'Store',
    dataIndex: 'storeName',
    key: 'storeName',
    ellipsis: true
  }];

  var onResetQryCondition = function onResetQryCondition() {
    setProductName('');
    setPromotions(null);
    setMinPrice('');
    setMaxPrice('');
    setSelBrandsList([]);
    setSelCatgsList([]);
    setSelLabelData([]);
  };

  return /*#__PURE__*/_react["default"].createElement(_antd.Modal, {
    cancelText: "Cancel",
    draggable: false,
    footer: null,
    okText: "OK",
    onCancel: closeModal,
    onOk: handleModalSave,
    title: "Product Select",
    visible: visible,
    width: "auto",
    wrapClassName: "modalCot"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "proModalWrap"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "content"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "leftCot"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Form, {
    layout: "vertical"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "Category"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Select, {
    className: "inputStyle",
    mode: "multiple",
    onChange: function onChange(value, option) {
      setSelCatgsList(value);
    },
    placeholder: "Please select",
    value: selCatgsList
  }, catgsList.map(function (item) {
    return /*#__PURE__*/_react["default"].createElement(OptGroup, {
      key: item.model.catgId,
      label: item.model.catgName
    }, (item.children || []).map(function (i) {
      return /*#__PURE__*/_react["default"].createElement(Option, {
        key: i.model.catgId,
        value: i.model.catgId
      }, i.model.catgName);
    }));
  }))), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "Brand"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Select, {
    className: "inputStyle",
    mode: "multiple",
    onChange: function onChange(value, option) {
      setSelBrandsList(value);
    },
    placeholder: "Please select",
    value: selBrandsList
  }, brandsList.map(function (item, index) {
    return /*#__PURE__*/_react["default"].createElement(Option, {
      key: item.catgId,
      value: item.brandId
    }, item.brandName);
  }))), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "Lable"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Select, {
    className: "inputStyle",
    defaultValue: selLabelData.children || null,
    onChange: function onChange(v, o) {
      console.log(v, o, 33);
      setSelLabelData(o);
    },
    placeholder: "Please Select",
    value: selLabelData.children
  }, labelData && labelData.length > 0 && labelData.map(function (v) {
    return /*#__PURE__*/_react["default"].createElement(Option, {
      key: v.labelId,
      value: v.labelId
    }, v.labelName);
  }))), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "Price"
  }, /*#__PURE__*/_react["default"].createElement(InputGroup, {
    compact: true
  }, /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    onChange: function onChange(e) {
      setMinPrice(e.target.value);
    },
    placeholder: "Minimum",
    style: {
      width: '38%',
      textAlign: 'center'
    },
    value: minPrice
  }), /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    disabled: true,
    placeholder: "~",
    style: {
      width: '20%',
      borderLeft: 0,
      pointerEvents: 'none',
      backgroundColor: '#fff',
      borderTop: '1px solid #d4d4d4',
      borderBottom: '1px solid #d4d4d4'
    }
  }), /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    onChange: function onChange(e) {
      setMaxPrice(e.target.value);
    },
    placeholder: "Maximum",
    style: {
      width: '38%',
      textAlign: 'center',
      borderLeft: 0
    },
    value: maxPrice
  }))), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "Product Name"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    className: "inputStyle",
    onChange: function onChange(e) {
      setProductName(e.target.value);
    },
    placeholder: "Please Input",
    value: productName
  })), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "SKU Code"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    className: "inputStyle",
    onChange: function onChange(e) {
      setProductCode(e.target.value);
    },
    placeholder: "Please Input",
    value: productCode
  })), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "Promotions"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Select, {
    className: "inputStyle",
    defaultValue: promotions,
    onChange: function onChange(value) {
      setPromotions(value);
    },
    placeholder: "Please select",
    value: promotions
  }, props.type !== 'groupBuy' && /*#__PURE__*/_react["default"].createElement(Option, {
    value: promType.FLASH_SALE
  }, "Flash Sale"), /*#__PURE__*/_react["default"].createElement(Option, {
    value: promType.GROUP_BUY
  }, "Group Buy"))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "buttonStyle"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Button, {
    onClick: function onClick() {
      reset();
    }
  }, "Reset"), /*#__PURE__*/_react["default"].createElement(_antd.Button, {
    onClick: function onClick() {
      setLoading(true);
      paginationParams.current = 1;
      queryGoods({
        productName: productName,
        productCode: productCode,
        cmpTypeId: promotions || '',
        minPrice: minPrice === '' ? '' : minPrice * Math.pow(10, precision),
        maxPrice: maxPrice === '' ? '' : maxPrice * Math.pow(10, precision),
        catgIds: selCatgsList.join(','),
        brandIds: selBrandsList.join(','),
        labelIds: selLabelData.value || '',
        pageSize: paginationParams.pageSize,
        pageIndex: paginationParams.current,
        state: 'A'
      });
    },
    style: {
      marginRight: 8
    },
    type: "primary"
  }, "Query")))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "rightCot"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Table, {
    columns: columns,
    dataSource: goodsList,
    loading: loading,
    pagination: __assign(__assign({}, paginationParams), {
      onChange: function onChange(page) {
        console.log(page);
        setLoading(true);
        paginationParams.current = page;
        setPaginationParams(paginationParams);
        queryGoods({
          productName: productName,
          productCode: productCode,
          cmpTypeId: promotions || '',
          minPrice: minPrice === '' ? '' : minPrice * Math.pow(10, precision),
          maxPrice: maxPrice === '' ? '' : maxPrice * Math.pow(10, precision),
          catgIds: selCatgsList.join(','),
          brandIds: selBrandsList.join(','),
          labelIds: selLabelData.value || '',
          pageSize: paginationParams.pageSize,
          pageIndex: paginationParams.current,
          state: 'A'
        });
      }
    }),
    rowKey: "productId",
    rowSelection: rowSelection,
    scroll: {
      y: 300
    }
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "selectedCot"
  }, selectedList.map(function (item, index) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      key: index,
      className: "selectedItem"
    }, /*#__PURE__*/_react["default"].createElement("img", {
      alt: "",
      className: "selectedItemImg " + (item.state !== 'A' ? 'invalid' : ''),
      src: item.productImageUrl,
      title: item.productName
    }), /*#__PURE__*/_react["default"].createElement(_Iconfont["default"], {
      className: "selectedItemClose",
      color: "#000",
      onClick: function onClick() {
        return delSelectedItem(index);
      },
      size: 12,
      type: "icon-close"
    }));
  })))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "footer"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "total"
  }, "Selected", ' ', /*#__PURE__*/_react["default"].createElement("span", {
    className: "totalNum"
  }, selectedList.length, "/", maxSelect)), /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_antd.Button, {
    onClick: function onClick() {
      handleModalSave && handleModalSave(selectedList);
      closeModal && closeModal();
    },
    style: {
      marginRight: 10
    },
    type: "primary"
  }, "OK"), /*#__PURE__*/_react["default"].createElement(_antd.Button, {
    onClick: function onClick() {
      return closeModal && closeModal();
    }
  }, "Cancel")))));
};

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