"use strict";

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

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

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

var _rcUpload = _interopRequireDefault(require("rc-upload"));

var _dialog = _interopRequireDefault(require("../dialog"));

var _button = _interopRequireDefault(require("../button"));

var _uploadedPreview = _interopRequireDefault(require("./uploaded-preview"));

var _helpers = require("../../utils/helpers");

var _util = require("./util");

var _imgViewer = _interopRequireDefault(require("../img-viewer"));

var _toast = _interopRequireDefault(require("../toast"));

var _getLocale = require("../../utils/getLocale");

require("./index.css");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

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

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : 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; }

var preCls = 'titaui-dialog-upload';
var uploadUrl = (0, _helpers.getApiUrl)("Upload/PostFiles?format=json&timestamp=".concat(new Date().getTime()));
var Footer = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
  var onUpload = _ref.onUpload,
      onCancel = _ref.onCancel,
      onOk = _ref.onOk,
      files = _ref.files;
  var uploader = (0, _react.useRef)();
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      abort: function abort(f) {
        return uploader.current.abort(f);
      }
    };
  }, []);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls + '__footer'
  }, /*#__PURE__*/_react["default"].createElement(_rcUpload["default"], {
    ref: uploader,
    action: uploadUrl,
    multiple: true,
    beforeUpload: function beforeUpload(file, list) {
      if (file.size > (0, _helpers.getUploadMaxSize)() * 1024 * 1024) {
        onUpload((0, _util.transferRcFileToUploadFile)(file, {
          percentComplete: 0,
          uploadStatus: 4,
          Msg: '文件大小不能超过' + (0, _helpers.getUploadMaxSize)() + 'mb'
        }));
        return false;
      }

      return true;
    },
    onProgress: function onProgress(e, f) {
      onUpload((0, _util.transferRcFileToUploadFile)(f, {
        percentComplete: e.percent,
        uploadStatus: 2
      }));
    },
    onSuccess: function onSuccess(res, file) {
      onUpload(_objectSpread(_objectSpread({}, res.Result[0]), {}, {
        Id: file.uid,
        uploadStatus: res.Result[0].IsSuccess ? 3 : 4,
        percentComplete: 100,
        Size: Math.round(file.size * 10 / 1024) / 10
      }));
    }
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: "tu-icon-cus-fujian"
  }, (0, _getLocale.getLocale)('Pro_newpro_Upload'))), /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      flex: 1
    }
  }), /*#__PURE__*/_react["default"].createElement(_button["default"].Rect, {
    type: "cancel",
    size: "big",
    style: {
      marginRight: 12
    },
    onClick: onCancel
  }, (0, _getLocale.getLocale)('Mod_Cancel')), /*#__PURE__*/_react["default"].createElement(_button["default"].Rect, {
    type: "primary",
    size: "big",
    onClick: onOk,
    disabled: (files === null || files === void 0 ? void 0 : files.length) === 0
  }, (0, _getLocale.getLocale)('Mod_Determiness')));
});

function UploadDialog(_ref2) {
  var onSubmit = _ref2.onSubmit;

  var _useState = (0, _react.useState)([]),
      _useState2 = _slicedToArray(_useState, 2),
      files = _useState2[0],
      setFiles = _useState2[1];

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

  var uploader = (0, _react.useRef)();
  var previewRef = (0, _react.useRef)();
  (0, _react.useEffect)(function () {
    if (files.length > 0 && !visible) setVisible(true);
  }, [files]);
  var handleUpload = (0, _react.useCallback)(function (file) {
    var newFiles = _toConsumableArray(files);

    var index = newFiles.findIndex(function (f) {
      return f.Id == file.Id;
    });
    var isAdd = index == -1;

    if (isAdd) {
      newFiles.push(file);
    } else {
      newFiles[index] = file;
    }

    setFiles(newFiles);
  }, [files]);
  var handleSubmit = (0, _react.useCallback)(function (index, option) {
    switch (option) {
      case 'cancel':
        {
          uploader.current.abort({
            uid: files[index].Id
          });
          setFiles(files.filter(function (f) {
            return f.Id != files[index].Id;
          }));
          break;
        }

      case 'delete':
        {
          setFiles(files.filter(function (f) {
            return f.Id != files[index].Id;
          }));
          break;
        }

      case 'preview':
        {
          if ((0, _util.isImg)(files[index].MediaType)) {
            var i = files.filter(function (f) {
              return (0, _util.isImg)(f.MediaType);
            }).findIndex(function (f) {
              return f.Id == files[index].Id;
            });
            previewRef.current.show(i);
          } else {
            window.open(files[index].ClientUrl);
          }

          break;
        }

      case 'download':
        {
          window.open(files[index].DownloadUrl);
          break;
        }
    }
  }, [files]);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls
  }, /*#__PURE__*/_react["default"].createElement(_rcUpload["default"], {
    ref: uploader,
    action: uploadUrl,
    multiple: true,
    beforeUpload: function beforeUpload(file, list) {
      if (file.size > (0, _helpers.getUploadMaxSize)() * 1024 * 1024) {
        handleUpload((0, _util.transferRcFileToUploadFile)(file, {
          percentComplete: 0,
          uploadStatus: 4,
          Msg: '文件大小不能超过' + (0, _helpers.getUploadMaxSize)() + 'mb'
        }));
        return false;
      }

      return true;
    },
    onProgress: function onProgress(e, f) {
      handleUpload((0, _util.transferRcFileToUploadFile)(f, {
        percentComplete: e.percent,
        uploadStatus: 2
      }));
    },
    onSuccess: function onSuccess(res, file) {
      handleUpload(_objectSpread(_objectSpread({}, res.Result[0]), {}, {
        Id: file.uid,
        uploadStatus: res.Result[0].IsSuccess ? 3 : 4,
        percentComplete: 100,
        Size: Math.round(file.size * 10 / 1024) / 10
      }));
    }
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__dialog-upload-btn tu-icon-H5-add-s")
  })), /*#__PURE__*/_react["default"].createElement(_imgViewer["default"], {
    data: files.filter(function (f) {
      return (0, _util.isImg)(f.MediaType);
    }).map(function (f) {
      return _objectSpread(_objectSpread({}, f), {}, {
        previewUrl: f.ClientUrl
      });
    }),
    ref: previewRef,
    showDownload: true
  }), /*#__PURE__*/_react["default"].createElement(_dialog["default"], {
    visible: visible,
    noHeadLine: true,
    noFooterLine: true,
    title: (0, _getLocale.getLocale)('Pro_newpro_Upload'),
    footer: /*#__PURE__*/_react["default"].createElement(Footer, {
      ref: uploader,
      onUpload: handleUpload,
      onCancel: function onCancel() {
        setFiles([]);
        setVisible(false);
      },
      files: files,
      onOk: /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var isUploading, uploadfiles;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                isUploading = files.findIndex(function (f) {
                  return f.uploadStatus == 1 || f.uploadStatus == 2;
                }) !== -1;

                if (!isUploading) {
                  _context.next = 4;
                  break;
                }

                _toast["default"].Warning('有附件仍在上传，请稍等');

                return _context.abrupt("return");

              case 4:
                uploadfiles = files.filter(function (f) {
                  return f.uploadStatus == 3;
                });

                if (!uploadfiles.length) {
                  _context.next = 8;
                  break;
                }

                _context.next = 8;
                return onSubmit(uploadfiles);

              case 8:
                setFiles([]);
                setVisible(false);

              case 10:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }))
    }),
    width: "580px",
    onClose: function onClose() {
      setFiles([]);
      setVisible(false);
    }
  }, (files === null || files === void 0 ? void 0 : files.length) !== 0 ? /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls + '__content'
  }, files.map(function (f, index) {
    return /*#__PURE__*/_react["default"].createElement(_uploadedPreview["default"], {
      index: index,
      uploadResultItem: f,
      onSubmit: handleSubmit,
      className: preCls + '__preview'
    });
  })) : /*#__PURE__*/_react["default"].createElement("div", {
    className: preCls + '__empty'
  }, (0, _getLocale.getLocale)('Rep_Tab_Mys_Noattachment'))));
}

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