"use strict";

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

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

var _fishx = require("fishx");

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

var _IconBase = require("../../../assets/IconBase64");

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

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 _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 = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

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

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

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 = _fdx.Select.Option,
    OptGroup = _fdx.Select.OptGroup;
var InputGroup = _fdx.Input.Group;

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

  var _useState = (0, _react.useState)(defaultList),
      _useState2 = _slicedToArray(_useState, 2),
      selectedList = _useState2[0],
      setSelectedList = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      catgsList = _useState4[0],
      setCatgsList = _useState4[1];

  var _useState5 = (0, _react.useState)([]),
      _useState6 = _slicedToArray(_useState5, 2),
      brandsList = _useState6[0],
      setBrandsList = _useState6[1];

  var _useState7 = (0, _react.useState)([]),
      _useState8 = _slicedToArray(_useState7, 2),
      labelData = _useState8[0],
      setLabelData = _useState8[1];

  var _useState9 = (0, _react.useState)([]),
      _useState10 = _slicedToArray(_useState9, 2),
      selBrandsList = _useState10[0],
      setSelBrandsList = _useState10[1];

  var _useState11 = (0, _react.useState)([]),
      _useState12 = _slicedToArray(_useState11, 2),
      selCatgsList = _useState12[0],
      setSelCatgsList = _useState12[1];

  var _useState13 = (0, _react.useState)({}),
      _useState14 = _slicedToArray(_useState13, 2),
      selLabelData = _useState14[0],
      setSelLabelData = _useState14[1];

  var _useState15 = (0, _react.useState)(''),
      _useState16 = _slicedToArray(_useState15, 2),
      productName = _useState16[0],
      setProductName = _useState16[1];

  var _useState17 = (0, _react.useState)(''),
      _useState18 = _slicedToArray(_useState17, 2),
      productCode = _useState18[0],
      setProductCode = _useState18[1];

  var _useState19 = (0, _react.useState)(''),
      _useState20 = _slicedToArray(_useState19, 2),
      minPrice = _useState20[0],
      setMinPrice = _useState20[1];

  var _useState21 = (0, _react.useState)(''),
      _useState22 = _slicedToArray(_useState21, 2),
      maxPrice = _useState22[0],
      setMaxPrice = _useState22[1];

  var _useState23 = (0, _react.useState)([]),
      _useState24 = _slicedToArray(_useState23, 2),
      promotions = _useState24[0],
      setPromotions = _useState24[1];

  var _useState25 = (0, _react.useState)([]),
      _useState26 = _slicedToArray(_useState25, 2),
      goodsList = _useState26[0],
      setGoodsList = _useState26[1];

  var _useState27 = (0, _react.useState)(false),
      _useState28 = _slicedToArray(_useState27, 2),
      loading = _useState28[0],
      setLoading = _useState28[1];

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

  var changeRowKeys = [];
  var rowSelection = {
    selectedRowKeys: selectedRowKeys,
    onSelect: function onSelect(record, selected, selectedRows, nativeEvent) {
      console.log(record, selected, selectedRows, nativeEvent, 33);

      if (selected) {
        if (selectedList.length === maxSelect) {
          _fdx.message.warning("Max ".concat(maxSelect));

          return;
        }

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

      setSelectedRowKeys(changeRowKeys);
    },
    onChange: function onChange(selectedRowKeys, selectedRows) {
      // if (selectedList.length === maxSelect) {
      //   message.warning(`Max ${maxSelect}`);
      //   return;
      // }
      changeRowKeys = _toConsumableArray(selectedRowKeys); // setSelectedRowKeys([...selectedRowKeys]);

      console.log(selectedList, 231); // setSelectedList([...selectedList,...formatData([...selectedRows.slice(-1)])]);
    },
    getCheckboxProps: function getCheckboxProps(record) {
      return {
        name: record.name
      };
    }
  };

  var _useState31 = (0, _react.useState)({
    pageSize: 20,
    current: 1,
    total: 0
  }),
      _useState32 = _slicedToArray(_useState31, 2),
      paginationParams = _useState32[0],
      setPaginationParams = _useState32[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 = (0, _fishx.useFetch)(function (data) {
    return {
      url: "".concat(window.MParams.MBaseUrl, "/products"),
      method: 'GET',
      params: data
    };
  }, {
    manual: true,
    onSuccess: function onSuccess(result) {
      setLoading(false);
      paginationParams.total = result.total;
      setPaginationParams(paginationParams);
      setGoodsList(result.list || []);
    },
    onError: function onError(res) {
      _fdx.Modal.warning({
        title: res.response.data.message
      });
    }
  });
  var queryOfferCatgs = (0, _fishx.useFetch)(function () {
    return {
      url: '/h5/offers/catgs',
      method: 'GET'
    };
  }, {
    manual: true,
    onSuccess: function onSuccess(result) {
      var arr = [];
      result.forEach(function (f) {
        if (f.children) arr.push.apply(arr, _toConsumableArray(f.children));
      });
      setCatgsList(arr);
    },
    onError: function onError(res) {
      _fdx.Modal.warning({
        title: res.response.data.message
      });
    }
  });
  var queryBrands = (0, _fishx.useFetch)(function () {
    return {
      url: "".concat(window.MParams.MBaseUrl, "/offerdiscatgs/brands"),
      method: 'GET'
    };
  }, {
    manual: true,
    onSuccess: function onSuccess(result) {
      setBrandsList(result);
    },
    onError: function onError(res) {
      _fdx.Modal.warning({
        title: res.response.data.message
      });
    }
  }); // 请求标签

  var queryLabel = (0, _fishx.useFetch)(function (params) {
    return {
      url: "".concat(window.MParams.MBaseUrl, "/labels/list"),
      method: 'get'
    };
  }, {
    manual: true,
    onSuccess: function onSuccess(res) {
      console.log(res, 444);
      setLabelData(res);
    }
  });
  (0, _react.useEffect)(function () {
    queryOfferCatgs.run();
    queryBrands.run();
    queryLabel.run();
  }, []);
  (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);
  }; // useEffect(()=>{
  //   const modalEle = document.querySelector('.ant-modal')
  //   console.log(modalEle,33377)
  // })


  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(_fdx.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(_fdx.Form, {
    layout: "vertical"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Form.Item, {
    label: "Category"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.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(_fdx.Form.Item, {
    label: "Brand"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.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(_fdx.Form.Item, {
    label: "Lable"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.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(_fdx.Form.Item, {
    label: "Price"
  }, /*#__PURE__*/_react["default"].createElement(InputGroup, {
    compact: true
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Input, {
    value: minPrice,
    onChange: function onChange(e) {
      setMinPrice(e.target.value);
    },
    style: {
      width: '38%',
      textAlign: 'center'
    },
    placeholder: "Minimum"
  }), /*#__PURE__*/_react["default"].createElement(_fdx.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(_fdx.Input, {
    value: maxPrice,
    onChange: function onChange(e) {
      setMaxPrice(e.target.value);
    },
    style: {
      width: '38%',
      textAlign: 'center',
      borderLeft: 0
    },
    placeholder: "Maximum"
  }))), /*#__PURE__*/_react["default"].createElement(_fdx.Form.Item, {
    label: "Product Name"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Input, {
    value: productName,
    onChange: function onChange(e) {
      setProductName(e.target.value);
    },
    className: "inputStyle",
    placeholder: "Please Input"
  })), /*#__PURE__*/_react["default"].createElement(_fdx.Form.Item, {
    label: "SKU Code"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Input, {
    value: productCode,
    onChange: function onChange(e) {
      setProductCode(e.target.value);
    },
    className: "inputStyle",
    placeholder: "Please Input"
  })), /*#__PURE__*/_react["default"].createElement(_fdx.Form.Item, {
    label: "Promotions"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.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(_fdx.Button, {
    onClick: function onClick() {
      reset();
    }
  }, "Reset"), /*#__PURE__*/_react["default"].createElement(_fdx.Button, {
    onClick: function onClick() {
      setLoading(true);
      paginationParams.current = 1;
      queryGoods.run({
        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(_fdx.NativeTable, {
    rowKey: "productId",
    loading: loading,
    pagination: _objectSpread({}, paginationParams, {
      onChange: function onChange(page) {
        console.log(page);
        setLoading(true);
        paginationParams.current = page;
        setPaginationParams(paginationParams);
        queryGoods.run({
          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("img", {
      alt: "",
      onClick: function onClick() {
        return delSelectedItem(index);
      },
      className: "selectedItemClose",
      src: _IconBase.closeIcon
    }));
  })))), /*#__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(_fdx.Button, {
    onClick: function onClick() {
      handleModalSave && handleModalSave(selectedList);
      closeModal && closeModal();
    },
    type: "primary",
    style: {
      marginRight: 10
    }
  }, "OK"), /*#__PURE__*/_react["default"].createElement(_fdx.Button, {
    onClick: function onClick() {
      return closeModal && closeModal();
    }
  }, "Cancel")))));
};

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