/**
 * [OElove] (C)2010-2099 oelove.com  biz
 * Email: service@phpcoo.com ,phpcoo@qq.com
 * This is NOT a freeware, use is subject to license terms
 * $ Last update 2020/11/11 by BO $
*/
(function () {
    /**
     * @param {el, data, url, color, width, height, bgColor} options 
     * @function on 绑定事件
     */
    function OEUploader (options) {
        var option = {
            color: '#999',
            width: 30,
            height: 30,
            bgColor: '#fff'
        };
        this.events = {};
        this.option = $.extend({}, option, options);
        this.el = typeof options.el == 'object' ? options.el: document.querySelector(options.el);
    }
    OEUploader.prototype = {
        on: function (name, cb){ 
            if(this.events [name]){ 
                this.events [name].push(cb); 
            } else { 
                this.events [name] = [cb]; 
            } 
        },
        callHook: function (name, arg){ 
            if(this.events [name]){ 
                const result = [];
                this.events [name] .forEach(eventListener => { 
                    let res = eventListener(... arg); 
                    result.push(res);
                }); 
                if(result.some( v => {return v === false})) {
                    return false;
                } else {
                    return true;
                }
            } 
            return true;
        },
        initUploader: function () {
            if (typeof Uploader == 'undefined') return;
            var loading;
            var upload = new Uploader({
                el: this.el,
                url: this.option.url,
                data: this.option.data
            });
            var _this = this;
            upload.on('beforeUpload', function (e) {
                var file = e.target.files[0];
                var regexp = /.(gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG)$/;
                if (!regexp.test(file.name)) {
                    OEUI.message.msg({ text: '请上传gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG格式的图片' });
                    return false;
                }
                var beforeUpload = _this.callHook('beforeUpload', e);
                if(!beforeUpload) {
                    return;
                }
                loading = OEUI.loading({
                    el: _this.el,
                    color: _this.option.color,
                    width: _this.option.width,
                    height: _this.option.height,
                    bgColor: _this.option.bgColor
                });
                loading.show();
                return true;
            });
            upload.on('success', function (res) {
                _this.callHook('success', res);
                loading.remove();
            });
            upload.on('error', function () {
                _this.callHook('error');
                loading.remove();
            });
        },
    }
    window.OEUploader = OEUploader;
})();