Ext.define("App.view.MaterialBandWindow", {
    extend: "Ext.window.Window",
    alias: "widget.materialBandWindow",
    xtype: "materialBandWindow",
    title: App.localeRes("Band Details"),
    width: 800,
    height: 280,
    modal: true,

    resizable: true,
    layout: "fit",
    constrainHeader: true,

    isDeleted:false,

    onSave: function(){
        var me = this,
        f = me.down('form');

        if (f.isValid()) {
            f.submit({
                url: App.url("/common/material/band/save"),
                method: 'POST',
                submitEmptyText: false,
                success: function (form, action) {
                    App.showMsg('Saved');
                    me.savedId = action.result.id;
                    me.close();
                }
            });
        }
    },

    onDelete: function(){
        var me = this,
        f = me.down('form');

        if(!f.getValues().id) return;

        App.confirm('Confirm Delete', 'Confirm Delete', function(buttonId, text, opt) {
            if (buttonId === 'yes') {
                if (App.isGranted(['PRICE_LIST_MAINTAIN']) == true) {
                    Ext.Ajax.request({
                        url: App.url('/common/material/band/delete'),
                        params: { id: f.getValues().id },
                        success: function(response, opts) {
                            App.showMsg('Record Deleted');
                            me.isDeleted = true;
                            me.close();
                        },
                        failure: function(response, opts) {
                            App.showError('Cannot Delete : ' + response.status);
                        },
                        scope: this
                    });
                } else {
                    App.showError(
                        'You Have No Authority To Process This Action!',
                        'Authority Issue'
                    );
                }
            }
        });

    },

    doLoad: function(){
        let me = this;
        me.down('form').load({
            url: App.url("/common/material/band/load"),
            method: "POST",
            params: {
                id: me.params.id
            },
            success: function(form, action) {
                if(App.isGranted(['PRICE_LIST_MAINTAIN'])){
                    me.down("#deleteBtn").setHidden(false);
                }
            }
        });
    },

    initComponent: function () {
        var me = this;
        Ext.apply(me, {
            items: [
                {
                    xtype: "form",
                    padding: '16 16 0 16',
                    height: '100%',
                    flex: 1,
                    params: {},
                    callbackOnSave: function(){
                        me.close();
                    },
                    bbar: {
                        defaultButtonUI: 'default',
                        layout: 'hbox',
                        padding: 0,
                        items: [
                            {
                                xtype: 'button',
                                text: App.localeRes('Delete'),
                                itemId: 'deleteBtn',
                                ui: "soft-red",
                                margin: '0 0 16 0',
                                hidden: true,
                                handler: function(button, event){
                                    me.onDelete();
                                }
                            },
                            '->',
                            {
                                xtype: 'button',
                                text: App.localeRes('Save & Close'),
                                ui: "blue",
                                margin: '0 0 16 0',
                                formBind: true,
                                handler: function(button, event){
                                    me.onSave();
                                }
                            }
                        ]
                    },
                    defaults:{
                        width: '100%',
                    },
                    items:[
                        {
                            xtype: 'hidden',
                            itemId: 'bandId',
                            name: 'id',
                        },
                        {
                            xtype: 'hidden',
                            name: 'fileId',
                        },
                        {
                            xtype: 'textfield',
                            name: 'name',
                            fieldLabel: App.localeRes("Name"),
                        },
                        {
                            xtype: 'label',
                            hidden: !App.isGranted(["VIEW_EXPECTED_PRICE"]),
                            html: "<dl style='color:red'><dt>**"+App.localeRes("Formula Tips")+" :</dt>"
                                +"<dd>"+App.localeRes("Valid Input")+" : 0123456789.+-*/()M</dd>"
                                +"<dd>M = "+App.localeRes("Material Cost")+"</dd>"
                                +"</dl>",
                        },
                        {
                            xtype: 'textfield',
                            hidden: !App.isGranted(["VIEW_EXPECTED_PRICE"]),
                            name: 'expectedPriceFormula',
                            fieldLabel: App.localeRes("Formula"),
                        },
                    ]
                },
               
            ],
            listeners: {
                show: function () {
                    if(me.params && me.params.id){
                        me.doLoad();
                    }
                },
                close: function (window, opts) {
                    if(me.isDeleted){
                        if(me.callbackOnDelete){
                            me.callbackOnDelete();
                        }
                        return;
                    }
                    if (me.callbackOnClose) {
                        me.callbackOnClose(me.savedId,
                             me.down('form').getValues().name,
                             me.down('form').getValues().expectedPriceFormula,
                             );
                    }
                }
            }
        });
        me.callParent(arguments);
    }
});


Ext.define("App.view.MaterialBandIconWindow", {
    extend: "Ext.window.Window",
    alias: "widget.materialBandIconWindow",
    xtype: "materialBandIconWindow",
    title: App.localeRes("Icon"),
    width: 500,
    height: 500,
    modal: true,

    resizable: true,
    layout: "vbox",
    constrainHeader: true,

    uploadFile: function() {
        let me = this;
        if (me.down("filefield").getValue() == "") return;
        me.down('form').submit({
            method: "POST",
            waitMsg: "Uploading...",
            url: App.url("/file/band/icon/ul") + "?bandId="+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("");
            }
        });
    },

    deleteFile: function(){
        let me = this;
        Ext.Ajax.request({
            url: App.url("/common/material/band/icon/delete"),
            params: { 
                id: me.params.id
            },
            success: function(response, opts) {
                me.down('#photoList').loadPanel();
            },
            failure: function(response, opts) {
                App.showError('Message : ' + response.status);
            },
            scope: this
        });
    },

    initComponent: function () {
        var me = this;
        Ext.apply(me, {
            items: [
                {
                    xtype: "form",
                    padding: '16 16 0 16',
                    height: 100,
                    width: '100%',
                    defaults:{
                        width: '100%',
                    },
                    items:[
                        {
                            xtype: 'filefield',
                            name: 'multipartFile',
                            accept: 'image/*',
                            allowBlank: false,
                            fieldLabel: App.localeRes("Upload"),
                        },
                    ],
                    bbar: {
                        defaultButtonUI: 'default',
                        layout: 'hbox',
                        padding: 0,
                        items: [
                            '->',
                            {
                                xtype: 'button',
                                text: App.localeRes('Upload'),
                                ui: "blue",
                                margin: '0 0 16 0',
                                formBind: true,
                                handler: function(button, event){
                                    me.uploadFile();
                                }
                            }
                        ]
                    },
                },
                {
                    layout: 'hbox',
                    width: '100%',
                    items:[
                        {
                            xtype: "container",
                            flex: 1,
                        },
                        {
                            xtype: 'button',
                            text: App.localeRes('Delete'),
                            ui: "soft-red",
                            buttonAlign: 'right',
                            margin: '0 16 0 0',
                            handler: function(button, event){
                                me.deleteFile();
                            }
                        },
                    ]
                },
                {
                    xtype: "container",
                    itemId: "photoList",
                    width: '100%',
                    layout: 'fit',
                    flex:1,
                    items: [],
                    loadPanel: function() {
                        var container = this;
                        if(!me.params.id) return;
                        Ext.Ajax.request({
                            url: App.url("/common/material/band/icon"),
                            params: { 
                                bandId: me.params.id
                            },
                            success: function(response, opts) {
                                var result = Ext.decode(response.responseText);
                                if(result.records == null) return;
                                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,
                                       checkboxHidden: true,
                                       labelHidden: true,
                                       fileId: item.id,
                                       skey: item.skey,
                                   });
                                });
                            },
                            failure: function(response, opts) {
                                App.showError('Message : ' + response.status);
                            },
                            scope: this
                        });
                    }
                }
            ],
            listeners: {
                show: function () {
                    if(me.params && me.params.id){
                        me.down('#photoList').loadPanel();
                    }
                },
                close: function (window, opts) {
                    if (me.callbackOnClose) {
                        me.callbackOnClose();
                    }
                }
            }
        });
        me.callParent(arguments);
    }
});


