"use strict";

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

require("antd-mobile/lib/modal/style");

var _modal = _interopRequireDefault(require("antd-mobile/lib/modal"));

require("antd-mobile/lib/list/style");

var _list = _interopRequireDefault(require("antd-mobile/lib/list"));

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

var _propTypes = _interopRequireDefault(require("prop-types"));

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

var _spin = _interopRequireDefault(require("../spin"));

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }

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

function _typeof(obj) { 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); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

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 Item = _list["default"].Item;
var LOCAL_STORAGE_FILES_KEY = 'evhUploader-files'; // 端口号为443的使用https，其他使用http

var processHttp = function processHttp() {
  var contentServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var server = contentServer.trim();
  server = server.split(':')[1] === '443' ? "https://".concat(server) : "http://".concat(server);
  return server;
};
/**
 * 文件中转站 非跳转组件 仅支持上传文件
 */


var FileUpload =
/*#__PURE__*/
function (_Component) {
  _inherits(FileUpload, _Component);

  function FileUpload(props) {
    var _this;

    _classCallCheck(this, FileUpload);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(FileUpload).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "handleToggleUploadModal", function (e, cb) {
      var uploadModalVisible = _this.state.uploadModalVisible;

      _this.setState({
        uploadModalVisible: !uploadModalVisible
      }, cb);
    });

    _defineProperty(_assertThisInitialized(_this), "handlePcUpload", function () {
      var fileList = _this.props.fileList;
      localStorage.setItem(LOCAL_STORAGE_FILES_KEY, JSON.stringify(fileList));

      _this.setState({
        iframeLoading: true
      });

      _this.handleToggleUploadModal();
    });

    _defineProperty(_assertThisInitialized(_this), "handleIframeOnload", function () {
      _this.setState({
        iframeLoading: false
      });
    });

    var self = _assertThisInitialized(_this);

    var _self$props = self.props,
        limitCount = _self$props.limitCount,
        limitPerSize = _self$props.limitPerSize,
        fileExtension = _self$props.fileExtension,
        loginToken = _self$props.loginToken,
        contentServer = _self$props.contentServer,
        onChange = _self$props.onChange;
    _this.uploaderProps = {
      headers: {
        'X-Requested-With': null,
        'Access-Control-Request-Headers:': null
      },
      disabled: true,
      name: 'upload_file',
      action: "".concat(processHttp(contentServer), "/upload/file?token=").concat(loginToken),
      accept: fileExtension,
      component: 'div',
      multiple: true,
      onSuccess: function onSuccess(file) {
        var onClose = self.props.onClose;
        var tempFiles = self.state.tempFiles;
        var files = tempFiles.slice();
        var _file$response = file.response,
            url = _file$response.url,
            uri = _file$response.uri;
        var index = files.findIndex(function (item) {
          return item.status === 'uploading';
        });
        if (index !== -1) files[index] = _objectSpread({}, files[index], {
          status: 'done',
          url: url,
          uri: uri
        });
        onChange(files);
        onClose();
      },
      onStart: function onStart(file) {
        var fileList = self.props.fileList;
        var files = fileList.slice();
        var name = file.name;
        var size = file.size;
        var uid = file.uid;
        files.push({
          uid: uid,
          name: name,
          status: 'uploading',
          size: size
        });

        _this.setState({
          tempFiles: files
        }); // onChange(files);

      },
      beforeUpload: function beforeUpload(file) {
        var _self$props2 = self.props,
            fileList = _self$props2.fileList,
            onClose = _self$props2.onClose; // 增加文件大小及数量的判断

        return new Promise(function (resolve, reject) {
          if (limitPerSize && file.size > limitPerSize) {
            _modal["default"].alert(null, '文件过大，无法上传');

            onClose();
            reject();
          } else if (limitCount && fileList.length >= limitCount) {
            _modal["default"].alert(null, "\u6700\u591A\u4E0A\u4F20 ".concat(limitCount, " \u4E2A\u6587\u4EF6"));

            onClose();
            reject();
          } else {
            resolve(file);
          }
        });
      },
      onError: function onError() {
        var onClose = self.props.onClose;

        _modal["default"].alert(null, '上传失败');

        onClose();
      }
    };
    _this.state = {
      uploadModalVisible: false,
      iframeLoading: false,
      tempFiles: []
    };
    return _this;
  }

  _createClass(FileUpload, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      // 在 iframe 中同步上传结果
      window.onFinish = function () {
        var _this2$props = _this2.props,
            onClose = _this2$props.onClose,
            onChange = _this2$props.onChange;
        var files = localStorage.getItem(LOCAL_STORAGE_FILES_KEY);
        files = files ? JSON.parse(files) : [];
        onChange(files);

        _this2.handleToggleUploadModal(null, onClose);
      };
    } // 文件中转站 popup 的显示和隐藏

  }, {
    key: "render",
    value: function render() {
      var prefixCls = 'eh-file-upload';
      var _this$state = this.state,
          uploadModalVisible = _this$state.uploadModalVisible,
          iframeLoading = _this$state.iframeLoading;
      var _this$props = this.props,
          visible = _this$props.visible,
          onClose = _this$props.onClose,
          namespaceId = _this$props.namespaceId,
          limitCount = _this$props.limitCount,
          limitPerSize = _this$props.limitPerSize,
          fileExtension = _this$props.fileExtension;
      var _window$location = window.location,
          host = _window$location.host,
          protocol = _window$location.protocol;
      var uploadUrl;

      if (/localhost/i.test(host)) {
        uploadUrl = "http://gonggdev1.zuolin.com/upload-service/mobile/index.html?ns=".concat(namespaceId, "&isFrame=1");
      } else {
        uploadUrl = "".concat(protocol, "//").concat(host, "/upload-service/mobile/index.html?ns=").concat(namespaceId, "&isFrame=1");
      }

      if (limitCount) {
        uploadUrl += "&limitCount=".concat(limitCount);
      }

      if (limitPerSize) {
        uploadUrl += "&limitPerSize=".concat(limitPerSize);
      }

      if (typeof fileExtension === 'string' && fileExtension.trim()) {
        uploadUrl += "&fileExtension=".concat(fileExtension.trim());
      }

      uploadUrl += '#/step';
      return _react["default"].createElement(_modal["default"], {
        popup: true,
        visible: visible,
        onClose: onClose,
        animationType: "slide-up",
        className: prefixCls
      }, _react["default"].createElement(_list["default"], null, _react["default"].createElement(Item, {
        onClick: function onClick() {}
      }, _react["default"].createElement(_rcUpload["default"], _extends({}, this.uploaderProps, {
        prefixCls: "".concat(prefixCls, "-btn")
      }), "\u624B\u673A\u4E0A\u4F20")), _react["default"].createElement(Item, {
        onClick: this.handlePcUpload
      }, "\u7535\u8111\u4E0A\u4F20"), _react["default"].createElement(Item, {
        onClick: onClose,
        className: "".concat(prefixCls, "-cancel")
      }, "\u53D6\u6D88")), _react["default"].createElement(_modal["default"], {
        popup: true,
        animationType: "slide-up",
        visible: uploadModalVisible,
        onClose: this.handleToggleUploadModal,
        title: "\u6587\u4EF6\u4E0A\u4F20",
        closable: true,
        className: "".concat(prefixCls, "-modal")
      }, iframeLoading ? _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-loading-mask")
      }, _react["default"].createElement(_spin["default"], {
        type: "black",
        delay: 100,
        spinning: iframeLoading,
        onClickBtn: function onClickBtn() {
          window.frames[0].location.reload();
        }
      })) : null, _react["default"].createElement("iframe", {
        title: "\u6587\u4EF6\u4E0A\u4F20",
        src: uploadUrl,
        seamless: true,
        width: "100%",
        height: "100%",
        frameBorder: "0",
        onLoad: this.handleIframeOnload
      })));
    }
  }]);

  return FileUpload;
}(_react.Component);

FileUpload.propTypes = {
  // 上传文件需要的参数
  namespaceId: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]).isRequired,
  loginToken: _propTypes["default"].string.isRequired,
  contentServer: _propTypes["default"].string.isRequired,
  // 文件列表
  fileList: _propTypes["default"].arrayOf(_propTypes["default"].object),
  // 上传文件完成后的回调
  onChange: _propTypes["default"].func,
  // 跟上传文件有关的内容
  limitCount: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]),
  limitPerSize: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]),
  fileExtension: _propTypes["default"].string,
  title: _propTypes["default"].string
};
FileUpload.defaultProps = {
  fileList: [],
  onChange: function onChange() {// do nothing
  },
  limitCount: '',
  limitPerSize: '',
  fileExtension: '',
  title: '上传文件'
};
var _default = FileUpload;
exports["default"] = _default;
module.exports = exports.default;