/**
 * kunbei  增加上传进度条显示
 * 应用于： file-upload.js
 * OCA.Files._uploadProgressBar 
 * 本文件代码 已经被 移动到 同文件夹的 file-upload.js 中。
 * 不再维护本份代码
 * 2019-10-10
 */
(function () {
    var UploadFilesModels = OC.Backbone.Model.extend({
        defaults: {
            _progress: {},
            files: {},
            uploadId: '',
            dir: '/'
        },
        initialize(attributes) {
            this.set(attributes);

        },
        sync: function () {
            return false;
        }

    });
    var UploadFilesCollection = OC.Backbone.Collection.extend({
        model: UploadFilesModels,
        comparator: 'time',
   
    });
    /**
     * 进度条框 的单个文件 进度显示
     * @type type
     */
    var UploadProgressBarItemView = OC.Backbone.View.extend({
        tagName: 'li',
        className: 'file-list status-success',
        $li: '',
        events: {
               "click a.server_path": "opendir"
           },   
        //初始化
        initialize: function () {

            this.model.on('change:loaded', this.render, this);
        },
        //打开上传目录
        opendir : function(ev){
              if (ev && ev.preventDefault) { ev.preventDefault(); }           
              OCA.Files._uploadProgressBar.fileList.changeDirectory(this.model.get("dir"), false)
        },

        render: function () {

            var $tpl = $('<div><div class="process" style="{style}"></div>\n\
                <div class="info"><div class="file-name" title="{name}"><span class="name-text">{name}</span></div>\n\
                <div class="file-size">{totalSize}</div>\n\
                <div class="file-path"><a title="{dir}" class="server_path" data-dir="{dir}">{dir}</a></div>\n\
                <div class="file-status"></div></div>');
            //
            var _progress = this.model.get('_progress');

            var progress = Math.ceil((_progress.loaded / _progress.total) * 100);
            var style = 'width: ' + progress + '%;';
            if (progress > 99) {
                style = 'width: 0%;';
            }
            var bitrate = humanFileSize(_progress.bitrate / 8) + '/s';
            
            this.$li = $tpl.octemplate({
                dir: this.model.get('dir'),              
                style: style,
                uploadId: this.model.get('uploadId'),
                name: this.model.get('files')[0].name,
                loadedSize: humanFileSize(_progress.loaded),
                totalSize: humanFileSize(_progress.total),
                bitrate: bitrate,
            });
            //上传状态改变
            if (_progress.loaded == 0) {
               
                this.$li.find('.file-status').html('<span class="waiting">等待…</span>');
                
            } else {
                if (_progress.loaded < _progress.total) {
                    this.$li.find('.file-status').html('<span class="uploading"><em class="precent">' + progress + '%</em><em class="speed">(' + bitrate + ')</em></span>');

                } else if (_progress.loaded == _progress.total) { //传输完成
                    this.$li.find('.file-status').html('<span class="success"><i>完成</i></span>')
                }
            }
            this.$el.html(this.$li);
            return true;
        },
        
    })
    /**
     * 这个是 底部弹出的 进度条对话框
     * 包括 多个 文件的进度条显示
     * @type type
     */
    var UploadProgressBarView = OC.Backbone.View.extend({
        id: 'app-dialog-progressbar',
        tagName: 'div',
        className: 'oc-dialog-progress dialog-web-uploader',
        //对话框位置大小
        _showPosition: {width: "600px", height: "420px", right: "20px", bottom: "2px", position: "fixed"},
        //当前状态是展开还是最小化
        _isbigshow: 1,
        //总文件数
        fileCount: 0,
        UpfilesData: null, //这个是上传的当个文件模型
        //要显示的文件数组

        events: {
            'click a.closeDialog': '_onClose',
            'click a.toggleDialog': '_togglebox',
            'keyup .tabHeaders .tabHeader': '_onKeyboardActivateTab'
        },
        //  创建实例时初始化
        initialize: function (options) {
            this.model = new OC.Backbone.Model({
                "files": [],
                "title": '上传文件',
                totalCount: 0,
            }); 
            //要显示进度条的文件数据集合
           this.UpfilesData = new UploadFilesCollection();

            options = options || {};
            if (options.position) {
                //覆盖_showPosition 样式属性
                for (var a in option.positon) {
                    this._showPosition[a] = option.positon[a];
                }
            }
            this.fileList = options.fileList;
        },
        /**
         * 创建添加到列表的数据模型
         * @param {type} data
         * @returns {undefined}
         */
        createUpfileData: function (data) {
            OCA.Files.$progressViews = OCA.Files.$progressViews || {};
            if (!this.UpfilesData.findWhere({"uploadId": data.uploadId})) {
                /*添加上传文件到 数据模型中*/             
                var model  = new UploadFilesModels(  {
                    _progress: data._progress,
                    files: data.files,
                    uploadId: data.uploadId,
                    dir: data.dir,
                    time: new Date(),
                });
                this.UpfilesData.add(model);
                //添加到数据集合中
                var uploadId = data.uploadId;
                if (!OCA.Files.$progressViews[uploadId]) {
                        OCA.Files.$progressViews[uploadId] = new UploadProgressBarItemView( {"model": model} );
                    }
                 OCA.Files.$progressViews[uploadId].render();
                this.$el.find("#uploaderList").prepend(OCA.Files.$progressViews[uploadId].$el);
            }           
            this._show();          
        },
  
        //某个文件的进度变化了
        fileuploadprogress: function (data) {
            var uploadId = data.uploadId;    
            if (this.UpfilesData.findWhere({"uploadId": uploadId})) {
               
                OCA.Files.$progressViews[uploadId].model.set({"_progress": data._progress});
                OCA.Files.$progressViews[uploadId].model.set('loaded', data._progress.loaded);
             
            }
        },
        //模板内容
        _template: function () {
            var html = '<div class="progress-container"><div class="barhead">'
                    + '<h2 class="oc-dialog-title"> {title}</h2>'
                    + '<div class="dialogBtn"><a class="toggleDialog"><i class="ton ton-minimize"></i></a> <a class="closeDialog"><i class="ton ton-close"></i></a> </div>'
                    + '</div>'
                    + '<div class="uploader-list-wrapper uploader-list"> '
                    + '<div class="uploader-list-header"><div class="file-name">文件(夹)名</div><div class="file-size">大小</div> '
                    + '<div class="file-path">上传目录</div><div class="file-status">状态</div> </div>'
                    + '<ul class="container" id="uploaderList"></ul>'
                    + '</div></div>';
            this.$tmpl = $(html);
            return this.$tmpl;
        },
        //渲染模板
        render: function () {
            var $tmpl = this._template();
            this.$el.html($tmpl.octemplate(this.model.toJSON()));
        },
        /*显示*/
        showAsDailog: function () {
            this.render();
            this.$el.css(this._showPosition);

            $('body').append(this.$el);

        },
        //最大化和最小化
        _togglebox: function (event) {
            event.preventDefault();
            if (this._isbigshow == 1) {
                this._bh = this.$el.height();
                this.$el.css({height: "42px"});
                this._isbigshow = 0;
                this.$el.find('.uploader-list-wrapper').hide();
                this.$el.find(".toggleDialog i").removeClass("ton ton-minimize");
                this.$el.find(".toggleDialog i").addClass("ton ton-maximize");

            } else {
                this.$el.css({height: this._bh + "px"});
                this._isbigshow = 1;
                this.$el.find('.uploader-list-wrapper').show();
                this.$el.find(".toggleDialog i").removeClass("ton ton-maximize");
                this.$el.find(".toggleDialog i").addClass("ton ton-minimize");

            }

        },
        _show: function () {
            var $appSidebar = this.$el || $("#app-dialog-progressbar");
            this.$el.show('slide', {direction: 'right'}, 300,
                    function () {
                        $appSidebar.removeClass('disappear');
                    });
        },
        //关闭窗口
        _onClose: function (event) {
            var $appSidebar = this.$el || $("#app-dialog-progressbar");
            this.$el.hide('slide', {direction: 'right'}, 300,
                    function () {
                        $appSidebar.addClass('disappear');
                    });
            //$('#app-content').trigger(new $.Event('appresized'));
        },

    });

    OCA.Files.UploadProgressBarView = UploadProgressBarView;
 
})();


