"use strict";

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

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

var _rest = require("@fishx/rest");

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

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

var _index = _interopRequireDefault(require("../../../../property-panel/components/ProductModal/index"));

var _CommonMaterialLibrary = _interopRequireDefault(require("../components/CommonMaterialLibrary"));

require("./RecPropNode.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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": 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; }

var Option = _fdx.Select.Option;

function RecPropNode(props, ref) {
  var deleteNode = props.deleteNode,
      _props$data = props.data,
      data = _props$data === void 0 ? {} : _props$data;

  var _useState = (0, _react.useState)(data.title || ''),
      _useState2 = _slicedToArray(_useState, 2),
      name = _useState2[0],
      setName = _useState2[1];

  var _useState3 = (0, _react.useState)(data.icon || ''),
      _useState4 = _slicedToArray(_useState3, 2),
      img = _useState4[0],
      setImg = _useState4[1];

  var _useState5 = (0, _react.useState)(data.source || 'I'),
      _useState6 = _slicedToArray(_useState5, 2),
      source = _useState6[0],
      setSource = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      _useState8 = _slicedToArray(_useState7, 2),
      visible = _useState8[0],
      setVisible = _useState8[1];

  var _useState9 = (0, _react.useState)(function () {
    if (data.params) {
      return data.params.products;
    }

    return '';
  }),
      _useState10 = _slicedToArray(_useState9, 2),
      prodIds = _useState10[0],
      setProdIds = _useState10[1];

  var _useState11 = (0, _react.useState)([]),
      _useState12 = _slicedToArray(_useState11, 2),
      selectedProds = _useState12[0],
      setSelectedProds = _useState12[1]; // const uploadProps = {
  //   accept: 'webp,jpg,png',
  //   name: 'file',
  //   action: `${window.MParams.MBaseUrl}/image`,
  //   headers: {
  //     accessToken: localStorage.getItem('accessToken') || '',
  //     'x-csrf-token': localStorage.getItem('X-CSRF-TOKEN') || '',
  //   },
  //   showUploadList: false,
  //   beforeUpload: () => {},
  //   onChange(info) {
  //     if (info.file.status !== 'uploading') {
  //       console.log(info.file, info.fileList);
  //     }
  //     if (info.file.status === 'done') {
  //       setImg(info.file.response.fullPath);
  //     }
  //   },
  // };
  // useEffect(() =>{
  //   setName(data.title)
  //   setImg(data.icon);
  //   setSource(data.source || 'I')
  // },[data])


  var onSourceChange = function onSourceChange(value) {
    setSource(value);
  };

  var handleModalSave = function handleModalSave(list) {
    var ids = list.map(function (prod) {
      return prod.productId;
    }).join(',');
    setProdIds(ids);
  };

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      get: function get() {
        return {
          title: name || 'default name',
          icon: img,
          source: source,
          params: {
            products: prodIds
          }
        };
      }
    };
  });

  var getLength = function getLength() {
    if (!prodIds) {
      return 0;
    }

    return prodIds.split(',').length;
  };

  var onSelectProduct = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
      var _yield$fetch, list;

      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!(prodIds.length > 0)) {
                _context.next = 6;
                break;
              }

              _context.next = 3;
              return (0, _rest.fetch)("".concat(window.MParams.MBaseUrl, "/products"), {
                method: 'GET',
                params: {
                  products: prodIds
                }
              });

            case 3:
              _yield$fetch = _context.sent;
              list = _yield$fetch.list;
              setSelectedProds(list || []);

            case 6:
              setVisible(true);

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

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

  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "nodeWrap"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Form, {
    layout: "vertical"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Form.Item, {
    label: "Label"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Row, null, /*#__PURE__*/_react["default"].createElement(_fdx.Col, {
    span: 20
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Input, {
    value: name,
    onChange: function onChange(event) {
      event.persist();
      setName(event.target.value);
    },
    placeholder: "please input"
  })), /*#__PURE__*/_react["default"].createElement(_fdx.Col, {
    span: 4
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Button, {
    onClick: deleteNode,
    style: {
      padding: '0 10px',
      margin: '0 5px'
    }
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Icon, {
    type: "delete"
  }))))), /*#__PURE__*/_react["default"].createElement(_fdx.Form.Item, {
    label: "Image Setting"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "uploadWrap"
  }, img ? /*#__PURE__*/_react["default"].createElement("div", {
    className: "upload"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "imgModal"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Icon, {
    onClick: function onClick() {
      return window.open(img);
    },
    type: "eye",
    style: {
      color: '#fff',
      fontSize: 16,
      marginRight: 16,
      cursor: 'pointer'
    }
  }), /*#__PURE__*/_react["default"].createElement(_fdx.Icon, {
    onClick: function onClick() {
      return setImg('');
    },
    type: "delete",
    style: {
      color: '#fff',
      fontSize: 16,
      cursor: 'pointer'
    }
  })), /*#__PURE__*/_react["default"].createElement("img", {
    height: "58",
    src: img,
    alt: ""
  })) : /*#__PURE__*/_react["default"].createElement(_CommonMaterialLibrary["default"], {
    maxCount: 1,
    value: {},
    onChange: function onChange(value) {
      console.log(value);

      if (value && value[0]) {
        setImg(value[0].url || '');
      }
    }
  }) // <div className="uploading">
  //   <Upload {...uploadProps}>
  //     <Icon type="plus" style={{ fontSize: 32, color: '#abacb2', cursor: 'pointer' }} />
  //   </Upload>
  // </div>
  )), /*#__PURE__*/_react["default"].createElement(_fdx.Form.Item, {
    label: "Source of product"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Select, {
    showSearch: true,
    style: {
      width: '100%'
    },
    onChange: onSourceChange,
    value: source
  }, /*#__PURE__*/_react["default"].createElement(Option, {
    value: "I"
  }, "Intelligent Recommendation"), /*#__PURE__*/_react["default"].createElement(Option, {
    value: "S"
  }, "Select Product"))), source === 'S' && /*#__PURE__*/_react["default"].createElement(_fdx.Form.Item, {
    label: "Source of product"
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Row, null, /*#__PURE__*/_react["default"].createElement(_fdx.Col, {
    span: 18
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Input, {
    disabled: true,
    value: "Total: ".concat(getLength(), " products"),
    onChange: function onChange(event) {
      event.persist();
      setName(event.target.value);
    },
    placeholder: "please input"
  })), /*#__PURE__*/_react["default"].createElement(_fdx.Col, {
    span: 6
  }, /*#__PURE__*/_react["default"].createElement(_fdx.Button, {
    onClick: onSelectProduct,
    style: {
      padding: '0 10px',
      margin: '0 5px'
    }
  }, "Select"))))), /*#__PURE__*/_react["default"].createElement(_index["default"], {
    maxSelect: 100,
    defaultList: selectedProds,
    handleModalSave: handleModalSave,
    closeModal: function closeModal() {
      return setVisible(false);
    },
    visible: visible
  }));
}

var _default = _react["default"].forwardRef(RecPropNode);

exports["default"] = _default;