import _extends from 'babel-runtime/helpers/extends';
import defaultRequest from './request';
import Toast from '../toast';

function fileToObject(file) {
    return _extends({}, file, {
        lastModified: file.lastModified,
        lastModifiedDate: file.lastModifiedDate,
        name: file.name,
        size: file.size,
        type: file.type,
        uid: file.uid,
        percent: 0,
        originFileObj: file
    });
}
var Upload = {
    props: {
        beforeUpload: Function, //选中文件后上传文件前的校验检查
        action: {
            type: String,
            'default': ''
        },
        customRequest: Function, //上传文件列表的方法，若没有设置，则默认使用h5的ajax请求上传
        method: {
            //h5的ajax请求上传的method
            type: String,
            'default': 'POST'
        },
        //是否支持多选
        multiple: {
            type: Boolean,
            'default': function _default() {
                return true;
            } // or false
        },
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    },
    data: function data() {
        return {
            index: 0,
            reqs: function reqs() {
                return [];
            }
        };
    },
    beforeCreate: function beforeCreate() {},
    created: function created() {},
    mounted: function mounted() {},

    methods: {
        //触发系统的文件选择
        selectFile: function selectFile() {
            var el = this.$refs.fileInputRef;
            if (!el) {
                return;
            }
            el.click();
            this.index++;
        },
        onChange: function onChange(e) {
            var files = e.target.files;
            if (files) {
                this.beforeUploadfiles(files);
                this.$refs.fileInputRef.value = null;
            }
        },

        //提供给外层直接调用文件选中后上传之前的前置检查入口
        beforeUploadfiles: function beforeUploadfiles(files) {
            var _this = this;

            var fileList = Array.prototype.slice.call(files);
            var request = this.customRequest || this.uploadfiles;
            if (!this.beforeUpload) {
                request.bind(this, files)();
            }
            var before = this.beforeUpload(fileList);
            if (before === true) {
                request.bind(this, files)();
            } else if (before && before.then) {
                before.then(function (processFile) {
                    processFile && request.bind(_this, processFile)();
                })['catch'](function (e) {
                    Toast(e);
                    console && console.log(e); // eslint-disable-line
                });
            } else if (before !== false) {
                request.bind(this, before)();
            }
        },

        // 批量上传文件方法
        // 如果用户传递了customRequest属性方法，则调用customRequest方法，
        // 默认使用uploadfiles方法
        // 参数为file对象数组
        uploadfiles: function uploadfiles(processFile) {
            var _this2 = this;

            processFile.forEach(function (file) {
                var uid = _this2.getUid();
                file.uid = uid;
                var fileObj = void 0;
                if (typeof file === 'object' && file.status === 'upload-error') {
                    fileObj = _extends({}, file);
                    file = file.originFileObj;
                } else {
                    fileObj = fileToObject(file);
                }
                var action = file.uploadUrl || _this2.$props['action'];

                var options = {
                    action: action,
                    data: file,
                    headers: _this2.headers,
                    method: _this2.method,
                    onProgress: function onProgress(e) {
                        _this2.progress(e, fileObj);
                    },
                    onSuccess: function onSuccess(ret, xhr) {
                        fileObj.options = options;
                        _this2.success(fileObj, ret, xhr);
                    },
                    onError: function onError(err, ret) {
                        console.log('directUpload failed. fileName: ');
                        delete _this2.reqs[uid];
                        _this2.error(fileObj, err, ret);
                    }
                };
                _this2.start(fileObj);
                _this2.reqs[uid] = defaultRequest(options);
            });
        },
        success: function success(fileObj, ret, xhr) {
            fileObj.status = 'uploaded';
            this.$emit('success', fileObj);
        },

        //文件开始上传事件
        start: function start(fileObj) {
            fileObj.status = 'uploading';
            this.$emit('start', fileObj);
        },

        // 附件上传失败
        error: function error(fileObj, info, result) {
            fileObj.status = 'upload-error';
            Toast(fileObj.name + '\u4E0A\u4F20\u5931\u8D25');
            this.$emit('error', fileObj);
        },

        //文件上传过程中事件，一般显示进度条使用
        progress: function progress(info, fileObj) {
            fileObj.percent = parseInt(info.loaded * 100 / fileObj.size);
            this.$emit('progress', info, fileObj);
        },

        // 生成上传文件唯一标识
        getUid: function getUid() {
            return 'vc-upload-' + +new Date() + '-' + ++this.index;
        },

        // 根据文件的唯一标识取消上传过程中的文件
        // 参数file对象
        // {
        //  uid: 上传文件的唯一标识
        // }
        // 附件上传成功
        abort: function abort(file) {
            var reqs = this.reqs;
            var uid = file.uid;

            if (reqs[uid]) {
                reqs[uid].abort();
            }
            delete reqs[uid];
        }
    },
    render: function render() {
        var h = arguments[0];

        return h('input', {
            attrs: {
                type: 'file',

                multiple: this.multiple
            },
            key: this.uid,
            ref: 'fileInputRef',
            style: { display: 'none' }, on: {
                'change': this.onChange
            }
        });
    }
};
export default Upload;