"use strict";
const React = require("react");
const request = require("./request.js");
const _interface = require("./interface.js");
const is = require("../_util/is.js");
const triggerNode = require("./trigger-node.js");
const util = require("./util.js");
const emotionReactJsxRuntime_browser_esm = require("../../../../../../@emotion_react@11.10.4_3toe27fv7etiytxb5kxc7fxaw4/node_modules/@emotion/react/jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js");
const CSSTransition = require("../../../../../../react-transition-group@4.4.5_biqbaboplfbrettd7655fr4n2y/node_modules/react-transition-group/esm/CSSTransition.js");
const _interopDefaultLegacy = (e) => e && typeof e === "object" && "default" in e ? e : { default: e };
const React__default = /* @__PURE__ */ _interopDefaultLegacy(React);
var __extends = globalThis && globalThis.__extends || function() {
  var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf || {
      __proto__: []
    } instanceof Array && function(d2, b2) {
      d2.__proto__ = b2;
    } || function(d2, b2) {
      for (var p in b2)
        if (Object.prototype.hasOwnProperty.call(b2, p))
          d2[p] = b2[p];
    };
    return extendStatics(d, b);
  };
  return function(d, b) {
    if (typeof b !== "function" && b !== null)
      throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
    extendStatics(d, b);
    function __() {
      this.constructor = d;
    }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
}();
var __assign = globalThis && globalThis.__assign || function() {
  __assign = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p))
          t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
var __awaiter = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator = globalThis && globalThis.__generator || function(thisArg, body) {
  var _ = {
    label: 0,
    sent: function() {
      if (t[0] & 1)
        throw t[1];
      return t[1];
    },
    trys: [],
    ops: []
  }, f, y, t, g;
  return g = {
    next: verb(0),
    "throw": verb(1),
    "return": verb(2)
  }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f)
      throw new TypeError("Generator is already executing.");
    while (_)
      try {
        if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
          return t;
        if (y = 0, t)
          op = [op[0] & 2, t.value];
        switch (op[0]) {
          case 0:
          case 1:
            t = op;
            break;
          case 4:
            _.label++;
            return {
              value: op[1],
              done: false
            };
          case 5:
            _.label++;
            y = op[1];
            op = [0];
            continue;
          case 7:
            op = _.ops.pop();
            _.trys.pop();
            continue;
          default:
            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _ = 0;
              continue;
            }
            if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
              _.label = op[1];
              break;
            }
            if (op[0] === 6 && _.label < t[1]) {
              _.label = t[1];
              t = op;
              break;
            }
            if (t && _.label < t[2]) {
              _.label = t[2];
              _.ops.push(op);
              break;
            }
            if (t[2])
              _.ops.pop();
            _.trys.pop();
            continue;
        }
        op = body.call(thisArg, _);
      } catch (e) {
        op = [6, e];
        y = 0;
      } finally {
        f = t = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return {
      value: op[0] ? op[1] : void 0,
      done: true
    };
  }
};
var Uploader = function(_super) {
  __extends(Uploader2, _super);
  function Uploader2(props) {
    var _this = _super.call(this, props) || this;
    _this.upload = function(file) {
      _this.doUpload(file);
    };
    _this.abort = function(file) {
      var req = _this.state.uploadRequests[file.uid];
      if (req) {
        req.abort && req.abort();
        _this.updateFileStatus(__assign(__assign({}, file), {
          status: _interface.STATUS.fail
        }));
        _this.deleteReq(file.uid);
      }
    };
    _this.reupload = function(file) {
      _this.doUpload(__assign(__assign({}, file), {
        percent: 0,
        status: _interface.STATUS.uploading
      }));
    };
    _this.deleteReq = function(uid) {
      var newValue = __assign({}, _this.state.uploadRequests);
      delete newValue[uid];
      _this.setState({
        uploadRequests: newValue
      });
    };
    _this.delete = _this.deleteReq;
    _this.updateFileStatus = function(file) {
      var onFileStatusChange = _this.props.onFileStatusChange;
      onFileStatusChange && onFileStatusChange(file);
    };
    _this.getTargetFile = function(file) {
      var key = "uid" in file ? "uid" : "name";
      var targetFile = _this.props.fileList.find(function(item) {
        return item[key] === file[key];
      });
      return targetFile;
    };
    _this.doUpload = function(file) {
      return __awaiter(_this, void 0, void 0, function() {
        var _a, action, headers, name, data, withCredentials, customRequest, onProgress, onSuccess, onError, options, request$1;
        var _b;
        var _this2 = this;
        return __generator(this, function(_c) {
          switch (_c.label) {
            case 0:
              _a = this.props, action = _a.action, headers = _a.headers, name = _a.name, data = _a.data, withCredentials = _a.withCredentials, customRequest = _a.customRequest;
              onProgress = function(percent, event) {
                var targetFile = _this2.getTargetFile(file);
                if (targetFile) {
                  targetFile.status = _interface.STATUS.uploading;
                  targetFile.percent = percent;
                  _this2.props.onProgress && _this2.props.onProgress(targetFile, event);
                }
              };
              onSuccess = function(response) {
                var targetFile = _this2.getTargetFile(file);
                if (targetFile) {
                  targetFile.status = _interface.STATUS.success;
                  targetFile.response = response;
                  _this2.updateFileStatus(targetFile);
                }
                _this2.deleteReq(file.uid);
              };
              onError = function(response) {
                var targetFile = _this2.getTargetFile(file);
                if (targetFile) {
                  targetFile.status = _interface.STATUS.fail;
                  targetFile.response = response;
                  _this2.updateFileStatus(targetFile);
                }
                _this2.deleteReq(file.uid);
              };
              options = {
                onProgress,
                onSuccess,
                onError,
                headers,
                name,
                file: file.originFile,
                data,
                withCredentials
              };
              this.updateFileStatus(file);
              if (!action)
                return [
                  3,
                  1
                ];
              request$1 = request(__assign(__assign({}, options), {
                action
              }));
              return [
                3,
                3
              ];
            case 1:
              if (!customRequest)
                return [
                  3,
                  3
                ];
              return [
                4,
                customRequest(options)
              ];
            case 2:
              request$1 = _c.sent();
              _c.label = 3;
            case 3:
              this.setState({
                uploadRequests: __assign(__assign({}, this.state.uploadRequests), (_b = {}, _b[file.uid] = request$1, _b))
              });
              return [
                2
              ];
          }
        });
      });
    };
    _this.handleFiles = function(files) {
      var _a = _this.props, limit = _a.limit, fileList = _a.fileList, onExceedLimit = _a.onExceedLimit, autoUpload = _a.autoUpload;
      if (is.isNumber(limit) && limit < fileList.length + files.length) {
        return onExceedLimit && onExceedLimit(files, fileList);
      }
      var asyncUpload = function(file, index) {
        var upload = {
          uid: "" + String(+new Date()) + index,
          originFile: file,
          percent: 0,
          status: _interface.STATUS.init,
          name: file.name
        };
        _this.updateFileStatus(upload);
        if (autoUpload) {
          setTimeout(function() {
            _this.doUpload(__assign(__assign({}, upload), {
              status: _interface.STATUS.uploading
            }));
          }, 0);
        }
      };
      files.forEach(function(file, index) {
        if (util.isAcceptFile(file, _this.props.accept)) {
          if (is.isFunction(_this.props.beforeUpload)) {
            Promise.resolve(_this.props.beforeUpload(file, files)).then(function(val) {
              if (val !== false) {
                var newFile = is.isFile(val) ? val : file;
                asyncUpload(newFile, index);
              }
            }).catch(function(e) {
              console.error(e);
            });
          } else {
            asyncUpload(file, index);
          }
        }
      });
    };
    _this.state = {
      uploadRequests: {}
    };
    return _this;
  }
  Uploader2.prototype.render = function() {
    var _this = this;
    var _a = this.props, accept = _a.accept, multiple = _a.multiple, children = _a.children, prefixCls = _a.prefixCls, tip = _a.tip, disabled = _a.disabled, drag = _a.drag, listType = _a.listType, hide = _a.hide, directory = _a.directory, onDrop = _a.onDrop;
    return /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsxs(emotionReactJsxRuntime_browser_esm.Fragment, {
      children: [/* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx("input", {
        ...__assign({
          key: "trigger-input",
          ref: function(node) {
            return _this.inputRef = node;
          },
          style: {
            display: "none"
          },
          type: "file",
          accept,
          multiple
        }, directory ? {
          webkitdirectory: "true"
        } : {}, {
          onChange: function(e) {
            var files = e.target.files;
            if (files) {
              _this.handleFiles([].slice.call(files));
              _this.inputRef.value = "";
            }
          },
          onClick: function(e) {
            e.stopPropagation();
          }
        })
      }), /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(CSSTransition, {
        in: !hide,
        timeout: 100,
        unmountOnExit: true,
        classNames: "fadeIn",
        children: /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(triggerNode, {
          directory,
          tip,
          multiple,
          accept,
          disabled,
          drag,
          listType,
          onDrop,
          onDragFiles: this.handleFiles,
          onClick: function() {
            !disabled && _this.inputRef && _this.inputRef.click();
          },
          prefixCls,
          children: is.isFunction(children) ? children({
            fileList: this.props.fileList
          }) : children
        })
      }, "trigger-node"), tip && listType !== "picture-card" && !drag ? /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx("div", {
        className: prefixCls + "-trigger-tip",
        children: tip
      }, "trigger-tip") : null]
    });
  };
  return Uploader2;
}(React__default.default.Component);
const Uploader$1 = Uploader;
module.exports = Uploader$1;
//# sourceMappingURL=uploader.js.map
