"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 _commonUtil = require("../../utils/commonUtil");

var _antd = require("antd");

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

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 __spreadArray = void 0 && (void 0).__spreadArray || function (to, from, pack) {
  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
    if (ar || !(i in from)) {
      if (!ar) ar = Array.prototype.slice.call(from, 0, i);
      ar[i] = from[i];
    }
  }
  return to.concat(ar || Array.prototype.slice.call(from));
};

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 ".concat(maxSelect));

          return;
        }

        if (selectedList.length < maxSelect) {
          setSelectedList(__spreadArray(__spreadArray([], selectedList, true), formatData([record]), true));
        }
      } 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)("".concat(window.MParams.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)("".concat(window.MParams.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)("".concat(window.MParams.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)("".concat(window.MParams.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(".concat(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, {
    title: "Product Select",
    okText: "OK",
    cancelText: "Cancel",
    width: "1000",
    wrapClassName: "modalCot",
    visible: visible,
    onOk: handleModalSave,
    draggable: false,
    onCancel: closeModal,
    footer: null
  }, /*#__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, {
    mode: "multiple",
    className: "inputStyle",
    placeholder: "Please select",
    value: selCatgsList,
    onChange: function onChange(value, option) {
      setSelCatgsList(value);
    }
  }, catgsList.map(function (item) {
    return /*#__PURE__*/_react["default"].createElement(OptGroup, {
      label: item.model.catgName,
      key: item.model.catgId
    }, (item.children || []).map(function (i) {
      return /*#__PURE__*/_react["default"].createElement(Option, {
        value: i.model.catgId,
        key: i.model.catgId
      }, i.model.catgName);
    }));
  }))), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "Brand"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Select, {
    mode: "multiple",
    className: "inputStyle",
    placeholder: "Please select",
    value: selBrandsList,
    onChange: function onChange(value, option) {
      setSelBrandsList(value);
    }
  }, 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, {
    defaultValue: selLabelData.children || null,
    value: selLabelData.children,
    placeholder: "Please Select",
    className: "inputStyle",
    onChange: function onChange(v, o) {
      console.log(v, o, 33);
      setSelLabelData(o);
    }
  }, 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, {
    value: minPrice,
    onChange: function onChange(e) {
      setMinPrice(e.target.value);
    },
    style: {
      width: '38%',
      textAlign: 'center'
    },
    placeholder: "Minimum"
  }), /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    style: {
      width: '20%',
      borderLeft: 0,
      pointerEvents: 'none',
      backgroundColor: '#fff',
      borderTop: '1px solid #d4d4d4',
      borderBottom: '1px solid #d4d4d4'
    },
    placeholder: "~",
    disabled: true
  }), /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    value: maxPrice,
    onChange: function onChange(e) {
      setMaxPrice(e.target.value);
    },
    style: {
      width: '38%',
      textAlign: 'center',
      borderLeft: 0
    },
    placeholder: "Maximum"
  }))), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "Product Name"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    value: productName,
    onChange: function onChange(e) {
      setProductName(e.target.value);
    },
    className: "inputStyle",
    placeholder: "Please Input"
  })), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "SKU Code"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    value: productCode,
    onChange: function onChange(e) {
      setProductCode(e.target.value);
    },
    className: "inputStyle",
    placeholder: "Please Input"
  })), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: "Promotions"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Select, {
    defaultValue: promotions,
    value: promotions,
    className: "inputStyle",
    placeholder: "Please select",
    onChange: function onChange(value) {
      setPromotions(value);
    }
  }, 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'
      });
    },
    type: "primary",
    style: {
      marginRight: 8
    }
  }, "Query")))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "rightCot"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Table, {
    rowKey: "productId",
    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'
        });
      }
    }),
    scroll: {
      y: 300
    },
    rowSelection: rowSelection,
    dataSource: goodsList,
    columns: columns
  }), /*#__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", {
      className: "selectedItemImg ".concat(item.state !== 'A' ? 'invalid' : ''),
      title: item.productName,
      src: item.productImageUrl,
      alt: ""
    }), /*#__PURE__*/_react["default"].createElement(_Iconfont["default"], {
      onClick: function onClick() {
        return delSelectedItem(index);
      },
      className: "selectedItemClose",
      color: "#000",
      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();
    },
    type: "primary",
    style: {
      marginRight: 10
    }
  }, "OK"), /*#__PURE__*/_react["default"].createElement(_antd.Button, {
    onClick: function onClick() {
      return closeModal && closeModal();
    }
  }, "Cancel")))));
};

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