import _regeneratorRuntime from "@babel/runtime/regenerator";

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

import { useFetch } from '@fishx/rest';
import { Button, Form, Icon, Input, InputNumber, message, NativeTable, Select, TreeSelect } from '@whalecloud/fdx';
import React, { useEffect, useState } from 'react';
import { ensure } from '../../../utils/commonUtil';
import { formatCurrencyWithSymbol } from '../../../utils/currencyUtil';
import './index.less';

var FilteredProductModal = function FilteredProductModal(props) {
  var handleModalSave = props.handleModalSave,
      closeModal = props.closeModal,
      visible = props.visible,
      onDataChange = props.onDataChange;

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

  var _useState3 = useState([]),
      _useState4 = _slicedToArray(_useState3, 2),
      selectedRowKeys = _useState4[0],
      setSelectedRowKeys = _useState4[1];

  var Option = Select.Option;
  var InputGroup = Input.Group;

  var _useState5 = useState([]),
      _useState6 = _slicedToArray(_useState5, 2),
      tValue = _useState6[0],
      settVal = _useState6[1];

  var _useState7 = useState([]),
      _useState8 = _slicedToArray(_useState7, 2),
      brandId = _useState8[0],
      settBrandId = _useState8[1];

  var _useState9 = useState({}),
      _useState10 = _slicedToArray(_useState9, 2),
      labelId = _useState10[0],
      settLabelId = _useState10[1];

  var _useState11 = useState([]),
      _useState12 = _slicedToArray(_useState11, 2),
      treeData = _useState12[0],
      setTreeData = _useState12[1];

  var _useState13 = useState([]),
      _useState14 = _slicedToArray(_useState13, 2),
      brandData = _useState14[0],
      setBrandData = _useState14[1];

  var _useState15 = useState([]),
      _useState16 = _slicedToArray(_useState15, 2),
      labelData = _useState16[0],
      setLabelData = _useState16[1];

  var _useState17 = useState(''),
      _useState18 = _slicedToArray(_useState17, 2),
      storeName = _useState18[0],
      setStoreName = _useState18[1];

  var _useState19 = useState(''),
      _useState20 = _slicedToArray(_useState19, 2),
      productName = _useState20[0],
      setProductName = _useState20[1];

  var _useState21 = useState(''),
      _useState22 = _slicedToArray(_useState21, 2),
      minimum = _useState22[0],
      setMinimum = _useState22[1];

  var _useState23 = useState(''),
      _useState24 = _slicedToArray(_useState23, 2),
      maximum = _useState24[0],
      setMaximum = _useState24[1];

  var _useState25 = useState([]),
      _useState26 = _slicedToArray(_useState25, 2),
      dataSource = _useState26[0],
      setDataSource = _useState26[1];

  var _useState27 = useState({}),
      _useState28 = _slicedToArray(_useState27, 2),
      promotions = _useState28[0],
      setPromotions = _useState28[1];

  var _useState29 = useState(false),
      _useState30 = _slicedToArray(_useState29, 2),
      loading = _useState30[0],
      setLoading = _useState30[1];

  var _useState31 = useState({
    pageSize: 20,
    current: 1,
    total: 0
  }),
      _useState32 = _slicedToArray(_useState31, 2),
      paginationParams = _useState32[0],
      setPaginationParams = _useState32[1];

  var onChange = function onChange(value) {
    console.log(value);
    settVal(value);
  };

  var handleBrandChange = function handleBrandChange(value, node) {
    // console.log(value,a,b,132)
    settBrandId(node.map(function (v) {
      return {
        key: v.key,
        value: v.value
      };
    }));
  };

  var handleLabelChange = function handleLabelChange(value, node) {
    settLabelId({
      key: node.key,
      value: node.value
    });
  };

  var reset = function reset() {
    settVal([]);
    settBrandId([]);
    settLabelId({});
    setStoreName('');
    setProductName('');
    setMinimum('');
    setMaximum('');
    setDataSource([]);
    setPromotions({});
    onDataChange('', 0);
  }; // const dataSource = [
  //   // {
  //   //   key: '1',
  //   //   imgSrc: 'https://img11.360buyimg.com/mobilecms/s300x300_jfs/t25573/21/996335954/251516/593d93a3/5b84ac4cN64654a51.jpg!q70.jpg',
  //   //   name: 'Jual GEMBOK ALARM REM CAKRAM MACIYNJL GEMBOK ALARM REM CAKRAM MACIYNJL',
  //   //   sku: 'The 27 - inch set shows a fixed good thing',
  //   //   price: '200.00',
  //   //   brand: 'Apple',
  //   //   store: 'OEN Company',
  //   // },
  //   // {
  //   //   key: '2',
  //   //   imgSrc: 'https://img20.360buyimg.com/mobilecms/s300x300_jfs/t1/66959/4/9915/50676/5d789624E6c216310/c669fb95493ddbd3.jpg!q70.jpg',
  //   //   name: 'Jual GEMBOK ALARM REM CAKRAM MACIYNJL GEMBOK ALARM REM CAKRAM MACIYNJL',
  //   //   sku: 'The 27 - inch set shows a fixed good thing - inch set shows a fixed good thing',
  //   //   price: '200.00',
  //   //   brand: 'Apple',
  //   //   store: 'OEN Company',
  //   // },
  //   // {
  //   //   key: '3',
  //   //   imgSrc: 'https://img30.360buyimg.com/ceco/s300x300_jfs/t1/117526/28/14514/205764/5f32348fE84ce22c1/686f80ea0a4d7121.jpg!q70.jpg',
  //   //   name: 'Jual GEMBOK ALARM REM CAKRAM MACIYNJL',
  //   //   sku: 'The 27 - inch set shows a fixed good thing',
  //   //   price: '200.00',
  //   //   brand: 'Apple',
  //   //   store: 'OEN Company',
  //   // },
  //   // {
  //   //   key: '4',
  //   //   imgSrc: 'https://img10.360buyimg.com/ceco/s300x300_jfs/t1/32397/13/12805/60241/5cb8a86eE85d4f52b/f729273f8e028423.jpg!q70.jpg',
  //   //   name: 'Jual GEMBOK ALARM REM CAKRAM MACIYNJL',
  //   //   sku: 'The 27 - inch set shows a fixed good thing',
  //   //   price: '200.00',
  //   //   brand: 'Apple',
  //   //   store: 'OEN Company',
  //   // },
  //   // {
  //   //   key: '5',
  //   //   imgSrc: 'https://img10.360buyimg.com/mobilecms/s300x300_jfs/t1/92763/23/2284/159616/5dce4479E2d9f80cf/653fe954f9ca6b3e.jpg!q70.jpg',
  //   //   name: 'Jual GEMBOK ALARM REM CAKRAM MACIYNJL',
  //   //   sku: 'The 27 - inch set shows a fixed good thing',
  //   //   price: '200.00',
  //   //   brand: 'Apple',
  //   //   store: 'OEN Company',
  //   // },
  // ];


  var columns = [{
    title: 'Image',
    dataIndex: 'productImageUrl',
    key: 'productImageUrl',
    render: function render(productImageUrl) {
      return /*#__PURE__*/React.createElement("img", {
        width: "52",
        src: productImageUrl,
        alt: ""
      });
    },
    width: 90
  }, {
    title: 'Product Name',
    dataIndex: 'productName',
    key: 'productName',
    ellipsis: true
  }, {
    title: 'SKU',
    dataIndex: 'attrValues',
    key: 'attrValues',
    ellipsis: true
  }, {
    title: 'Price',
    dataIndex: 'salesPrice',
    key: 'salesPrice',
    render: function render(salesPrice) {
      return /*#__PURE__*/React.createElement("span", null, formatCurrencyWithSymbol(salesPrice));
    }
  }, {
    title: 'Brand',
    dataIndex: 'brandName',
    key: 'brandName',
    ellipsis: true
  }, {
    title: 'Store',
    dataIndex: 'storeName',
    key: 'storeName',
    ellipsis: true
  }]; // 请求类目

  var queryCategory = useFetch(function (params) {
    return {
      url: "".concat(window.MParams.MBaseUrl, "/offercatgs/list"),
      method: 'get'
    };
  }, {
    manual: true,
    onSuccess: function onSuccess(res) {
      console.log(res, 7878);

      function listToTree(list) {
        var map = {};
        var node;
        var tree = [];
        var i;
        var nList = [];

        for (i = 0; i < list.length; i++) {
          map[list[i].catgId] = list[i];
          list[i].children = [];
        }

        for (i = 0; i < list.length; i += 1) {
          node = {
            title: list[i].catgName,
            value: list[i].catgId,
            key: list[i].catgId,
            children: list[i].children
          };

          if (list[i].parentCatgId !== null) {
            map[list[i].parentCatgId] && map[list[i].parentCatgId].children.push(node);
          } else {
            tree.push(node);
          }
        }

        return tree;
      }

      setTreeData(listToTree(res));
    }
  }); // 请求品牌

  var queryBrand = useFetch(function (params) {
    return {
      url: "".concat(window.MParams.MBaseUrl, "/brands/list"),
      method: 'get'
    };
  }, {
    manual: true,
    onSuccess: function onSuccess(res) {
      console.log(res, 333);
      setBrandData(res);
    }
  }); // 请求标签

  var queryLabel = 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);
    }
  }); // 搜索商品

  var queryOffers = useFetch(function (params) {
    return {
      url: "".concat(window.MParams.MBaseUrl, "/products"),
      method: 'GET',
      params: params
    };
  }, {
    manual: true
  });

  var JsonToUrl = function JsonToUrl(data) {
    var tempArr = [];

    for (var i in data) {
      var key = encodeURIComponent(i);
      var value = encodeURIComponent(data[i]);
      tempArr.push("".concat(key, "=").concat(value));
    }

    var urlParamsStr = tempArr.join('&');
    return urlParamsStr;
  };

  var loadGoods = function loadGoods() {
    setLoading(true);
    return new Promise( /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(resolve, reject) {
        var precision, res;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                precision = Math.pow(10, ensure(function () {
                  return window.ecommerce.precision;
                }, '0'));
                _context.next = 3;
                return queryOffers.run({
                  catgIds: tValue.join(','),
                  brandIds: brandId.map(function (v) {
                    return v.key;
                  }).join(','),
                  labelIds: labelId.key,
                  productName: productName,
                  minPrice: minimum * precision || '',
                  maxPrice: maximum * precision || '',
                  // storeName:storeName,
                  cmpTypeId: promotions.key || '',
                  pageSize: paginationParams.pageSize,
                  pageIndex: paginationParams.current,
                  state: 'A'
                });

              case 3:
                res = _context.sent;
                setLoading(false);
                console.log(res, 3344);
                paginationParams.total = res.total;

                if (res && res.list && res.list.length > 0) {
                  setDataSource(res.list);
                  resolve({
                    url: JsonToUrl({
                      catgIds: tValue.join(',') || '',
                      brandIds: brandId.map(function (v) {
                        return v.key;
                      }).join(',') || '',
                      labelIds: labelId.key || '',
                      productName: productName || '',
                      minPrice: minimum * precision || '',
                      maxPrice: maximum * precision || '',
                      storeName: storeName || '',
                      cmpTypeId: promotions.key || '',
                      state: 'A'
                    }),
                    total: res.total
                  });
                } else {
                  setDataSource([]);
                  resolve({
                    total: 0
                  });
                }

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

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

  useEffect(function () {
    queryCategory.run();
    queryBrand.run();
    queryLabel.run(); // queryOffers.run({q:2,operationType:'mobile'})
  }, []);
  return /*#__PURE__*/React.createElement("div", {
    className: "filteredProductModal"
  }, /*#__PURE__*/React.createElement("div", {
    className: "proModalWrap"
  }, /*#__PURE__*/React.createElement("div", {
    className: "info"
  }, /*#__PURE__*/React.createElement(Icon, {
    style: {
      color: '#4477EE',
      fontSize: 16,
      marginRight: 4
    },
    type: "info-circle",
    theme: "filled"
  }), "The product quantity will be automatically updated with the items that meet the category conditions."), /*#__PURE__*/React.createElement("div", {
    className: "filteredProductModalContent"
  }, /*#__PURE__*/React.createElement("div", {
    className: "leftCot"
  }, /*#__PURE__*/React.createElement(Form, {
    layout: "vertical"
  }, /*#__PURE__*/React.createElement(Form.Item, {
    label: "Category"
  }, /*#__PURE__*/React.createElement(TreeSelect, {
    style: {
      width: 'calc(100% - 16px)'
    },
    value: tValue,
    dropdownStyle: {
      maxHeight: 400,
      overflow: 'auto'
    },
    treeData: treeData,
    placeholder: "Please select",
    treeDefaultExpandAll: true,
    allowClear: true,
    multiple: true,
    onChange: onChange
  })), /*#__PURE__*/React.createElement(Form.Item, {
    label: "Brand"
  }, /*#__PURE__*/React.createElement(Select, {
    mode: "multiple",
    className: "inputStyle",
    placeholder: "Please select",
    value: brandId.map(function (v) {
      return v.value;
    }),
    defaultValue: [],
    onChange: handleBrandChange
  }, brandData && brandData.length > 0 && brandData.map(function (v) {
    return /*#__PURE__*/React.createElement(Option, {
      key: v.brandId,
      value: v.brandName
    }, v.brandName);
  }))), /*#__PURE__*/React.createElement(Form.Item, {
    label: "Lable"
  }, /*#__PURE__*/React.createElement(Select, {
    value: labelId.value,
    defaultValue: [],
    placeholder: "Please select",
    className: "inputStyle",
    onChange: handleLabelChange
  }, labelData && labelData.length > 0 && labelData.map(function (v) {
    return /*#__PURE__*/React.createElement(Option, {
      key: v.labelId,
      value: v.labelName
    }, v.labelName);
  }))), /*#__PURE__*/React.createElement(Form.Item, {
    label: "Price"
  }, /*#__PURE__*/React.createElement(InputGroup, {
    compact: true
  }, /*#__PURE__*/React.createElement(InputNumber, {
    value: minimum,
    min: 0,
    style: {
      width: '35%',
      textAlign: 'center'
    },
    placeholder: "0",
    onChange: function onChange(value) {
      setMinimum(value);
    }
  }), /*#__PURE__*/React.createElement(Input, {
    style: {
      width: '20%',
      borderLeft: 0,
      pointerEvents: 'none',
      backgroundColor: '#fff'
    },
    placeholder: "~",
    disabled: true
  }), /*#__PURE__*/React.createElement(InputNumber, {
    value: maximum,
    min: 0,
    style: {
      width: '38%',
      textAlign: 'center',
      borderLeft: 0
    },
    placeholder: "0",
    onChange: function onChange(value) {
      setMaximum(value);
    }
  }))), /*#__PURE__*/React.createElement(Form.Item, {
    label: "Product Name"
  }, /*#__PURE__*/React.createElement(Input, {
    value: productName,
    className: "inputStyle",
    placeholder: "Please Input",
    onChange: function onChange(e) {
      setProductName(e.currentTarget.value);
    }
  })), /*#__PURE__*/React.createElement(Form.Item, {
    label: "Promotions"
  }, /*#__PURE__*/React.createElement(Select, {
    value: promotions.value,
    defaultValue: [],
    className: "inputStyle",
    placeholder: "Please select",
    onChange: function onChange(value, node) {
      setPromotions({
        value: node.value,
        key: node.key
      });
    }
  }, /*#__PURE__*/React.createElement(Option, {
    value: "Flash Sale",
    key: "2"
  }, "Flash Sale"), /*#__PURE__*/React.createElement(Option, {
    value: "Group By",
    key: "4"
  }, "Group By"))), /*#__PURE__*/React.createElement("div", {
    className: "buttonStyle"
  }, /*#__PURE__*/React.createElement(Button, {
    onClick: function onClick() {
      reset();
    }
  }, "Cancel"), /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    style: {
      marginRight: 8
    },
    onClick: function onClick() {
      paginationParams.current = 1;
      loadGoods().then(function (res) {
        if (res.total !== 0) {
          onDataChange("filter-".concat(res.url), res.total);
        } else {
          onDataChange('', res.total);
          message.warn('no goods!');
        }
      });
    }
  }, "Load Products")))), /*#__PURE__*/React.createElement("div", {
    className: "rightCot"
  }, /*#__PURE__*/React.createElement(NativeTable, {
    dataSource: dataSource,
    columns: columns,
    loading: loading,
    scroll: {
      y: 450
    },
    pagination: _objectSpread({}, paginationParams, {
      onChange: function onChange(page) {
        paginationParams.current = page;
        loadGoods();
      }
    })
  })))));
};

export default FilteredProductModal;