Ext.define("App.view.SystemGroupContainer", {
    extend: "Ext.container.Container",
    xtype: "systemGroupContainer",
    alias: "widget.systemGroupContainer",
    layout: "vbox",
    defaults: {
        width: '100%',
        margin: '2 4 0 4'
    },

    doSearch: function() {
        var f = this.down('#searchCriteriaForm').getForm(),
            g = this.down('grid');

        Ext.apply(g.getStore().getProxy().extraParams, f.getValues());

        g.getStore().loadPage(1, {
            params: { start: 0 },
            callback: function(records, operation, success) {}
        });
        g.needReload = true;
        g.reconfigure(g.getStore());
    },

    initComponent: function() {
        var me = this;
        me.items = [
           {
                xtype: 'form',
                itemId: 'searchCriteriaForm',
                bodyPadding: "15 15 0 15",
                buttonAlign: 'left',
                defaults: {
                    selectOnFocus: true,
                    margin: '0 4 0 4',
                },
               items: [
                    {
                        
                        xtype: 'fieldcontainer',
                        margin: '0 4 0 4',
                        layout: {
                            type: 'table',
                            columns: 3
                        },
                        defaults: {
                            width: '95%',
                            margin: {
                                bottom: 4,
                            },
                            listeners: {
                                specialkey: function(field, e) {
                                    if (e.getKey() == e.ENTER) me.doSearch();
                                }
                            }
                        },
                        items:[
                            {
                                xtype: 'textfield',
                                fieldLabel: App.localeRes('Name'),
                                name: 'name',
                            },
                        ]
                    }
               ],
               buttons:[
                    {
                        xtype: 'button',
                        text: App.localeRes('New'),
                        ui: 'default',
                        itemId: 'newBtn',
                        iconCls: 'silk-add',
                        handler: function(button, event) {
                            App.loadModuleWin('systemGroupWindow', App.localeRes('System Group'), {
                                params: { record: null },
                                callbackOnClose: function() {
                                    me.down("grid").reloadStore();
                                }
                            });
                        }
                    },
                    '->',
                    {
                        text: App.localeRes('Search'),
                        iconCls: 'silk-magnifier',
                        handler: function(button, event) {
                            me.doSearch();
                        }
                    },
                    {
                        text: App.localeRes('Reset'),
                        handler: function(button, event) {
                            me.down('#searchCriteriaForm')
                                .getForm()
                                .reset();
                        }
                    },
                ]
           },
           {
                xtype: 'grid',
                width: '100%',
                flex: 1,
                store: Ext.create('App.store.SysGroupStore', {}),
                reloadStore: function(){
                    var grid = this;
                    grid.getStore().reload();
                    grid.reconfigure(grid.getStore());
                },
                columns: [
                    {
                        xtype: 'rownumberer'
                    },
                    {
                        xtype: 'actioncolumn',
                        text: '',
                        width: 30,
                        align: 'center',
                        //hidden: !App.isGranted(['PRICE_LIST_MAINTAIN']),
                        items: [
                            {
                                iconCls: 'icon-edit',
                                tooltip: App.localeRes('Edit'),
                                handler: function(view, rowIndex, colIndex, item, e, record) {
                                    App.loadModuleWin('systemGroupWindow', App.localeRes("System Group"), {
                                        params:{
                                            id: record.get("id"),
                                        },
                                        callbackOnClose: function () {
                                            me.down("grid").reloadStore();
                                        }
                                    });
                                },
                            }
                        ]
                    },
                    {
                        text: App.localeRes('Name'),
                        dataIndex: 'name',
                        width: 250,
                        renderer: function(value, metaData, record, row, col, store, grid){
                            return value;
                        }
                    },
                    {
                        text: App.localeRes('Description'),
                        dataIndex: 'description',
                        flex: 1,
                    },
                    {
                        text: App.localeRes('User Count'),
                        dataIndex: 'userCount',
                        renderer: function(value, metaData, record, row, col, store, grid){
                            var extId = Ext.id();
                            //TODO: AUTH
                            //if(!App.isGranted(App.getPanelAuths('customerContainer'))) return viewText;
                            setTimeout(function () {
                                if (Ext.fly(extId)) {
                                    Ext.EventManager.addListener(
                                        extId, 'click',
                                        function () {
                                            App.loadModuleWin('systemGroupWindow_ViewUser', App.localeRes('View User'), {
                                                params: { id: record.get("id") },
                                                callbackOnClose: function() {
                                                    if(callback) callback();
                                                }
                                            });
                                        }
                                    );
                                }
                            }, 200);
                            return Ext.String.format('<b><a href="javascript:void(0);" id="{0}">{1}</a></b>', extId, value);
                        }
                    }
                ]
           },
        ];
        me.callParent(arguments);
    }
});


Ext.define("App.view.SystemGroupWindow", {
    extend: "Ext.window.Window",
    alias: "widget.systemGroupWindow",
    xtype: "systemGroupWindow",
    title: App.localeRes("System Group"),
    modal: true,
    resizable: true,
    layout: "fit",
    constrainHeader: true,

    loadWindow: function (id) {
        var me = this;
        me.down("form").load({
            url: App.url("/user/sys-group/load"),
            method: 'POST',
            params:{
                id: id
            },
            success: function(form, action) {
                var formData = form.getValues();
                if(!formData.id) return;
           
                var filefield = me.down("filefield");
                var removeBtn = me.down("#removeBtn");
                
                filefield.setDisabled(false);
                removeBtn.setDisabled(false);

            }
        });
    },
    doSave: function(){
        var me = this;
        var f = me.down("form");

        if (f.isValid()) {
            f.submit({
                url: App.url("/user/sys-group/save")+ "?_csrf=" + App.csrf,
                method: 'POST',
                submitEmptyText: false,
                success: function (form, action) {
                    App.showMsg('Saved');
                    me.loadWindow(action.result.id);
                    //me.close();
                }
            });
        }
    },
    uploadFile: function() {
        var me = this;
        if (me.down("filefield").getValue() == "") return;
        me.getForm().submit({
            method: "POST",
            waitMsg: "Uploading...",
            url: App.url("/file/measurement-sheet/ul") + "?orderId="+me.params.id+"&_csrf=" + App.csrf,
            success: function(f, action) {
                App.showMsg("Uploaded");
                me.down("filefield").setValue("");
                me.down('#photoList').loadPanel();
            },
            failure: function(f, action) {
                alert("Uploaded failure");
                me.down("filefield").setValue("");
            }
        });
        console.log(App.url("/file/measurement-sheet/ul") + "?orderId="+me.params.id+"&_csrf=" + App.csrf)
    },
    initComponent: function () {
        var me = this;
        Ext.apply(me, {
            items: [
                {
                    xtype: "form",
                    padding: '16 16 0 16',
                    params: {},
                    defaults: {
                        width: 800
                    },
                    items:[
                        {
                            xtype: 'hidden',
                            name: 'id',
                        },
                        {
                            xtype: 'textfield',
                            name: 'name',
                            fieldLabel: App.localeRes("Name"),
                        },
                        {
                            xtype: 'textfield',
                            name: 'companyName',
                            fieldLabel: App.localeRes("Company Name"),
                        },
                        {
                            xtype: 'textfield',
                            name: 'phone',
                            fieldLabel: App.localeRes("Phone"),
                        },
                        {
                            xtype: 'textfield',
                            name: 'fax',
                            fieldLabel: App.localeRes("Fax"),
                        },
                        {
                            xtype: 'textfield',
                            name: 'email',
                            fieldLabel: App.localeRes("Email"),
                        },
                        {
                            xtype: 'textfield',
                            name: 'address',
                            fieldLabel: App.localeRes("Address"),
                        },
                        {
                            xtype: 'textarea',
                            name: 'description',
                            fieldLabel: App.localeRes("Description"),
                        },
                        {
                            xtype: 'label',
                            html: '<b>'+App.localeRes("Icon")+'</b>',
                        },
                        {
                            xtype: 'container',
                            layout: 'hbox',
                            width: '100%',
                            items: [
                                {
                                    xtype: "filefield",
                                    disabled: true,
                                    buttonText: App.localeRes("Upload"),
                                    buttonConfig:{
                                        iconCls: 'fas fa-upload',
                                    },
                                    ui: "soft-blue",
                                    name: "multipartFile",
                                    margin: 4,
                                    buttonOnly: true,
                                    accept: "image/*",
                                    listeners: {
                                        change: function(field, value, eOpts) {
                                            if(me.down('#photoList').items.items.length>0){
                                                field.setValue("");
                                                App.showWarning("Please remove current icon before upload the new one.");
                                                return;
                                            }
                                            me.uploadFile();
                                        }
                                    }
                                },
                                {
                                    xtype: 'container',
                                    flex: 1,
                                },
                                {
                                    xtype: 'button',
                                    itemId: 'removeBtn',
                                    disabled: true,
                                    iconCls: 'fas fa-trash',
                                    ui: 'soft-red',
                                    margin: 4,
                                    text: App.localeRes('Remove'),
                                    handler: function(button, event){
                                        if(!me.params.id) return;
                                        var deleteRecord = [];
                                        me.down('#photoList').items.items
                                            .forEach(function(item, index, array){
                                                if(item.selected){
                                                    deleteRecord.push({
                                                        fileId: item.fileId,
                                                        refId: me.refId,
                                                        refType: me.refType,
                                                        skey: item.skey,
                                                    });
                                                }
                                            });
                                
                                        if(deleteRecord.length<=0) return;
                                
                                        Ext.Ajax.request({
                                            url: App.url("/file/delete"),
                                            params: { 
                                                fileId: deleteRecord.fileId,
                                                refId: deleteRecord.refId,
                                                refType: deleteRecord.refType,
                                                skey: deleteRecord.skey,
                                            },
                                            success: function(response, opts) {
                                                App.showMsg('Removed');
                                                me.down('#photoList').loadPanel();
                                            },
                                            failure: function(response, opts) {
                                                App.showError('Message : ' + response.status);
                                            },
                                            scope: this
                                        });
                                    }
                                },
                            ]
                        },
                        {
                            xtype: "container",
                            itemId: "photoList",
                            items: [],
                            loadPanel: function() {
                                var container = this;
                                if(!me.params.id) return;
                                Ext.Ajax.request({
                                    url: App.url("/user/sys-group/get-icon"),
                                    params: { 
                                        id: me.params.id
                                    },
                                    success: function(response, opts) {
                                        var result = Ext.decode(response.responseText);
                                        container.removeAll(true);
                                        result.records.forEach(function(item, index, array) {
                                            container.add({
                                               xtype: 'imagefield',
                                               name: item.filename,
                                               thumbnailPath: App.url("/file/thumbnail/"+item.id+"/"+item.skey+"/"+item.filename),
                                               path: App.url("/file/dl/"+item.id+"/"+item.skey+"/"+item.filename),
                                               imageWidth: item.imageWidth,
                                               imageHeight: item.imageHeight,
                                               fileId: item.id,
                                               skey: item.skey,
                                           });
                                        });
                                    },
                                    failure: function(response, opts) {
                                        App.showError('Message : ' + response.status);
                                    },
                                    scope: this
                                });
                            }
                        }
                    ],
                    buttons: [
                        {
                            text: App.localeRes("Save"),
                            handler: function(){
                                me.doSave();
                            }
                        }
                    ],
                },
            ],
            listeners: {
                show: function () {
                    if(me.params.id){
                        me.loadWindow(me.params.id);
                    }
                },
                close: function (window, opts) {
                    if (me.callbackOnClose) {
                        me.callbackOnClose();
                    }
                }
            }
        });
        me.callParent(arguments);
    }
});
