'use strict';

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

var _defineProperty2 = require('babel-runtime/helpers/defineProperty');

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var React = _interopRequireWildcard(_react);

var _reactLifecyclesCompat = require('react-lifecycles-compat');

var _rcUpload = require('rc-upload');

var _rcUpload2 = _interopRequireDefault(_rcUpload);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _uniqBy = require('lodash/uniqBy');

var _uniqBy2 = _interopRequireDefault(_uniqBy);

var _findIndex = require('lodash/findIndex');

var _findIndex2 = _interopRequireDefault(_findIndex);

var _UploadList = require('./UploadList');

var _UploadList2 = _interopRequireDefault(_UploadList);

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

var _LocaleReceiver = require('antd/lib/locale-provider/LocaleReceiver');

var _LocaleReceiver2 = _interopRequireDefault(_LocaleReceiver);

var _default = require('../locale/default');

var _default2 = _interopRequireDefault(_default);

var _configProvider = require('antd/lib/config-provider');

var _warning = require('../_util/warning');

var _warning2 = _interopRequireDefault(_warning);

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)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }

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

var Upload = function (_React$Component) {
    (0, _inherits3['default'])(Upload, _React$Component);

    function Upload(props) {
        (0, _classCallCheck3['default'])(this, Upload);

        var _this = (0, _possibleConstructorReturn3['default'])(this, (Upload.__proto__ || Object.getPrototypeOf(Upload)).call(this, props));

        _this.saveUpload = function (node) {
            _this.upload = node;
        };
        _this.onStart = function (file) {
            var fileList = _this.state.fileList;

            var targetItem = (0, _utils.fileToObject)(file);
            targetItem.status = 'uploading';
            var nextFileList = fileList.concat();
            var fileIndex = (0, _findIndex2['default'])(nextFileList, function (_ref) {
                var uid = _ref.uid;
                return uid === targetItem.uid;
            });
            if (fileIndex === -1) {
                nextFileList.push(targetItem);
            } else {
                nextFileList[fileIndex] = targetItem;
            }
            _this.onChange({
                file: targetItem,
                fileList: nextFileList
            });
            // fix ie progress
            if (!window.File || process.env.TEST_IE) {
                _this.autoUpdateProgress(0, targetItem);
            }
        };
        _this.onSuccess = function (response, file, xhr) {
            _this.clearProgressTimer();
            try {
                if (typeof response === 'string') {
                    response = JSON.parse(response);
                }
            } catch (e) {
                /* do nothing */
            }
            var fileList = _this.state.fileList;

            var targetItem = (0, _utils.getFileItem)(file, fileList);
            // removed
            if (!targetItem) {
                return;
            }
            targetItem.status = 'done';
            targetItem.response = response;
            targetItem.xhr = xhr;
            _this.onChange({
                file: (0, _extends3['default'])({}, targetItem),
                fileList: fileList
            });
        };
        _this.onProgress = function (e, file) {
            var fileList = _this.state.fileList;

            var targetItem = (0, _utils.getFileItem)(file, fileList);
            // removed
            if (!targetItem) {
                return;
            }
            targetItem.percent = e.percent;
            _this.onChange({
                event: e,
                file: (0, _extends3['default'])({}, targetItem),
                fileList: fileList
            });
        };
        _this.onError = function (error, response, file) {
            _this.clearProgressTimer();
            var fileList = _this.state.fileList;

            var targetItem = (0, _utils.getFileItem)(file, fileList);
            // removed
            if (!targetItem) {
                return;
            }
            targetItem.error = error;
            targetItem.response = response;
            targetItem.status = 'error';
            _this.onChange({
                file: (0, _extends3['default'])({}, targetItem),
                fileList: fileList
            });
        };
        _this.handleRemove = function (file) {
            var onRemove = _this.props.onRemove;
            var fileList = _this.state.fileList;

            Promise.resolve(typeof onRemove === 'function' ? onRemove(file) : onRemove).then(function (ret) {
                // Prevent removing file
                if (ret === false) {
                    return;
                }
                var removedFileList = (0, _utils.removeFileItem)(file, fileList);
                if (removedFileList) {
                    file.status = 'removed'; // eslint-disable-line
                    if (_this.upload) {
                        _this.upload.abort(file);
                    }
                    _this.onChange({
                        file: file,
                        fileList: removedFileList
                    });
                }
            });
        };
        _this.onChange = function (info) {
            if (!('fileList' in _this.props)) {
                _this.setState({ fileList: info.fileList });
            }
            var onChange = _this.props.onChange;

            if (onChange) {
                onChange(info);
            }
        };
        _this.onFileDrop = function (e) {
            _this.setState({
                dragState: e.type
            });
        };
        _this.beforeUpload = function (file, fileList) {
            var beforeUpload = _this.props.beforeUpload;
            var stateFileList = _this.state.fileList;

            if (!beforeUpload) {
                return true;
            }
            var result = beforeUpload(file, fileList);
            if (result === false) {
                _this.onChange({
                    file: file,
                    fileList: (0, _uniqBy2['default'])(stateFileList.concat(fileList.map(_utils.fileToObject)), function (item) {
                        return item.uid;
                    })
                });
                return false;
            }
            if (result && result.then) {
                return result;
            }
            return true;
        };
        _this.renderUploadList = function (locale) {
            var _this$props = _this.props,
                showUploadList = _this$props.showUploadList,
                listType = _this$props.listType,
                onPreview = _this$props.onPreview,
                onDownload = _this$props.onDownload,
                previewFile = _this$props.previewFile,
                disabled = _this$props.disabled,
                propLocale = _this$props.locale;
            var showRemoveIcon = showUploadList.showRemoveIcon,
                showPreviewIcon = showUploadList.showPreviewIcon,
                showDownloadIcon = showUploadList.showDownloadIcon,
                downloadIcon = showUploadList.downloadIcon,
                removeIcon = showUploadList.removeIcon;
            var fileList = _this.state.fileList;

            return React.createElement(_UploadList2['default'], { listType: listType, items: fileList, previewFile: previewFile, onPreview: onPreview, onDownload: onDownload, onRemove: _this.handleRemove, showRemoveIcon: !disabled && showRemoveIcon, showPreviewIcon: showPreviewIcon, downloadIcon: downloadIcon, removeIcon: removeIcon, showDownloadIcon: showDownloadIcon, locale: (0, _extends3['default'])((0, _extends3['default'])({}, locale), propLocale) });
        };
        _this.renderUpload = function (_ref2) {
            var _classNames2;

            var getPrefixCls = _ref2.getPrefixCls;
            var _this$props2 = _this.props,
                customizePrefixCls = _this$props2.prefixCls,
                className = _this$props2.className,
                showUploadList = _this$props2.showUploadList,
                listType = _this$props2.listType,
                type = _this$props2.type,
                disabled = _this$props2.disabled,
                children = _this$props2.children,
                style = _this$props2.style;
            var _this$state = _this.state,
                fileList = _this$state.fileList,
                dragState = _this$state.dragState;

            var prefixCls = getPrefixCls('upload', customizePrefixCls);
            var rcUploadProps = (0, _extends3['default'])((0, _extends3['default'])({ onStart: _this.onStart, onError: _this.onError, onProgress: _this.onProgress, onSuccess: _this.onSuccess }, _this.props), { prefixCls: prefixCls, beforeUpload: _this.beforeUpload });
            delete rcUploadProps.className;
            delete rcUploadProps.style;
            // Remove id to avoid open by label when trigger is hidden
            // !children: https://github.com/ant-design/ant-design/issues/14298
            // disabled: https://github.com/ant-design/ant-design/issues/16478
            //           https://github.com/ant-design/ant-design/issues/24197
            if (!children || disabled) {
                delete rcUploadProps.id;
            }
            var uploadList = showUploadList ? React.createElement(
                _LocaleReceiver2['default'],
                { componentName: 'Upload', defaultLocale: _default2['default'].Upload },
                _this.renderUploadList
            ) : null;
            if (type === 'drag') {
                var _classNames;

                var dragCls = (0, _classnames2['default'])(prefixCls, (_classNames = {}, (0, _defineProperty3['default'])(_classNames, prefixCls + '-drag', true), (0, _defineProperty3['default'])(_classNames, prefixCls + '-drag-uploading', fileList.some(function (file) {
                    return file.status === 'uploading';
                })), (0, _defineProperty3['default'])(_classNames, prefixCls + '-drag-hover', dragState === 'dragover'), (0, _defineProperty3['default'])(_classNames, prefixCls + '-disabled', disabled), _classNames), className);
                return React.createElement(
                    'span',
                    null,
                    React.createElement(
                        'div',
                        { className: dragCls, onDrop: _this.onFileDrop, onDragOver: _this.onFileDrop, onDragLeave: _this.onFileDrop, style: style },
                        React.createElement(
                            _rcUpload2['default'],
                            (0, _extends3['default'])({}, rcUploadProps, { ref: _this.saveUpload, className: prefixCls + '-btn' }),
                            React.createElement(
                                'div',
                                { className: prefixCls + '-drag-container' },
                                children
                            )
                        )
                    ),
                    uploadList
                );
            }
            var uploadButtonCls = (0, _classnames2['default'])(prefixCls, (_classNames2 = {}, (0, _defineProperty3['default'])(_classNames2, prefixCls + '-select', true), (0, _defineProperty3['default'])(_classNames2, prefixCls + '-select-' + listType, true), (0, _defineProperty3['default'])(_classNames2, prefixCls + '-disabled', disabled), _classNames2));
            var uploadButton = React.createElement(
                'div',
                { className: uploadButtonCls, style: children ? undefined : { display: 'none' } },
                React.createElement(_rcUpload2['default'], (0, _extends3['default'])({}, rcUploadProps, { ref: _this.saveUpload }))
            );
            if (listType === 'picture-card') {
                return React.createElement(
                    'span',
                    { className: (0, _classnames2['default'])(className, prefixCls + '-picture-card-wrapper') },
                    uploadList,
                    uploadButton
                );
            }
            return React.createElement(
                'span',
                { className: className },
                uploadButton,
                uploadList
            );
        };
        _this.state = {
            fileList: props.fileList || props.defaultFileList || [],
            dragState: 'drop'
        };
        (0, _warning2['default'])('fileList' in props || !('value' in props), 'Upload', '`value` is not validate prop, do you mean `fileList`?');
        return _this;
    }

    (0, _createClass3['default'])(Upload, [{
        key: 'componentWillUnmount',
        value: function componentWillUnmount() {
            this.clearProgressTimer();
        }
    }, {
        key: 'clearProgressTimer',
        value: function clearProgressTimer() {
            clearInterval(this.progressTimer);
        }
    }, {
        key: 'autoUpdateProgress',
        value: function autoUpdateProgress(_, file) {
            var _this2 = this;

            var getPercent = (0, _utils.genPercentAdd)();
            var curPercent = 0;
            this.clearProgressTimer();
            this.progressTimer = setInterval(function () {
                curPercent = getPercent(curPercent);
                _this2.onProgress({
                    percent: curPercent * 100
                }, file);
            }, 200);
        }
    }, {
        key: 'render',
        value: function render() {
            return React.createElement(
                _configProvider.ConfigConsumer,
                null,
                this.renderUpload
            );
        }
    }], [{
        key: 'getDerivedStateFromProps',
        value: function getDerivedStateFromProps(nextProps) {
            if ('fileList' in nextProps) {
                return {
                    fileList: nextProps.fileList || []
                };
            }
            return null;
        }
    }]);
    return Upload;
}(React.Component);
// @ts-ignore


Upload.defaultProps = {
    type: 'select',
    multiple: false,
    action: '',
    data: {},
    accept: '',
    beforeUpload: _utils.T,
    showUploadList: true,
    listType: 'text',
    className: '',
    disabled: false,
    supportServerRender: true
};
(0, _reactLifecyclesCompat.polyfill)(Upload);
exports['default'] = Upload;
module.exports = exports['default'];