'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _class, _temp, _VIEW$EDIT; /**
                                * Created by liuqiang on 2017/6/3.
                                */

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _mxa = require('../../../../../components/mxa');

var _StaticDisplay = require('./StaticDisplay');

var _StaticDisplay2 = _interopRequireDefault(_StaticDisplay);

var _constant = require('../../constant');

var _CacheService = require('../../../../service/CacheService');

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

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

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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

var MyUpload = (_temp = _class = function (_React$Component) {
  _inherits(MyUpload, _React$Component);

  function MyUpload(props) {
    _classCallCheck(this, MyUpload);

    var _this = _possibleConstructorReturn(this, (MyUpload.__proto__ || Object.getPrototypeOf(MyUpload)).call(this, props));

    _this.onRemove = function (file) {
      var client = _this.state.client;

      _this.setState({
        size: '0B',
        disabled: false,
        percent: 0,
        status: 'active'
      });
      _this.props.onChange && _this.props.onChange('');
      return true;
    };

    _this.customRequest = function (info, response) {
      // 开始上传
      var that = _this;
      var stsToken = _this.state.stsToken;

      var token = response || stsToken;

      if (!token || Object.keys(token).length === 0) {
        info.onError('获取token失败');
      } else {
        /* eslint-disable */
        var client = new OSS.Wrapper({
          region: 'oss-cn-hangzhou',
          accessKeyId: token.accessKeyId,
          accessKeySecret: token.accessKeySecret,
          stsToken: token.securityToken,
          bucket: 'demo-loc'
        });
        var value = token.tenantIdentifier + '/' + info.file.uid + '$' + info.file.name;
        _this.setState({
          client: client,
          value: value
        });
        client.multipartUpload(value, info.file, {
          progress: regeneratorRuntime.mark(function progress(p) {
            return regeneratorRuntime.wrap(function progress$(_context) {
              while (1) {
                switch (_context.prev = _context.next) {
                  case 0:
                    that.setState({
                      percent: ((p === 0 ? p + 0.05 : p) * 100).toFixed(2)
                    });

                  case 1:
                  case 'end':
                    return _context.stop();
                }
              }
            }, progress, this);
          })
        }).then(function (result) {
          info.onSuccess(result);
        }).catch(function (err) {
          if (err.code === 'InvalidSecurityToken' && _this.state.reloadStatus) {
            // 重试一次获取token
            that.setState({
              reloadStatus: false
            });
            (0, _CacheService.updateSecurityToken)().then(function (res) {
              _this.customRequest(info, res);
            }).catch(function (error) {
              info.onError(error.msgCode);
            });
          } else {
            info.onError(err.code + '[' + err.requestId + ']');
          }
        });
      }
    };

    _this.onChange = function (info) {
      if (info.file.status === 'done') {
        _this.setState({
          disabled: false,
          status: 'success'
        });
        _mxa.Modal.success({
          title: '上传成功',
          content: info.file.name + ' \u6587\u4EF6\u4E0A\u4F20\u6210\u529F'
        });
        var value = info.file.name + ',' + _this.state.value + ',' + info.file.size;
        _this.props.onChange && _this.props.onChange(value);
      } else if (info.file.status === 'error') {
        _this.showErrorModal(info.file, info.file.error);
      }
    };

    _this.beforeUpload = function (file) {
      var fileList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      var multiple = _this.props.multiple;

      return new Promise(function (res, rej) {
        _this.setState({
          disabled: true,
          percent: 5,
          status: 'active'
        });
        _this.validateFile(file, function (errors) {
          if (errors.length === 0) {
            if (!multiple) {
              // 不是多选，列表上只能显示一条文件信息，其余的都需要移除
              fileList.forEach(function (item) {
                // this.onRemove(file)
              });
              _this.setState({
                fileList: [file],
                size: _this.resolveFileSize(file.size)
              });
            }
            var stsToken = (0, _CacheService.getSecurityToken)();
            if (stsToken && Object.keys(stsToken).length > 0) {
              res(_this.setState({
                stsToken: stsToken,
                reloadStatus: true
              }));
            } else {
              (0, _CacheService.updateSecurityToken)().then(function (response) {
                res(_this.setState({
                  stsToken: response,
                  reloadStatus: true
                }));
              }).catch(function (err) {
                rej(_this.showErrorModal(file, err.msgCode || err));
              });
            }
          } else {
            rej(_this.showErrorModal(file, errors));
          }
        });
      });
    };

    _this.showErrorModal = function (file, err) {
      _this.setState({
        disabled: false,
        status: 'active',
        percent: 0,
        size: '0B',
        fileList: []
      });
      _this.props.onChange && _this.props.onChange('');
      _mxa.Modal.error({
        title: '上传失败',
        content: _react2.default.createElement(
          'span',
          null,
          '\u6587\u4EF6 ',
          file.name,
          ' \u4E0A\u4F20\u5931\u8D25\uFF01 ',
          _react2.default.createElement('br', null),
          ' \u5931\u8D25\u539F\u56E0\uFF1A ',
          err
        )
      });
    };

    _this.validateFile = function (file, call) {
      var errors = [];
      var reg = /[,|$]|[/|\\]/g;
      if (reg.test(file.name)) {
        errors.push('nameError');
      }
      if (file.size / 1024 / 1024 > 10) {
        errors.push('sizeError');
      }
      var accepts = Object.keys(_this.state.accept).reduce(function (a, b) {
        return a.concat(_this.state.accept[b]);
      }, []);
      if (!accepts.includes(file.type)) {
        errors.push('typeError');
      }
      if (file.name.length > 100) {
        errors.push('nameLengthError');
      }
      if (errors.length > 1) {
        call(errors.map(function (error) {
          return _react2.default.createElement(
            'span',
            null,
            _react2.default.createElement('br', null),
            _this.state.fileTypeError[error].value
          );
        }));
      } else {
        call(errors.map(function (error) {
          return _react2.default.createElement(
            'span',
            null,
            _this.state.fileTypeError[error].value,
            _react2.default.createElement('br', null),
            _this.state.fileTypeError[error].desc,
            _react2.default.createElement('br', null)
          );
        }));
      }
    };

    _this.resolveFileSize = function (size) {
      var tempSize = '0B';
      if (size >= 0 && size < 1024) {
        tempSize = size + 'B';
      }
      if (size >= 1024 && size < 1024 * 1024) {
        tempSize = (size / 1024).toFixed(2) + 'K';
      }
      if (size >= 1024 * 1024) {
        tempSize = (size / (1024 * 1024)).toFixed(2) + 'M';
      }
      return tempSize;
    };

    _this.state = {
      accept: {
        office: ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.ms-powerpoint', 'application/msword', 'application/vnd.ms-excel'],
        pdf: ['application/pdf'],
        img: ['image/png', 'image/jpg', 'image/jpeg'],
        text: ['text/plain']
      },
      fileTypeError: {
        nameError: {
          value: '文件名不合法！',
          desc: '文件名不能包含美元符号，逗号，斜杠，反斜杠，请修改后再上传！'
        },
        sizeError: {
          value: '文件大小超过限制！',
          desc: '文件大小不能超过10M！'
        },
        typeError: {
          value: '文件类型错误！',
          desc: '文件类型仅支持静态图片、office(支持doc、docx、xls、xlsx、ppt、pptx)文档、pdf文档和普通文本文档！'
        },
        nameLengthError: {
          value: '文件名错误！',
          desc: '文件名长度不能超过100个字符！'
        }
      },
      stsToken: '',
      client: {},
      fileList: [],
      value: '',
      disabled: false,
      size: '0B',
      status: 'active',
      percent: 0,
      reloadStatus: true
    };
    return _this;
  }

  _createClass(MyUpload, [{
    key: 'render',
    value: function render() {
      var multiple = this.props.multiple;

      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(
            _mxa.Upload,
            {
              onChange: this.onChange,
              customRequest: this.customRequest,
              onRemove: this.onRemove,
              multiple: multiple,
              fileList: this.state.fileList,
              beforeUpload: this.beforeUpload
            },
            _react2.default.createElement(
              _mxa.Button,
              { disabled: this.state.disabled },
              _react2.default.createElement(_mxa.Icon, { type: 'upload' }),
              ' \u9009\u62E9\u6587\u4EF6'
            )
          )
        ),
        _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(
            'span',
            null,
            '文件大小：' + this.state.size
          ),
          _react2.default.createElement('br', null),
          _react2.default.createElement(_mxa.Progress, { percent: this.state.percent, status: this.state.status })
        )
      );
    }
  }]);

  return MyUpload;
}(_react2.default.Component), _class.defaultProps = {
  multiple: false
}, _temp);


var compRender = function compRender(config) {
  var _config$record = config.record,
      record = _config$record === undefined ? {} : _config$record;

  return _react2.default.createElement(MyUpload, {
    multiple: record.multiple || false
  });
};

exports.default = (_VIEW$EDIT = {}, _defineProperty(_VIEW$EDIT, _constant.VIEW, _StaticDisplay2.default), _defineProperty(_VIEW$EDIT, _constant.EDIT, compRender), _VIEW$EDIT);