"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getBase64 = getBase64;
exports.default = exports.imgAccept = exports.Dragger = void 0;

require("@parallel-line/common/es/common/spin/style");

var _spin = _interopRequireDefault(require("@parallel-line/common/es/common/spin"));

require("antd/es/message/style");

var _message2 = _interopRequireDefault(require("antd/es/message"));

require("antd/es/upload/style");

var _upload = _interopRequireDefault(require("antd/es/upload"));

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

var _classnames = _interopRequireDefault(require("classnames"));

var _lodashEs = require("lodash-es");

var _ahooks = require("ahooks");

var _icons = require("@ant-design/icons");

var _utils = require("@parallel-line/utils");

var _hooks = require("@parallel-line/common/es/hooks");

var _icons2 = require("@parallel-line/icons");

var _image = _interopRequireDefault(require("../image"));

var _excluded = ["data", "prefixCls", "disabled", "serviceName", "moduleName", "fileSource", "value", "defaultValue", "onChange", "businessId"];

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 _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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(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 _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 Dragger = _upload.default.Dragger;
exports.Dragger = Dragger;
var imgAccept = ['image/jpeg', 'image/png', 'image/jpg'];
exports.imgAccept = imgAccept;

function getBase64(img, callback) {
  var reader = new FileReader();
  reader.addEventListener('load', function () {
    return callback(reader.result);
  });
  reader.readAsDataURL(img);
}

var Placeholder = function Placeholder(_ref) {
  var disabled = _ref.disabled,
      prefixCls = _ref.prefixCls,
      className = _ref.className,
      width = _ref.width,
      height = _ref.height,
      style = _ref.style,
      children = _ref.children,
      text = _ref.text;

  var _useNamespace = (0, _hooks.useNamespace)('upload', prefixCls),
      _useNamespace2 = _slicedToArray(_useNamespace, 2),
      bem = _useNamespace2[1];

  return /*#__PURE__*/React.createElement("div", {
    className: (0, _classnames.default)(bem('placeholder', {
      disabled: disabled
    }), className),
    style: _objectSpread({
      width: width,
      height: height
    }, style)
  }, /*#__PURE__*/React.createElement("span", {
    className: bem('placeholder-icon')
  }, /*#__PURE__*/React.createElement(_icons2.PlusCircleFill, null)), /*#__PURE__*/React.createElement("span", null, children !== null && children !== void 0 ? children : text));
};

function useShamMemo(factory) {
  return factory();
}

var Upload = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var _global$companyInfo$i, _global$companyInfo;

  var headers = props.headers,
      _props$listType = props.listType,
      listType = _props$listType === void 0 ? 'text' : _props$listType,
      _props$maxCount = props.maxCount,
      maxCount = _props$maxCount === void 0 ? -1 : _props$maxCount,
      placeholderProps = props.placeholderProps,
      _props$accessTokenKey = props.accessTokenKey,
      accessTokenKey = _props$accessTokenKey === void 0 ? 'pxx_accessToken' : _props$accessTokenKey;

  var _data = props.data,
      prefixCls = props.prefixCls,
      disabled = props.disabled,
      serviceName = props.serviceName,
      moduleName = props.moduleName,
      _props$fileSource = props.fileSource,
      fileSource = _props$fileSource === void 0 ? 12 : _props$fileSource,
      value = props.value,
      defaultValue = props.defaultValue,
      onChange = props.onChange,
      _props$businessId = props.businessId,
      businessId = _props$businessId === void 0 ? (_global$companyInfo$i = _utils.global === null || _utils.global === void 0 ? void 0 : (_global$companyInfo = _utils.global.companyInfo) === null || _global$companyInfo === void 0 ? void 0 : _global$companyInfo.id) !== null && _global$companyInfo$i !== void 0 ? _global$companyInfo$i : localStorage.getItem('pxx_userId') : _props$businessId,
      restProps = _objectWithoutProperties(props, _excluded);

  var _useNamespace3 = (0, _hooks.useNamespace)('upload', prefixCls),
      _useNamespace4 = _slicedToArray(_useNamespace3, 2),
      bem = _useNamespace4[1];

  var _useBoolean = (0, _ahooks.useBoolean)(props.loading),
      _useBoolean2 = _slicedToArray(_useBoolean, 2),
      loading = _useBoolean2[0],
      toggle = _useBoolean2[1].toggle;

  var _useBoolean3 = (0, _ahooks.useBoolean)(!!value),
      _useBoolean4 = _slicedToArray(_useBoolean3, 2),
      status = _useBoolean4[0],
      setStatus = _useBoolean4[1].toggle;

  var _React$useState = React.useState(function () {
    return value ? value.map(function (uid, idx) {
      if (listType === 'text') {
        var _defaultValue$idx;

        return {
          uid: uid,
          name: (_defaultValue$idx = defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue[idx]) !== null && _defaultValue$idx !== void 0 ? _defaultValue$idx : ''
        };
      }

      return {
        uid: uid,
        name: uid,
        url: defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue[idx]
      };
    }) : [];
  }),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      fileList = _React$useState2[0],
      setFileList = _React$useState2[1];

  var _React$useState3 = React.useState(function () {
    if (listType === 'picture') {
      return _objectSpread(_objectSpread({
        width: 280,
        height: 180,
        src: !loading ? value ? defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue[0] : _image.default.PLACEHOLDER : _image.default.PLACEHOLDER
      }, props.imageProps), {}, {
        disabled: disabled,
        onDelete: function onDelete() {
          var _props$onImageProps;

          setStatus(false);

          var newImageProps = _objectSpread(_objectSpread({}, imageProps), {}, {
            src: _image.default.PLACEHOLDER,
            preview: false,
            delete: false
          });

          setImageProps(newImageProps);
          (_props$onImageProps = props.onImageProps) === null || _props$onImageProps === void 0 ? void 0 : _props$onImageProps.call(props, newImageProps);
          onChange === null || onChange === void 0 ? void 0 : onChange([], []);
        },
        preview: !!value,
        delete: !!value
      });
    }

    return _objectSpread(_objectSpread({
      width: 104,
      height: 104,
      delete: true,
      size: 'small'
    }, props.imageProps), {}, {
      disabled: disabled
    });
  }),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      imageProps = _React$useState4[0],
      setImageProps = _React$useState4[1];

  var _props$placeholder = props.placeholder,
      placeholder = _props$placeholder === void 0 ? /*#__PURE__*/React.createElement(Placeholder, Object.assign({}, _objectSpread(_objectSpread({
    text: '上传照片',
    width: imageProps === null || imageProps === void 0 ? void 0 : imageProps.width,
    height: imageProps === null || imageProps === void 0 ? void 0 : imageProps.height,
    prefixCls: prefixCls,
    disabled: disabled
  }, placeholderProps), listType === 'picture-list' ? {
    width: 122,
    height: 122
  } : {}))) : _props$placeholder;
  var rcUploadProps = useShamMemo(function () {
    var rcUploadProps = _objectSpread(_objectSpread({}, (0, _lodashEs.omit)(restProps, ['type', 'prefixCls', 'listType', 'headers', 'imageProps', 'onImageProps', 'value', 'onChange', 'loading', 'onLoading'])), {}, {
      disabled: disabled,
      className: bem(),
      showUploadList: false,
      action: '/host/uploadFile',
      headers: _objectSpread({
        Authorization: localStorage.getItem(accessTokenKey)
      }, headers),
      listType: props.listType == null && props.listType === 'picture-list' ? 'picture-card' : 'text',
      data: function data(file) {
        return _objectSpread({
          waterMark: 0,
          serviceName: serviceName,
          moduleName: moduleName,
          businessId: businessId,
          fileSource: fileSource
        }, (0, _lodashEs.isFunction)(_data) ? _data(file) : _data);
      },
      beforeUpload: function beforeUpload(file) {
        if (props.maxSize && (0, _utils.calc)("".concat(file.size, " / 1024 / 1024")) >= props.maxSize) {
          _message2.default.warning("\u4E0A\u4F20\u6587\u4EF6\u5927\u5C0F\u4E0D\u80FD\u5927\u4E8E".concat(props.maxSize, "M"));

          return false;
        }

        if (props.minSize && (0, _utils.calc)("".concat(file.size, " / 1024")) <= props.minSize) {
          _message2.default.warning("\u4E0A\u4F20\u6587\u4EF6\u5927\u5C0F\u4E0D\u80FD\u5C0F\u4E8E".concat(props.minSize, "KB"));

          return false;
        }

        return true;
      }
    });

    if (listType === 'picture' || listType === 'picture-list') {
      rcUploadProps = _objectSpread({
        accept: imgAccept.join(',')
      }, rcUploadProps);
    }

    if (listType === 'picture') {
      rcUploadProps.onChange = function (info) {
        if (info.file.status === 'uploading') {
          var _props$onLoading;

          toggle(true);
          (_props$onLoading = props.onLoading) === null || _props$onLoading === void 0 ? void 0 : _props$onLoading.call(props, true);
          setStatus(true);
          return;
        }

        if (info.file.status === 'done') {
          if (info.file.originFileObj) getBase64(info.file.originFileObj, function (imageUrl) {
            var _info$file, _props$onLoading2, _props$onImageProps2;

            var response = ((_info$file = info.file) === null || _info$file === void 0 ? void 0 : _info$file.response) || {};

            var newImageProps = _objectSpread(_objectSpread({}, imageProps), {}, {
              src: imageUrl,
              preview: true,
              delete: true
            });

            toggle(false);
            setStatus(true);
            (_props$onLoading2 = props.onLoading) === null || _props$onLoading2 === void 0 ? void 0 : _props$onLoading2.call(props, false);
            setImageProps(newImageProps);
            (_props$onImageProps2 = props.onImageProps) === null || _props$onImageProps2 === void 0 ? void 0 : _props$onImageProps2.call(props, newImageProps);

            if ((response === null || response === void 0 ? void 0 : response.success) && (response === null || response === void 0 ? void 0 : response.data)) {
              onChange === null || onChange === void 0 ? void 0 : onChange([response.data], [imageUrl]);
            }
          });
        }
      };
    }

    if (listType === 'picture-list' || listType === 'text') {
      rcUploadProps.fileList = fileList;

      rcUploadProps.onChange = function (info) {
        if (info.file.status === 'done') {
          if (info.file.originFileObj) getBase64(info.file.originFileObj, function (imageUrl) {
            var _info$file2;

            var response = ((_info$file2 = info.file) === null || _info$file2 === void 0 ? void 0 : _info$file2.response) || {};

            var newFileList = _toConsumableArray(fileList);

            var currentileIdx = newFileList.findIndex(function (f) {
              return f.uid === info.file.uid;
            });
            newFileList[currentileIdx].status = 'done';

            if (listType === 'picture-list') {
              newFileList[currentileIdx].url = imageUrl;
            }

            if ((response === null || response === void 0 ? void 0 : response.success) && (response === null || response === void 0 ? void 0 : response.data)) {
              newFileList[currentileIdx].uid = response.data;
            }

            updateFileList(newFileList);
          });
        } else {
          setFileList(info.fileList);
        }
      };
    }

    return rcUploadProps;
  });

  var updateFileList = function updateFileList(fileList) {
    setFileList(fileList);

    var _fileList$reduce = fileList.reduce(function (p, c) {
      var _p = _slicedToArray(p, 2),
          v = _p[0],
          u = _p[1];

      v.push(c.uid);
      u.push(c.url);
      return [v, u];
    }, [[], []]),
        _fileList$reduce2 = _slicedToArray(_fileList$reduce, 2),
        v = _fileList$reduce2[0],
        u = _fileList$reduce2[1];

    onChange === null || onChange === void 0 ? void 0 : onChange(v, u);
  };

  (0, _ahooks.useUpdateEffect)(function () {
    toggle(props.loading);
  }, [props.loading]);
  (0, _ahooks.useUpdateEffect)(function () {
    setImageProps(_objectSpread(_objectSpread({}, imageProps), props.imageProps));
  }, [props.imageProps]);

  var renderPictureList = function renderPictureList() {
    return /*#__PURE__*/React.createElement("div", {
      className: bem('list')
    }, fileList.map(function (file) {
      return /*#__PURE__*/React.createElement(_spin.default, {
        key: file.uid,
        tip: "\u6B63\u5728\u4E0A\u4F20\u4E2D....",
        spinning: file.status === 'uploading'
      }, /*#__PURE__*/React.createElement("div", {
        className: bem('list-container')
      }, /*#__PURE__*/React.createElement("div", {
        className: bem('list-item', _defineProperty({}, file.status || 'uploading', true))
      }, /*#__PURE__*/React.createElement(_image.default, Object.assign({
        key: file.uid
      }, imageProps, {
        src: file.url,
        onDelete: function onDelete() {
          var newFileList = _toConsumableArray(fileList);

          var currentileIdx = newFileList.findIndex(function (f) {
            return f.uid === file.uid;
          });
          newFileList.splice(currentileIdx, 1);
          updateFileList(newFileList);
        }
      })))));
    }), /*#__PURE__*/React.createElement(_upload.default, Object.assign({
      ref: ref
    }, rcUploadProps), fileList.length >= maxCount ? null : placeholder));
  };

  var iconRender = function iconRender(file) {
    if (file.status === 'uploading') return /*#__PURE__*/React.createElement(_icons2.LoadingOutlined, {
      className: bem('text-icon')
    });
    var fileSuffix = file.name.split('.').slice(-1)[0];

    if (['xls', 'xlsx'].includes(fileSuffix)) {
      return /*#__PURE__*/React.createElement(_icons2.ExcelOutlined, null);
    }

    if (['doc', 'docx'].includes(fileSuffix)) {
      return /*#__PURE__*/React.createElement(_icons2.WordOutlined, null);
    }

    if (['ppt', 'pptx'].includes(fileSuffix)) {
      return /*#__PURE__*/React.createElement(_icons2.PptOutlined, null);
    }

    if (['pdf'].includes(fileSuffix)) {
      return /*#__PURE__*/React.createElement(_icons2.PdfOutlined, null);
    }

    return /*#__PURE__*/React.createElement(_icons.PaperClipOutlined, null);
  };

  var renderFile = function renderFile() {
    return /*#__PURE__*/React.createElement("div", {
      className: bem('text')
    }, /*#__PURE__*/React.createElement(_upload.default, Object.assign({
      ref: ref
    }, rcUploadProps), /*#__PURE__*/React.createElement("span", {
      className: bem('button', {
        disabled: disabled
      })
    }, /*#__PURE__*/React.createElement(_icons2.PlusOutlined, null), /*#__PURE__*/React.createElement("span", null, "\u4E0A\u4F20\u6587\u4EF6"))), /*#__PURE__*/React.createElement("div", {
      className: bem('text-list')
    }, /*#__PURE__*/React.createElement("div", {
      className: bem('text-list-container')
    }, fileList.map(function (file) {
      return /*#__PURE__*/React.createElement("div", {
        key: file.uid,
        className: bem('text-list-item', {
          loading: file.status === 'uploading'
        })
      }, /*#__PURE__*/React.createElement("div", {
        className: bem('text-list-item-info')
      }, /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement("span", {
        className: bem('text-list-item-icon')
      }, iconRender(file)), /*#__PURE__*/React.createElement("span", {
        className: bem('text-list-item-name'),
        title: file.name
      }, file.name), /*#__PURE__*/React.createElement("span", {
        className: bem('text-list-item-actions')
      }, !disabled ? /*#__PURE__*/React.createElement("span", {
        className: bem('text-list-item-actions-btn'),
        onClick: function onClick() {
          var newFileList = _toConsumableArray(fileList);

          var currentileIdx = newFileList.findIndex(function (f) {
            return f.uid === file.uid;
          });
          newFileList.splice(currentileIdx, 1);
          updateFileList(newFileList);
        }
      }, /*#__PURE__*/React.createElement(_icons2.DeleteOutlined, null)) : null))));
    }))));
  };

  var renderPicture = function renderPicture() {
    var render = function render() {
      if (!loading && !status) return placeholder;
      if (props.children) return props.children;
      return /*#__PURE__*/React.createElement(_spin.default, {
        tip: "\u6B63\u5728\u4E0A\u4F20\u4E2D....",
        spinning: loading
      }, /*#__PURE__*/React.createElement("div", {
        className: bem('picture', {
          disabled: disabled
        })
      }, /*#__PURE__*/React.createElement(_image.default, Object.assign({}, imageProps))));
    }; // TODO 临时解决预览图片点击触发上传的问题


    if (!loading && status) return render();
    return /*#__PURE__*/React.createElement(_upload.default, Object.assign({
      ref: ref
    }, rcUploadProps), render());
  };

  var render = function render() {
    switch (listType) {
      case 'picture':
        return renderPicture();

      case 'picture-list':
        return renderPictureList();

      case 'text':
      default:
        return renderFile();
    }
  };

  return render();
});
var _default = Upload;
exports.default = _default;