"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

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

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

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

var _reactDom = _interopRequireDefault(require("react-dom"));

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

var _isString = _interopRequireDefault(require("lodash/isString"));

var _isArray = _interopRequireDefault(require("lodash/isArray"));

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _toString = _interopRequireDefault(require("lodash/toString"));

var _isNil = _interopRequireDefault(require("lodash/isNil"));

var _uid = _interopRequireDefault(require("./uid"));

var _warning = _interopRequireDefault(require("../../_util/warning"));

/* eslint react/sort-comp:0 */
var IFRAME_STYLE = {
  position: 'absolute',
  top: 0,
  opacity: 0,
  filter: 'alpha(opacity=0)',
  left: 0,
  zIndex: 9999
}; // diferent from AjaxUpload, can only upload on at one time, serial seriously

var IframeUploader = /*#__PURE__*/function (_Component) {
  (0, _inherits2["default"])(IframeUploader, _Component);

  var _super = (0, _createSuper2["default"])(IframeUploader);

  function IframeUploader() {
    var _this;

    (0, _classCallCheck2["default"])(this, IframeUploader);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "state", {
      uploading: false
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "file", {});
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onLoad", function () {
      if (!_this.state.uploading) {
        return;
      }

      var _assertThisInitialize = (0, _assertThisInitialized2["default"])(_this),
          props = _assertThisInitialize.props,
          file = _assertThisInitialize.file;

      var response;

      try {
        var doc = _this.getIframeDocument();

        var script = doc.getElementsByTagName('script')[0];

        if (script && script.parentNode === doc.body) {
          doc.body.removeChild(script);
        }

        response = doc.body.innerHTML;
        props.onSuccess(response, file);
      } catch (err) {
        (0, _warning["default"])(false, 'cross domain error for Upload. Maybe server should return document.domain script. see Note from https://github.com/react-component/upload');
        response = 'cross-domain';
        props.onError(err, null, file);
      }

      _this.endUpload();
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onChange", function () {
      var target = _this.getFormInputNode(); // ie8/9 don't support FileList Object
      // http://stackoverflow.com/questions/12830058/ie8-input-type-file-get-files


      var file = _this.file = {
        uid: (0, _uid["default"])(),
        name: target.value
      };

      _this.startUpload();

      var _assertThisInitialize2 = (0, _assertThisInitialized2["default"])(_this),
          props = _assertThisInitialize2.props;

      if (!props.beforeUpload) {
        return _this.post(file);
      }

      var before = props.beforeUpload(file);

      if (before && before.then) {
        before.then(function () {
          _this.post(file);
        }, function () {
          _this.endUpload();
        });
      } else if (before !== false) {
        _this.post(file);
      } else {
        _this.endUpload();
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "saveIframe", function (node) {
      _this.iframe = node;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onClick", function (e) {
      var el = _this.getFormInputNode();

      if (!el) {
        return;
      }

      if (e.target === el) return;

      if (_this.props.fileInputClick) {
        _this.props.fileInputClick(el);
      } else {
        el.click();
      }
    });
    return _this;
  }

  (0, _createClass2["default"])(IframeUploader, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.updateIframeWH();
      this.initIframe();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      this.updateIframeWH();
    }
  }, {
    key: "getIframeNode",
    value: function getIframeNode() {
      return this.iframe;
    }
  }, {
    key: "getIframeDocument",
    value: function getIframeDocument() {
      return this.getIframeNode().contentDocument;
    }
  }, {
    key: "getFormNode",
    value: function getFormNode() {
      return this.getIframeDocument().getElementById('form');
    }
  }, {
    key: "getFormInputNode",
    value: function getFormInputNode() {
      return this.getIframeDocument().getElementById('input');
    }
  }, {
    key: "getFormDataNode",
    value: function getFormDataNode() {
      return this.getIframeDocument().getElementById('data');
    }
  }, {
    key: "getFileForMultiple",
    value: function getFileForMultiple(file) {
      return this.props.multiple ? [file] : file;
    }
  }, {
    key: "getIframeHTML",
    value: function getIframeHTML(domain) {
      var domainScript = '';
      var domainInput = '';

      if (domain) {
        var script = 'script';
        domainScript = "<".concat(script, ">document.domain=\"").concat(domain, "\";</").concat(script, ">");
        domainInput = "<input name=\"_documentDomain\" value=\"".concat(domain, "\" />");
      }

      return "\n    <!DOCTYPE html>\n    <html>\n    <head>\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n    <style>\n    body,html {padding:0;margin:0;border:0;overflow:hidden;}\n    </style>\n    ".concat(domainScript, "\n    </head>\n    <body>\n    <form method=\"post\"\n    encType=\"multipart/form-data\"\n    action=\"\" id=\"form\"\n    style=\"display:block;height:9999px;position:relative;overflow:hidden;\">\n    <input id=\"input\" type=\"file\"\n     name=\"").concat(this.props.name, "\"\n     style=\"position:absolute;top:0;right:0;height:9999px;font-size:9999px;cursor:pointer;\"/>\n    ").concat(domainInput, "\n    <span id=\"data\"></span>\n    </form>\n    </body>\n    </html>\n    ");
    }
  }, {
    key: "initIframeSrc",
    value: function initIframeSrc() {
      if (this.domain) {
        this.getIframeNode().src = "javascript:void((function(){\n        var d = document;\n        d.open();\n        d.domain='".concat(this.domain, "';\n        d.write('');\n        d.close();\n      })())");
      }
    }
  }, {
    key: "initIframe",
    value: function initIframe() {
      var iframeNode = this.getIframeNode();
      var win = iframeNode.contentWindow;
      var doc;
      this.domain = this.domain || '';
      this.initIframeSrc();

      try {
        doc = win.document;
      } catch (e) {
        this.domain = document.domain;
        this.initIframeSrc();
        win = iframeNode.contentWindow;
        doc = win.document;
      }

      doc.open('text/html', 'replace');
      doc.write(this.getIframeHTML(this.domain));
      doc.close();
      this.getFormInputNode().onchange = this.onChange;
    }
  }, {
    key: "endUpload",
    value: function endUpload() {
      if (this.state.uploading) {
        this.file = {}; // hack avoid batch

        this.state.uploading = false;
        this.setState({
          uploading: false
        });
        this.initIframe();
      }
    }
  }, {
    key: "startUpload",
    value: function startUpload() {
      if (!this.state.uploading) {
        this.state.uploading = true;
        this.setState({
          uploading: true
        });
      }
    }
  }, {
    key: "updateIframeWH",
    value: function updateIframeWH() {
      var rootNode = _reactDom["default"].findDOMNode(this);

      var iframeNode = this.getIframeNode();
      iframeNode.style.height = "".concat(rootNode.offsetHeight, "px");
      iframeNode.style.width = "".concat(rootNode.offsetWidth, "px");
    }
  }, {
    key: "abort",
    value: function abort(file) {
      if (file) {
        var uid = file;

        if (file && file.uid) {
          uid = file.uid;
        }

        if (uid === this.file.uid) {
          this.endUpload();
        }
      } else {
        this.endUpload();
      }
    }
  }, {
    key: "post",
    value: function post(file) {
      var _this2 = this;

      var formNode = this.getFormNode();
      var dataSpan = this.getFormDataNode();
      var _this$props = this.props,
          data = _this$props.data,
          requestFileKeys = _this$props.requestFileKeys;
      var onStart = this.props.onStart;

      if (typeof data === 'function') {
        data = data(file);
      }

      var inputs = this.requestFileInput(requestFileKeys, file, data);
      dataSpan.appendChild(inputs);
      new Promise(function (resolve) {
        var action = _this2.props.action;

        if (typeof action === 'function') {
          return resolve(action(file));
        }

        resolve(action);
      }).then(function (action) {
        formNode.setAttribute('action', action);
        formNode.submit();
        dataSpan.innerHTML = '';
        onStart(file);
      });
    }
    /**
     *
     * @param { 需要加入的参数 } requestFileKeys
     * @param { 文件内容 } file
     * @param { props的必传参数 } data
     */

  }, {
    key: "requestFileInput",
    value: function requestFileInput(requestFileKeys, file, data) {
      var inputs = document.createDocumentFragment();
      /**
       * 添加注入的data数据
       */

      if (data) {
        for (var key in data) {
          if (data.hasOwnProperty(key)) {
            var input = document.createElement('input');
            input.setAttribute('name', key);
            input.value = data[key];
            /**
             * 添加文件数据
             */

            inputs.appendChild(input);
          }
        }
      }

      var toStringValue = function toStringValue(value) {
        if ((0, _isNil["default"])(value)) {
          return '';
        }

        if ((0, _isString["default"])(value)) {
          return value;
        }

        if ((0, _isObject["default"])(value)) {
          return JSON.stringify(value);
        }

        return (0, _toString["default"])(value);
      };
      /**
       *
       * @param {所有数据} obj
       * @param {需要传出的参数keys} arrayString
       */


      var ArrayToObject = function ArrayToObject(obj, arrayString) {
        arrayString.forEach(function (item) {
          var input = document.createElement('input');
          input.setAttribute('name', toStringValue(item));
          input.value = toStringValue(obj[toStringValue(item)]);
          /**
           * 添加文件数据
           */

          inputs.appendChild(input);
        });
      };
      /**
       * 判断是否需要增加key
       */


      if ((0, _isString["default"])(requestFileKeys) || (0, _isArray["default"])(requestFileKeys)) {
        var requestFileKeysFile = ['uid', 'type', 'name', 'lastModifiedDate'];

        if ((0, _isString["default"])(requestFileKeys)) {
          requestFileKeysFile.push(requestFileKeys);
        } else {
          requestFileKeysFile = [].concat((0, _toConsumableArray2["default"])(requestFileKeysFile), (0, _toConsumableArray2["default"])(requestFileKeys));
        }

        ArrayToObject(file, requestFileKeysFile);
      }

      return inputs;
    }
  }, {
    key: "render",
    value: function render() {
      var _classNames;

      var _this$props2 = this.props,
          Tag = _this$props2.component,
          disabled = _this$props2.disabled,
          className = _this$props2.className,
          prefixCls = _this$props2.prefixCls,
          children = _this$props2.children,
          style = _this$props2.style;
      var iframeStyle = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, IFRAME_STYLE), {}, {
        display: this.state.uploading || disabled ? 'none' : ''
      });
      var cls = (0, _classnames["default"])((_classNames = {}, (0, _defineProperty2["default"])(_classNames, prefixCls, true), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-disabled"), disabled), (0, _defineProperty2["default"])(_classNames, className, className), _classNames));
      return /*#__PURE__*/_react["default"].createElement(Tag, {
        onClick: this.onClick,
        className: cls,
        style: (0, _objectSpread2["default"])({
          position: 'relative',
          zIndex: 0
        }, style)
      }, /*#__PURE__*/_react["default"].createElement("iframe", {
        ref: this.saveIframe,
        onLoad: this.onLoad,
        style: iframeStyle
      }), children);
    }
  }]);
  return IframeUploader;
}(_react.Component);

var _default = IframeUploader;
exports["default"] = _default;
//# sourceMappingURL=IframeUploader.js.map
