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

import { message, Modal } from '@whalecloud/fdx';
import cloneDeep from 'lodash/cloneDeep';
import isEmpty from 'lodash/isEmpty';
import React, { useEffect, useState } from 'react';
import DragAndDropHOC from '../../../layout/MGenerator/DragAndDropHOC';
import CommonAddPicCard from './CommonAddPicCard';
import CommonPicCard from './CommonPicCard';
import { contentCatgTypeMap } from './const';
import ImageModal from './ImageModal';

function CommonMaterialLibrary(props) {
  var _props$value = props.value,
      value = _props$value === void 0 ? [] : _props$value,
      onChange = props.onChange,
      disabled = props.disabled,
      _props$maxCount = props.maxCount,
      maxCount = _props$maxCount === void 0 ? 10 : _props$maxCount,
      _props$size = props.size,
      size = _props$size === void 0 ? 'normal' : _props$size,
      showDefault = props.showDefault,
      _props$type = props.type,
      type = _props$type === void 0 ? contentCatgTypeMap.PICTURE : _props$type;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      visible = _useState2[0],
      setVisible = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      previewVisible = _useState4[0],
      setPreviewVisible = _useState4[1];

  var _useState5 = useState({}),
      _useState6 = _slicedToArray(_useState5, 2),
      selectContent = _useState6[0],
      setSelectContent = _useState6[1];

  var _useState7 = useState([]),
      _useState8 = _slicedToArray(_useState7, 2),
      contents = _useState8[0],
      setContents = _useState8[1];

  useEffect(function () {
    if (!isEmpty(value)) {
      setContents(value);
    }
  }, [value]);

  var onRemove = function onRemove(content) {
    setContents(function (data) {
      var newContents = data.filter(function (item) {
        return item.contentId !== content.contentId;
      });

      if (onChange) {
        onChange(newContents);
      }

      return newContents;
    });
  };

  var onModalOk = function onModalOk(data) {
    if (data && data.length > maxCount) {
      message.warning("No more than ".concat(maxCount, " pictures!"));
      return;
    }

    setContents(function (params) {
      var uids = params.map(function (param) {
        return param.contentId;
      });
      var newContents = [].concat(_toConsumableArray(params), _toConsumableArray(data.filter(function (el) {
        return !uids.includes(el.contentId);
      })));

      if (onChange) {
        onChange(newContents);
      }

      return newContents;
    });
    setVisible(false);
  };

  var onMove = function onMove(dragIndex, hoverIndex) {
    setContents(function (params) {
      var tmp = params[dragIndex];
      params.splice(dragIndex, 1);
      params.splice(hoverIndex, 0, tmp);
      return cloneDeep(params);
    });
  };

  var onSetDefault = function onSetDefault(content) {
    setContents(function (data) {
      var newContents = [content];
      data.forEach(function (item) {
        if (item.contentId !== content.contentId) {
          newContents.push(item);
        }
      });
      return newContents;
    });
  };

  var renderPicCards = function renderPicCards() {
    var component = null;

    if (isEmpty(contents) && !disabled) {
      component = /*#__PURE__*/React.createElement(CommonAddPicCard, {
        onAdd: function onAdd() {
          return !disabled && setVisible(true);
        }
      });
    }

    if (!isEmpty(contents) && (contents.length >= maxCount || disabled)) {
      component = contents.map(function (content, index) {
        return /*#__PURE__*/React.createElement(CommonPicCard, {
          type: "PICTURE",
          index: index,
          size: size,
          key: content.contentId,
          disabled: disabled,
          content: content,
          onSetDefault: onSetDefault,
          onMove: onMove,
          onRemove: onRemove,
          showDefault: showDefault,
          onPreview: function onPreview() {
            setSelectContent(content);
            setPreviewVisible(true);
          }
        });
      });
    }

    if (!isEmpty(contents) && contents.length < maxCount && !disabled) {
      component = /*#__PURE__*/React.createElement(React.Fragment, null, contents.map(function (content, index) {
        return /*#__PURE__*/React.createElement(CommonPicCard, {
          type: "PICTURE",
          index: index,
          size: size,
          key: content.contentId,
          disabled: disabled,
          content: content,
          onSetDefault: onSetDefault,
          onMove: onMove,
          onRemove: onRemove,
          showDefault: showDefault,
          onPreview: function onPreview() {
            setSelectContent(content);
            setPreviewVisible(true);
          }
        });
      }), /*#__PURE__*/React.createElement(CommonAddPicCard, {
        onAdd: function onAdd() {
          return !disabled && setVisible(true);
        }
      }));
    }

    return component;
  };

  var renderVideoCard = function renderVideoCard() {
    var component = null;

    if (isEmpty(contents) && !disabled) {
      component = /*#__PURE__*/React.createElement(CommonAddPicCard, {
        onAdd: function onAdd() {
          return !disabled && setVisible(true);
        }
      });
    }

    if (!isEmpty(contents)) {
      component = /*#__PURE__*/React.createElement(CommonPicCard, {
        type: "VIDEO",
        disabled: disabled,
        content: contents[0],
        onPreview: function onPreview(content) {
          return window.open(content.url);
        },
        onRemove: function onRemove() {
          setContents([]);

          if (onChange) {
            onChange([]);
          }
        }
      });
    }

    return component;
  };

  var getClassName = function getClassName(param) {
    if (param === 'small') {
      return 'upload-list-small';
    }

    if (param === 'table') {
      return 'upload-list-table';
    }

    return null;
  };

  return /*#__PURE__*/React.createElement(DragAndDropHOC, null, /*#__PURE__*/React.createElement("span", {
    className: getClassName(size),
    style: {
      display: 'inline-block',
      width: '100%',
      textAlign: 'center'
    }
  }, type === contentCatgTypeMap.PICTURE && renderPicCards(), type === contentCatgTypeMap.VIDEO && renderVideoCard(), /*#__PURE__*/React.createElement(Modal, {
    visible: previewVisible,
    title: selectContent.name,
    footer: null,
    onCancel: function onCancel() {
      return setPreviewVisible(false);
    }
  }, /*#__PURE__*/React.createElement("img", {
    src: selectContent.url,
    alt: "",
    style: {
      width: '100%'
    }
  })), visible && /*#__PURE__*/React.createElement(ImageModal, {
    visible: true,
    maxCount: maxCount,
    type: type,
    onOk: onModalOk,
    onCancel: function onCancel() {
      return setVisible(false);
    }
  })));
}

export default CommonMaterialLibrary;