import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/inherits";
import _createSuper from "@babel/runtime/helpers/createSuper";
import _defineProperty from "@babel/runtime/helpers/defineProperty";

/* eslint react/sort-comp:0 */
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import isString from 'lodash/isString';
import isArray from 'lodash/isArray';
import isObject from 'lodash/isObject';
import toString from 'lodash/toString';
import isNil from 'lodash/isNil';
import getUid from './uid';
import warning from '../../_util/warning';
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) {
  _inherits(IframeUploader, _Component);

  var _super = _createSuper(IframeUploader);

  function IframeUploader() {
    var _this;

    _classCallCheck(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));

    _defineProperty(_assertThisInitialized(_this), "state", {
      uploading: false
    });

    _defineProperty(_assertThisInitialized(_this), "file", {});

    _defineProperty(_assertThisInitialized(_this), "onLoad", function () {
      if (!_this.state.uploading) {
        return;
      }

      var _assertThisInitialize = _assertThisInitialized(_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) {
        warning(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();
    });

    _defineProperty(_assertThisInitialized(_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: getUid(),
        name: target.value
      };

      _this.startUpload();

      var _assertThisInitialize2 = _assertThisInitialized(_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();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "saveIframe", function (node) {
      _this.iframe = node;
    });

    _defineProperty(_assertThisInitialized(_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;
  }

  _createClass(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.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 (isNil(value)) {
          return '';
        }

        if (isString(value)) {
          return value;
        }

        if (isObject(value)) {
          return JSON.stringify(value);
        }

        return toString(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 (isString(requestFileKeys) || isArray(requestFileKeys)) {
        var requestFileKeysFile = ['uid', 'type', 'name', 'lastModifiedDate'];

        if (isString(requestFileKeys)) {
          requestFileKeysFile.push(requestFileKeys);
        } else {
          requestFileKeysFile = [].concat(_toConsumableArray(requestFileKeysFile), _toConsumableArray(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 = _objectSpread(_objectSpread({}, IFRAME_STYLE), {}, {
        display: this.state.uploading || disabled ? 'none' : ''
      });

      var cls = classNames((_classNames = {}, _defineProperty(_classNames, prefixCls, true), _defineProperty(_classNames, "".concat(prefixCls, "-disabled"), disabled), _defineProperty(_classNames, className, className), _classNames));
      return /*#__PURE__*/React.createElement(Tag, {
        onClick: this.onClick,
        className: cls,
        style: _objectSpread({
          position: 'relative',
          zIndex: 0
        }, style)
      }, /*#__PURE__*/React.createElement("iframe", {
        ref: this.saveIframe,
        onLoad: this.onLoad,
        style: iframeStyle
      }), children);
    }
  }]);

  return IframeUploader;
}(Component);

export default IframeUploader;
//# sourceMappingURL=IframeUploader.js.map
