Ext.define('Ext.ux.multiupload.Panel', {
    extend: 'Ext.grid.Panel',
    requires: [
        'Ext.ux.multiupload.Upload',
        'Skirtle.grid.column.Component'
    ],
    viewConfig: {
        markDirty: false
    },
        store: {
            fields: ['ident', 'name', 'size', 'status', 'progress', 'md5']
        },

    tbarTitle: this.tbarTitle || '',
    animCollapse: false,
    initComponent: function () {
        var me = this;

        me.addEvents('fileuploadcomplete');

        //this.uploadConfig.panelId = Math.random().toString(36).substr(2);
        this.downloadOnly = this.downloadOnly || false;

        if (!this.downloadOnly) {
            me.tbar = [this.tbarTitle, '->',
                {
                    xtype: 'uploader',
                    //id: 'cal_uploader',
                    width: this.uploadConfig.buttonWidth || 78,
                    uploadConfig: this.uploadConfig,
                    listeners:
                {
                    'fileadded': function (source, file) {
                        //這邊先做重複檔案檢核，後續再改用swfUload
                        var s = this.up('grid').store;

                        if (s.find('name', file.fileName) == -1) {
                            s.add({
                                id: file.fileIndex,
                                name: file.fileName,
                                size: file.fileSize,
                                status: '',
                                progress: 0
                            });

                        } else {
                            //alert("【" + file.fileName + "】已存在附件清單中");
                            alert(String.format(AttExist, file.fileName));
                        }
                    },
                    'uploadstart': function (source, file) {
                        var grid = this.up('grid');
                        var record = grid.store.getById(file.fileIndex);

                        //                    if (record) {
                        //                        record.set('status', '上傳中....');
                        //                    }
                    },
                    'uploadprogress': function (source, file) {
                        var grid = this.up('grid');
                        var record = grid.store.getById(file.fileIndex);
                        if (record) {
                            var p = Math.round(file.fileProgress / file.fileSize * 100);
                            record.set('progress', p);
                        }
                    },
                    'uploaddatacomplete': function (source, file) {

                        var grid = this.up('grid');
                        var record = grid.store.getById(file.fileIndex);

                        if (record) {
                            record.set('status', 'N');
                            record.set('md5', file.data);
                        }
                        me.fireEvent('fileuploadcomplete', file.data);
                    },
                    'queuedatacomplete': function (source, data) {
                        //                    Ext.Msg.show({
                        //                        title: 'Info',
                        //                        msg: 'Queue upload end. ' + data.files + ' file(s) uploaded.',
                        //                        buttons: Ext.Msg.OK,
                        //                        icon: Ext.Msg.INFO
                        //                    });
                    },
                    'uploaderror': function (src, data) {
                        var msg = 'Error Type： ' + data.errorType;

                        switch (data.errorType) {
                            case 'FileSize':
                                msg = 'This file is too big: ' + Ext.util.Format.fileSize(data.fileSize) +
                                '. The maximum upload size is ' + Ext.util.Format.fileSize(data.maxFileSize) + '.';
                                break;
                            case 'QueueLength':
                                msg = 'Queue length is too long: ' + data.queueLength +
                                '. The maximum queue length is ' + data.maxQueueLength + '.';
                                break;
                        }

                        Ext.Msg.show({
                            title: UploadError,
                            msg: msg,
                            buttons: Ext.Msg.OK,
                            icon: Ext.Msg.ERROR
                        });
                    }
                }
                },
                '-', {
                    text: RemoveFile,
                    icon: '/Common/DMZ/Images/16x16/DeleteRed.png',
                    handler: function () {
                        Ext.each(me.getSelectionModel().getSelection(), function (item) {
                            me.store.remove(item);
                        });
                        //this.store.remove();
                    }
                }];
        }



        me.columns = {
            items:
                [
                    {
                        header: '',
                        width: 25,
                        hideable: false,
                        sortable: false,
                        renderer: function (value, m, record) {
                            //if (record.data['md5'] == '') return "";

                            var filename = record.data['name'];
                            var ext = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : '';
                            var icon = "";
                            switch (ext.toString().toLowerCase()) {
                                case 'rar':
                                    icon = '/Common/DMZ/Images/16x16/FileType/winrar.png';
                                    break;
                                case '7z':
                                    icon = '/Common/DMZ/Images/16x16/FileType/7-zip.png';
                                    break;
                                case 'xls':
                                case 'xlsx':
                                    icon = '/Common/DMZ/Images/16x16/FileType/excel.png';
                                    break;
                                case 'swf':
                                    icon = '/Common/DMZ/Images/16x16/FileType/flash.png';
                                    break;
                                case 'pdf':
                                    icon = '/Common/DMZ/Images/16x16/FileType/pdf.png';
                                    break;
                                case 'jpg':
                                case 'bmp':
                                case 'gif':
                                    icon = '/Common/DMZ/Images/16x16/FileType/picture.png';
                                    break;
                                case 'ppt':
                                case 'pptx':
                                    icon = '/Common/DMZ/Images/16x16/FileType/powerpoint.png';
                                    break;
                                case 'doc':
                                case 'docx':
                                    icon = '/Common/DMZ/Images/16x16/FileType/word.png';
                                    break;
                                default:
                                    icon = '/Common/DMZ/Images/16x16/FileType/text.png';
                                    break;
                            }

                            return '<img src=' + icon + '/>';
                        }
                    },
                    { header: FileName, dataIndex: 'name', width: 150, hideable: false, flex: 1 },
                    { header: FileSize, dataIndex: 'size', align: 'right', hideable: false, renderer: Ext.util.Format.fileSize },
                    {
                        //text: "<span style='cursor:pointer;vertical-align: middle;' width=100%><img src=/ePortal/Kernel/DMZ/Images/16x16/Download_Disk.png>&nbsp;下載全部</span>",
                        //text: "<span style='cursor:pointer;background-position: 0px 3px;background-image: url(/Common/DMZ/Images/16x16/Download_Disk.png);background-repeat: no-repeat;display: block;padding: 0 10px 0 20px;line-height: 20px;'>下載全部</span>",
                        id: me.id + 'DLALL',
                        dataIndex: 'progress',
                        xtype: 'componentcolumn',
                        width: 80,
                        hideable: false,
                        sortable: false,
                        renderer: function (value, m, record) {
                            m.style = 'padding:0 0 0 0';
                            var ident = record.data['ident'];
                            if (record.data['status'] == 'S') {
                                return {
                                    xtype: 'toolbar',
                                    padding: '0 0 0 15',
                                    border: false,
                                    items: [
                                        {
                                            text: Download,
                                            xtype: 'button',
                                            //width: 75,
                                            icon: '/Common/DMZ/Images/16x16/download.png',
                                            pressed: true,
                                            handler: function () {
                                                window.open("/Common/DataSource/FileDownload4MD5.ashx?file_ident=" + ident, "_blank");
                                            }
                                        }
                                    ]
                                };

                            } else if (record.data['status'] == 'N') {
                                return {
                                    xtype: 'toolbar',
                                    padding: '0 0 0 0',
                                    border: false,
                                    items: [
                                        {
                                            text: UploadFinish,
                                            xtype: 'button',
                                            icon: '/Common/DMZ/Images/16x16/accept.png',
                                            overCls: "",
                                            pressedCls: ""
                                        }
                                    ]
                                };
                            }

                            if (Ext.isDefined(value)) {
                                //                        setTimeout(function () {
                                //                            // This works because calling set() causes a re-render 
                                //                            record.set('downloading', value + 5);
                                //                        }, 500);

                                return {
                                    animate: false,
                                    value: value / 100,
                                    xtype: 'progressbar'
                                };
                            }
                        }
                    },
                    { header: 'md5', dataIndex: 'md5', hideable: false, sortable: false, hidden: true }
                ]
//            ,
//            listeners: {
//                headerclick: function (ct, column, e, t) {
//                    if (column.id == me.id + 'DLALL') {
//                        window.open("/Common/DataSource/FileDownload4MD5.ashx?file_ident=*&obj_ident=" + me.getDocId() + "&uploader_id=upload-1", "_blank");
//                    }
//                }
//            }
        };

        me.callParent(arguments);
    },

    afterRender: function () {
        this.callParent(arguments);

        var me = this;
        var t = this.title;
        this.store.on({
            add: function (s) {
                var c = s.getCount();
                if (c > 0)
                    me.setTitle(t + "(" + s.getCount() + ")");
                else
                    me.setTitle(t);
            },
            refresh: function (s) {
                var c = s.getCount();
                if (c > 0)
                    me.setTitle(t + "(" + s.getCount() + ")");
                else
                    me.setTitle(t);
            },
            clear: function (s) {
                me.setTitle(t);
            }
        });
    },

    reset: function (docId) {
        if (docId)
            this.docId = docId;
        else
            this.docId = "";

        this.store.removeAll();
    },

    getDocId: function () {
        return this.docId;
    }
});
