"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/toast/style");

var _toast = _interopRequireDefault(require("antd-mobile/lib/toast"));

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

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

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

var _rmcFeedback = _interopRequireDefault(require("rmc-feedback"));

var _superagent = _interopRequireDefault(require("superagent"));

var _utils = require("./utils");

var _imageViewer = _interopRequireDefault(require("../image-viewer"));

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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

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

/* babel-plugin-inline-import './assets/images/img_picker_add.png' */
var addImage = "data:image/png;base64, ";

function noop() {}

var num = 0;

var ImageUpload =
/*#__PURE__*/
function (_React$Component) {
  _inherits(ImageUpload, _React$Component);

  function ImageUpload(props) {
    var _this;

    _classCallCheck(this, ImageUpload);

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

    _defineProperty(_assertThisInitialized(_this), "getOrientation", function (file, callback) {
      var reader = new FileReader();

      reader.onload = function (e) {
        var view = new DataView(e.target.result);

        if (view.getUint16(0, false) !== 0xffd8) {
          // eslint-disable-next-line standard/no-callback-literal
          return callback(-2);
        }

        var length = view.byteLength;
        var offset = 2;

        while (offset < length) {
          var marker = view.getUint16(offset, false);
          offset += 2;

          if (marker === 0xffe1) {
            var tmp = view.getUint32(offset += 2, false);

            if (tmp !== 0x45786966) {
              // eslint-disable-next-line standard/no-callback-literal
              return callback(-1);
            }

            var little = view.getUint16(offset += 6, false) === 0x4949;
            offset += view.getUint32(offset + 4, little);
            var tags = view.getUint16(offset, little);
            offset += 2;

            for (var i = 0; i < tags; i++) {
              if (view.getUint16(offset + i * 12, little) === 0x0112) {
                return callback(view.getUint16(offset + i * 12 + 8, little));
              }
            } // eslint-disable-next-line no-bitwise

          } else if ((marker & 0xff00) !== 0xff00) {
            break;
          } else {
            offset += view.getUint16(offset, false);
          }
        } // eslint-disable-next-line standard/no-callback-literal


        return callback(-1);
      };

      reader.readAsArrayBuffer(file.slice(0, 64 * 1024));
    });

    _defineProperty(_assertThisInitialized(_this), "getRotation", function () {
      var orientation = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
      var imgRotation = 0;

      switch (orientation) {
        case 3:
          imgRotation = 180;
          break;

        case 6:
          imgRotation = 90;
          break;

        case 8:
          imgRotation = 270;
          break;

        default:
      }

      return imgRotation;
    });

    _defineProperty(_assertThisInitialized(_this), "pickImage", function () {
      var platform = _this.state.platform;

      if (platform === 'wx') {
        _this.wxChooseImage();
      } else if (platform === 'zuolin') {
        _this.zlChoseImage();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "zlChoseImage", function () {
      var _this$props = _this.props,
          limitCount = _this$props.limitCount,
          _this$props$files = _this$props.files,
          files = _this$props$files === void 0 ? [] : _this$props$files;
      window.ehopenapi.pickImages({
        count: limitCount - files.length,
        sourceType: '',
        success: function success(res) {
          // eslint-disable-next-line no-shadow
          var _this$props$files2 = _this.props.files,
              files = _this$props$files2 === void 0 ? [] : _this$props$files2;
          var localIds = res.localIds;
          files = files.slice(0);
          localIds.forEach(function (localId) {
            var imgId = num++;
            files.push({
              id: imgId,
              status: 'uploading',
              localUrl: localId
            });

            _this.zlUploadImage(localId, imgId);
          });

          _this.props.onChange(files, 'add');
        },
        cancel: function cancel() {// 取消操作
        }
      });
    });

    _defineProperty(_assertThisInitialized(_this), "zlUploadImage", function (localId, imgId) {
      window.ehopenapi.uploadImage({
        localId: localId,
        isShowProgressTips: 1,
        quality: 70,
        success: function success(res) {
          var _this$props$files3 = _this.props.files,
              files = _this$props$files3 === void 0 ? [] : _this$props$files3;
          files = files.slice(0);
          var fileIndex = files.findIndex(function (item) {
            return item.id === imgId;
          });

          if (fileIndex !== -1) {
            var url = res.url,
                uri = res.uid;
            files[fileIndex] = {
              status: 'done',
              uri: uri,
              url: url,
              fileName: "\u56FE\u7247".concat(imgId),
              uploadTime: new Date().getTime()
            };
          }

          _this.props.onChange(files, 'add');
        },
        cancel: function cancel() {// 取消操作
        },
        fail: function fail() {
          // 解决某些场景下，zlChoseImage 中的 this.props.onChange 还没执行完，就会进入此函数的问题
          setTimeout(function () {
            var _this$props$files4 = _this.props.files,
                files = _this$props$files4 === void 0 ? [] : _this$props$files4;
            files = files.slice(0);
            var fileIndex = files.findIndex(function (item) {
              return item.id === imgId;
            });

            if (fileIndex !== -1) {
              files.splice(fileIndex, 1);

              _this.props.onChange(files, 'remove');

              _toast["default"].fail('上传失败, 请重试', 2);
            }
          }, 0);
        }
      });
    });

    _defineProperty(_assertThisInitialized(_this), "wxChooseImage", function () {
      var _this$props$files5 = _this.props.files,
          files = _this$props$files5 === void 0 ? [] : _this$props$files5;
      window.wx.chooseImage({
        count: limitCount - files.length,
        success: function success(res) {
          var localIds = res.localIds;
          files = files.slice(0);
          localIds.forEach(function (item) {
            var imgId = num++;
            files.push({
              id: imgId,
              status: 'uploading',
              localUrl: item
            });

            _this.wxUploadImage(item, imgId);
          });

          _this.props.onChange(files, 'add');
        },
        fail: function fail() {}
      });
    });

    _defineProperty(_assertThisInitialized(_this), "wxUploadImage", function (localId, imgId) {
      window.wx.uploadImage({
        localId: localId,
        isShowProgressTips: 1,
        success: function success(res) {
          var serverId = res.serverId;

          _this.getWXImage(serverId, localId, imgId);
        }
      });
    });

    _defineProperty(_assertThisInitialized(_this), "getWXImage", function (mediaId, localId, imgId) {
      var url = "".concat(window.location.protocol, "//").concat(window.location.host, "/evh/wx/getContentServerUri?mediaId=").concat(mediaId);

      _superagent["default"].post(url).end(function (err, res) {
        var _this$props$files6 = _this.props.files,
            files = _this$props$files6 === void 0 ? [] : _this$props$files6;
        var urlMaps = _this.state.urlMaps;
        files = files.slice(0);
        var fileIndex = files.findIndex(function (item) {
          return item.id === imgId;
        });

        if (res && res.body && res.body.errorCode === 200) {
          var data = res.body.response;

          if (fileIndex !== -1) {
            files[fileIndex] = {
              status: 'done',
              uri: data.uri,
              url: data.url,
              fileName: "\u56FE\u7247".concat(imgId),
              uploadTime: new Date().getTime()
            };

            _this.setState({
              urlMaps: _objectSpread({}, urlMaps, _defineProperty({}, res.body.response.url, localId))
            });

            _this.props.onChange(files, 'add');
          }
        } else if (fileIndex !== -1) {
          files.splice(fileIndex, 1);

          _this.props.onChange(files, 'remove');

          _toast["default"].fail('上传失败, 请重试', 2);
        }
      });
    });

    _defineProperty(_assertThisInitialized(_this), "removeImage", function (index) {
      var newImages = [];
      var _this$props$files7 = _this.props.files,
          files = _this$props$files7 === void 0 ? [] : _this$props$files7;
      files.forEach(function (image, idx) {
        if (index !== idx) {
          newImages.push(image);
        }
      });

      _this.onChangeDefault(newImages, 'remove', index);
    });

    _defineProperty(_assertThisInitialized(_this), "addImage", function (imgItem) {
      var _this$props$files8 = _this.props.files,
          files = _this$props$files8 === void 0 ? [] : _this$props$files8;
      var newImages = files.concat(imgItem);

      _this.onChangeDefault(newImages, 'add');
    });

    _defineProperty(_assertThisInitialized(_this), "onChangeDefault", function (newFiles, operationType, index) {
      var _this$props$files9 = _this.props.files,
          files = _this$props$files9 === void 0 ? [] : _this$props$files9;
      var _this$state = _this.state,
          contentServer = _this$state.contentServer,
          token = _this$state.token;

      if (operationType === 'add') {
        var url = "".concat(contentServer, "/upload/image");
        var suffic = "token=".concat(token); // eslint-disable-next-line no-nested-ternary

        url += url.endsWith('?') ? suffic : url.includes('?') ? "&".concat(suffic) : "?".concat(suffic);
        var file = newFiles[newFiles.length - 1];
        var imgId = num++; // 最大上传固定限制20M

        var limitPerSize = _this.getSizeUnitB('20M');

        if (limitPerSize && file.file.size > limitPerSize) {
          _this.setState({
            errorVisible: true
          });

          return;
        }

        var blob = (0, _utils.dataURItoBlob)(file.url);
        var fd = new FormData();
        fd.append('upload_file', blob, file.file.name);
        files = files.slice(0);
        files.push({
          id: imgId,
          status: 'uploading',
          localUrl: file.url
        });

        _this.props.onChange(files, operationType, index);

        _superagent["default"].post(url).send(fd).end(function (err, res) {
          // eslint-disable-next-line no-shadow
          var _this$props$files10 = _this.props.files,
              files = _this$props$files10 === void 0 ? [] : _this$props$files10;
          var urlMaps = _this.state.urlMaps;
          files = files.slice(0);
          var fileIndex = files.findIndex(function (item) {
            return item.id === imgId;
          });

          if (res && res.body && res.body.errorCode === 0) {
            if (fileIndex !== -1) {
              files[fileIndex] = {
                status: 'done',
                uri: res.body.response.uri,
                url: res.body.response.url,
                fileName: file.file.name,
                uploadTime: new Date().getTime()
              };

              _this.setState({
                urlMaps: _objectSpread({}, urlMaps, _defineProperty({}, res.body.response.url, file.url))
              });

              _this.props.onChange(files, operationType, index);
            }
          } else if (fileIndex !== -1) {
            files.splice(fileIndex, 1);

            _this.props.onChange(files, operationType, index);

            _toast["default"].fail('上传失败, 请重试', 2);
          }
        });
      } else if (operationType === 'remove') {
        files = [].concat(_toConsumableArray(files.slice(0, index)), _toConsumableArray(files.slice(index + 1)));

        _this.props.onChange(files, operationType, index);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "getSizeUnitB", function (size) {
      var filesize = String(size);
      var upSize = parseInt(filesize, 10);

      if (filesize.endsWith('M')) {
        return upSize * 1024 * 1024;
      }

      if (filesize.endsWith('K')) {
        return upSize * 1024;
      }

      return upSize;
    });

    _defineProperty(_assertThisInitialized(_this), "onImageClick", function (index) {
      _this.setState({
        current: index,
        viewerVisible: true
      });

      document.addEventListener('touchmove', _this.preventTouchDefault, {
        passive: false
      });
    });

    _defineProperty(_assertThisInitialized(_this), "closeViewer", function () {
      _this.setState({
        viewerVisible: false
      });

      document.removeEventListener('touchmove', _this.preventTouchDefault);
    });

    _defineProperty(_assertThisInitialized(_this), "preventTouchDefault", function (e) {
      e.preventDefault();
    });

    _defineProperty(_assertThisInitialized(_this), "onFileChange", function () {
      var fileSelectorEl = _this.fileSelectorInput;

      if (fileSelectorEl && fileSelectorEl.files && fileSelectorEl.files.length) {
        var files = fileSelectorEl.files;
        var imageParsePromiseList = [];

        for (var i = 0; i < files.length; i++) {
          imageParsePromiseList.push(_this.parseFile(files[i], i));
        }

        Promise.all(imageParsePromiseList).then(function (imageItems) {
          return _this.addImage(imageItems);
        })["catch"](function (error) {
          if (_this.props.onFail) {
            _this.props.onFail(error);
          }
        });
      }

      if (fileSelectorEl) {
        fileSelectorEl.value = '';
      }
    });

    _defineProperty(_assertThisInitialized(_this), "parseFile", function (file, index) {
      return new Promise(function (resolve, reject) {
        var reader = new FileReader();

        reader.onload = function (e) {
          var dataURL = e.target.result;

          if (!dataURL) {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject("Fail to get the ".concat(index, " image"));
            return;
          }

          var orientation = 1;

          _this.getOrientation(file, function (res) {
            // -2: not jpeg , -1: not defined
            if (res > 0) {
              orientation = res;
            }

            resolve({
              url: dataURL,
              orientation: orientation,
              file: file
            });
          });
        };

        reader.readAsDataURL(file);
      });
    });

    var _platform = 'default';

    if (window.ehopenapi) {
      _platform = 'zuolin';
    } else if (/micromessenger/i.test(window.navigator.userAgent) && window.wx) {
      _platform = 'wx';
    }

    var _contentServer = window.localStorage.getItem('contentServer') || window.location.host; // 先去掉协议，再判断是否为443端口


    _contentServer = _contentServer.replace(/http(s)?:\/\//, '');
    _contentServer = _contentServer.split(':')[1] === '443' ? "https://".concat(_contentServer) : "http://".concat(_contentServer);

    var _token = (0, _utils.getCookie)('token');

    _this.state = {
      errorVisible: false,
      viewerVisible: false,
      current: 0,
      platform: _platform,
      urlMaps: {},
      contentServer: _contentServer,
      token: _token
    };
    return _this;
  } // http://stackoverflow.com/questions/7584794/accessing-jpeg-exif-rotation-data-in-javascript-on-the-client-side


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

      // eslint-disable-next-line prefer-const
      var _this$props2 = this.props,
          style = _this$props2.style,
          className = _this$props2.className,
          _this$props2$files = _this$props2.files,
          files = _this$props2$files === void 0 ? [] : _this$props2$files,
          accept = _this$props2.accept,
          limitCount = _this$props2.limitCount;
      var _this$state2 = this.state,
          errorVisible = _this$state2.errorVisible,
          viewerVisible = _this$state2.viewerVisible,
          current = _this$state2.current,
          platform = _this$state2.platform,
          urlMaps = _this$state2.urlMaps;
      var prefixCls = 'eh-image-upload';
      var imgItemList = [];
      var count = parseInt("".concat(this.props.length), 10);

      if (count <= 0) {
        count = 4;
      }

      var wrapCls = (0, _classnames["default"])("".concat(prefixCls), className);
      files = files.map(function (file) {
        var url = file.localUrl || file.url;
        if (urlMaps[url]) url = urlMaps[url];
        return _objectSpread({}, file, {
          url: url
        });
      });
      files.forEach(function (image, index) {
        var itemStyle = {};
        var imgStyle = {
          transform: "rotate(".concat(_this2.getRotation(image.orientation), "deg)")
        };
        imgItemList.push(_react["default"].createElement("div", {
          key: "item-".concat(index),
          className: "".concat(prefixCls, "-flex-item"),
          style: itemStyle
        }, _react["default"].createElement("div", {
          key: index,
          className: "".concat(prefixCls, "-item")
        }, _react["default"].createElement("img", {
          className: "".concat(prefixCls, "-item-img"),
          src: image.url,
          alt: "",
          style: imgStyle,
          onClick: function onClick() {
            return _this2.onImageClick(index);
          }
        }))));
      });

      var selectEl = _react["default"].createElement("div", {
        key: "select",
        className: "".concat(prefixCls, "-flex-item")
      }, _react["default"].createElement(_rmcFeedback["default"], {
        activeClassName: "".concat(prefixCls, "-upload-btn-active")
      }, _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-item ").concat(prefixCls, "-upload-btn"),
        role: "button",
        "aria-label": "Choose and add image",
        onClick: platform !== 'default' ? this.pickImage : undefined
      }, _react["default"].createElement("img", {
        src: addImage,
        alt: ""
      }), platform === 'default' ? _react["default"].createElement("input", {
        ref: function ref(input) {
          if (input) {
            _this2.fileSelectorInput = input;
          }
        },
        type: "file",
        accept: accept // tslint:disable-next-line:jsx-no-multiline-js
        ,
        onChange: function onChange() {
          _this2.onFileChange();
        },
        multiple: false
      }) : null)));

      var allEl = limitCount && files.length >= limitCount ? imgItemList : imgItemList.concat([selectEl]);
      var length = allEl.length;

      if (length !== 0 && length % count !== 0) {
        var blankCount = count - length % count;
        var fillBlankEl = [];

        for (var i = 0; i < blankCount; i++) {
          fillBlankEl.push(_react["default"].createElement("div", {
            key: "blank-".concat(i),
            className: "".concat(prefixCls, "-flex-item")
          }));
        }

        allEl = allEl.concat(fillBlankEl);
      }

      var flexEl = [];

      for (var _i = 0; _i < allEl.length / count; _i++) {
        var rowEl = allEl.slice(_i * count, _i * count + count);
        flexEl.push(rowEl);
      }

      var renderEl = flexEl.map(function (item, index) {
        return _react["default"].createElement("div", {
          key: "flex-".concat(index),
          className: "".concat(prefixCls, "-flex")
        }, item);
      });
      var imagelist = files.map(function (item) {
        return item.url;
      });
      return _react["default"].createElement("div", {
        className: wrapCls,
        style: style
      }, _react["default"].createElement("div", {
        className: "".concat(prefixCls, "-list"),
        role: "group"
      }, renderEl), _react["default"].createElement(_imageViewer["default"], {
        visible: viewerVisible,
        deletable: true,
        current: current,
        imagelist: imagelist,
        close: this.closeViewer,
        onDelete: this.removeImage
      }), _react["default"].createElement(_modal["default"], {
        visible: errorVisible,
        transparent: true,
        maskClosable: false,
        onClose: function onClose() {
          return _this2.setState({
            errorVisible: false
          });
        },
        title: "\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u4E0A\u4F20",
        footer: [{
          text: '我知道了',
          onPress: function onPress() {
            return _this2.setState({
              errorVisible: false
            });
          }
        }]
      }));
    }
  }]);

  return ImageUpload;
}(_react["default"].Component);

exports["default"] = ImageUpload;

_defineProperty(ImageUpload, "propTypes", {
  files: _propTypes["default"].array,
  onChange: _propTypes["default"].func,
  onFail: _propTypes["default"].func,
  length: _propTypes["default"].number,
  limitCount: _propTypes["default"].number,
  accept: _propTypes["default"].string
});

_defineProperty(ImageUpload, "defaultProps", {
  files: [],
  onChange: noop,
  onFail: noop,
  accept: 'image/*',
  length: 4,
  limitCount: 9
});

module.exports = exports.default;