Ext.define('App.view.MaterialContainer', {
    extend: 'Ext.container.Container',
    alias: 'widget.materialContainer',
    xtype: 'materialContainer',

    layout: 'hbox',

    defaults: {
        height: '100%',
        margin: '2 4 2 4'
    },
    doLoad: function() {
        var grid = this.down("#bandGrid");
        var store = grid.getStore();
        store.load();
        grid.reconfigure(store);
    },
    clearItemGrid: function(){
        this.down("#itemAddBtn").setDisabled(true);
        this.down("#titleLabel").setItemTitle("");
        this.down("#itemGrid").getStore().removeAll();
    },
    doLoadItems2: function() {
        var grid = this.down("#itemGrid");
        var store = grid.getStore();
        this.down("#itemAddBtn").setDisabled(false);
        store.load({
            callback: function(){
                grid.reconfigure(store);
            }
        });
        //this.down("#itemGrid").reconfigure(this.down("#itemGrid").getStore());
    },
    doReloaditems: function(resetOrderIdx) {
        this.down("#itemGrid").getStore().reload({
            callback: function(){
                if(!resetOrderIdx) return;
                doResetOrderIdx();
            }
        });
    },
    doResetOrderIdx: function(){
        var me = this;
        var store = me.down("#itemGrid").getStore();
        var id_orderIdx = [];
        
        var i=0;
        store.each(function(record,id){
            id_orderIdx.push({"id":record.get("id"), "orderIdx":i});
            i++;
        });

        Ext.Ajax.request({
            url: App.url('/common/material/item/set-orderIdx'),
            params: { "id_orderIdx": Ext.JSON.encode(id_orderIdx)},
            success: function(response, opts) {
                me.doReloaditems();
            },
            failure: function(response, opts) {
                App.showError('Action Fail : ' + response.status);
            },
        });
    },
    doLoadItems: function(){
        let g = this.down("#itemGrid");
        this.down("#itemAddBtn").setDisabled(false);
        Ext.apply(g.getStore().getProxy().extraParams, {
            bandId: g.bandId
        });
        g.getStore().loadPage(1, {
            params: { start: 0 },
            callback: function (records, operation, success) {}
        });
        g.reconfigure(g.getStore());
        g.getView().findFeature("grouping").collapseAll();
    },
    evil: function(fn) {
        return new Function('return ' + fn)();
    },
    params: {},
    initComponent: function() {
        var me = this;
        me.items=[
            {
                xtype: 'grid',
                itemId: 'bandGrid',
                buttonAlign: 'left',
                store:Ext.create('App.store.MaterialBandStore', {}),
                //flex: 1,
                width: 250,
                listeners:{
                    rowclick: function(grid, record, tr, rowIndex, e, eOpts){
                        me.down("#itemGrid").bandId = record.get("id");
                        me.down("#itemGrid").formula = record.get("expectedPriceFormula");
                        me.doLoadItems();
                        me.down("#titleLabel").setItemTitle(record.get("name"));
                        //me.down("#itemGrid").getView().features[0].collapseAll();
                        me.down("#itemGrid").getView().features[0].startCollapsed = true;
                        me.down("#showGroupCheckbox").doUpdateGrid();
                        me.down("#showCostCheckbox").doUpdateCostCol();
                    },
                },
                tbar:{
                    xtype: 'panel',
                    layout: 'hbox',
                    items:[
                        {
                            xtype: 'label',
                            flex:1,
                        },
                        {
                            xtype: 'form',
                            hidden: true,
                            padding: '5 5 0 0',
                            margin: 0,
                            items:[{
                                xtype: 'filefield',
                                buttonText: 'Import',
                                ui: 'default-toolbar',
                                name: 'multipartFile',
                                buttonOnly: true,
                                listeners: {
                                    change: function(field, value, eOpts){
                                        field.up('form').uploadFile();
                                    }
                                }
                            }],
                            uploadFile: function(){
                                var form = this;
                                form.submit({
                                    waitMsg: 'Importing...',
                                    url: App.url('/common/material/item/import')+"?_csrf=" + App.csrf,
                                    success: function(f, action) {
                                        App.showMsg('Imported');
                                    },
                                    failure: function(f, action) {
                                        alert('Import failure');
                                    }
                                });
                            }
                        },
                        {
                            xtype: 'button',
                            iconCls: 'silk-add',
                            hidden: !App.isGranted(['PRICE_LIST_MAINTAIN']),
                            text: App.localeRes("New Band"),
                            handler: function(button){
                                App.loadModuleWin('materialBandWindow', App.localeRes("Band"), {
                                    callbackOnClose: function (bandId, bankName, bandFormula) {
                                        if(!bandId) return;
                                        me.doLoad();
                                        me.down("#itemGrid").bandId = bandId;
                                        me.down("#titleLabel").setItemTitle(bankName);
                                        me.down("#itemGrid").formula = bandFormula;
                                        me.doReloaditems();
                                    }
                                });
                            }
                        }
                    ]
                },
                columns:[
                    /* Band Icon
                    {
                        text: App.localeRes("Band"),
                        flex: 1,
                        dataIndex: 'name',
                        items:[
                            {
                                xtype: 'searchtrigger',
                                anyMatch: true,
                                autoSearch: true,
                                caseSensitive: false,
                            }
                        ],
                        renderer: function(value, metaData, record, row, col, store, grid){
                            if(!App.isGranted(['PRICE_LIST_MAINTAIN'])){
                                if(record.get("fileId")){
                                    return "<img style='vertical-align:middle; object-fit:contain; width:50px; height:50px;' src='"
                                    +App.url("/file/dl/"+record.get("fileId")+"/"+record.get("skey")+"/"+record.get('filename'))+"'/>"
                                    +"&nbsp;&nbsp;&nbsp;"+value;
                                }else{
                                    return '<i style="color:#c9c9c9;" class="fas fa-folder-plus fa-2x"></i>'
                                    +"&nbsp;&nbsp;&nbsp;"+value;
                                }
                            }
                            if(record.get("fileId")){
                                return App.setClickableIcon(
                                    Ext.id(), 
                                    record.get('id'),
                                    "<img style='vertical-align:middle; object-fit:contain; width:50px; height:50px;' src='"
                                    +App.url("/file/dl/"+record.get("fileId")+"/"+record.get("skey")+"/"+record.get('filename'))+"'/>",
                                    value,
                                    function(){
                                        me.doLoad();
                                    });
                            }else{
                                return App.setClickableIcon(
                                    Ext.id(), 
                                    record.get('id'),
                                    '<i style="color:#c9c9c9;" class="fas fa-folder-plus fa-2x"></i>',
                                    value,
                                    function(){
                                        me.doLoad();
                                    });
                            }
                        }
                    },
                    */
                    {
                        text: App.localeRes("Band"),
                        flex: 1,
                        dataIndex: 'name',
                        items:[
                            {
                                xtype: 'searchtrigger',
                                anyMatch: true,
                                autoSearch: true,
                                caseSensitive: false,
                            }
                        ],
                    },
                    {
                        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('materialBandWindow', App.localeRes("Band"), {
                                        params:{
                                            id: record.get("id"),
                                        },
                                        callbackOnClose: function (bandId, bandName, bandFormula) {
                                            me.doLoad();
                                            if(!bandId) return;
                                            if(bandId == me.down("#itemGrid").bandId){
                                                me.down("#itemAddBtn").setDisabled(false);
                                                me.down("#itemGrid").bandId = bandId;
                                                me.down("#itemGrid").formula = bandFormula;
                                                me.doLoadItems();
                                                me.down("#titleLabel").setItemTitle(bandName);
                                            }
                                        },
                                        callbackOnDelete: function(){
                                            me.doLoad();
                                            me.clearItemGrid();
                                        }
                                    });
                                },
                            }
                        ]
                    }
                ]
            },
            {
                xtype: 'grid',
                itemId: 'itemGrid',
                flex: 3,
                buttonAlign: 'left',
                store: Ext.create('App.store.MaterialItemStore', {}),
                stateful : true,
                viewConfig: {
                    //preserveScrollOnReload: true,
                    plugins: { 
                        ptype: 'gridviewdragdrop',
                        dragText: 'Drag and drop to reorganize',
                        dragZone: {
                            onBeforeDrag: function(data, e) {
                                console.log( e);
                                if (e.position.column.dataIndex == 'drag') {
                                    // can be dragged
                                } else {
                                   // cannot be dragged
                                    return false;
                                }
                            }
                        }
                    },
                    listeners:{
                        
                        beforeDrop: function(node, data, overModel, dropPosition, eOpts){
                            
                            var store = me.down("#itemGrid").getStore();
                            var id_orderIdx = [];
                            var dragItem = store.indexOf(data.records[0].data);
                            var dropPosition = store.indexOf(overModel.data);
                            if(dragItem>dropPosition){
                                var position = dragItem;
                                for(position; position > dropPosition; position--){
                                    var record = store.getAt(position-1);
                                    id_orderIdx.push({"id":record.get("id"), "orderIdx":position});
                                }
                                var record = store.getAt(dragItem);
                                id_orderIdx.push({"id":record.get("id"), "orderIdx":dropPosition});
                            }else{
                                var position = dragItem; 
                                for(position; position < dropPosition; position++){
                                    var record = store.getAt(position+1);
                                    id_orderIdx.push({"id":record.get("id"), "orderIdx":position});
                                }
                                var record = store.getAt(dragItem);
                                id_orderIdx.push({"id":record.get("id"), "orderIdx":dropPosition});
                            }

                            Ext.Ajax.request({
                                url: App.url('/common/material/item/set-orderIdx'),
                                params: { "id_orderIdx": Ext.JSON.encode(id_orderIdx)},
                                success: function(response, opts) {
                                    me.doReloaditems();
                                },
                                failure: function(response, opts) {
                                    App.showError('Action Fail : ' + response.status);
                                },
                            });
                        },
                        
                       //TODO remove
                       /*
                        drop: function(){
                            var store = me.down("#itemGrid").getStore();
                            var id_orderIdx = [];
                            
                            var i=0;
                            store.each(function(record,id){
                                id_orderIdx.push({"id":record.get("id"), "orderIdx":i});
                                i++;
                            });
                            Ext.Ajax.request({
                                url: App.url('/common/material/item/set-orderIdx'),
                                params: { "id_orderIdx": Ext.JSON.encode(id_orderIdx)},
                                success: function(response, opts) {
                                    me.doReloaditems();
                                },
                                failure: function(response, opts) {
                                    App.showError('Action Fail : ' + response.status);
                                },
                            });
                        }
                        */
                    }
                },
                features: [
                    {
                        ftype:'grouping',
                        //hideGroupedHeader: true,
                        enableNoGroups: true,
                        enableGroupingMenu: true,
                        groupHeaderTpl: '{name}',
                        /*c             cc
                        groupers: [{
                            property: 'asset',
                            groupFn: function (val) {
                                return val.data.name;
                            }
                        }]
                        */
                    }
                ],
                tbar:{
                    xtype: 'panel',
                    layout: 'hbox',
                    items:[
                        {
                            xtype: 'label',
                            itemId: 'titleLabel',
                            html: '<b>&nbsp;</b>',
                            margin: "16 16 4 28",
                            flex: 1,
                            setItemTitle: function(title){
                                this.setHtml("<b>"+title+"</b>");
                            }
                        },
                        {
                            xtype: 'checkbox',
                            itemId: 'showGroupCheckbox',
                            boxLabel: App.localeRes("Show in group"),
                            boxLabelAlign: 'after',
                            value: App.getUserSetting("USER_materialItemGroup")=="T",
                            listeners:{
                                change: function(field, newValue, oldValue){
                                    App.setUserSetting({"name":"USER_materialItemGroup", "value":newValue?"T":"F"});
                                    field.doUpdateGrid();
                                },
                            },
                            doUpdateGrid: function(){
                                if(App.getUserSetting("USER_materialItemGroup")=="T"){
                                    me.down("#itemGrid").getStore().group("name");
                                    me.down("#drag").setVisible(false);
                                    me.down("#itemGrid").getView().features[0].collapseAll();
                                    me.down("#itemGrid").getView().features[0].startCollapsed = true;
                                }else{
                                    me.down("#itemGrid").getStore().group(null);
                                    me.down("#drag").setVisible(true);
                                } 
                            }
                        },
                        {
                            xtype: 'label',
                            width: 50
                        },  
                        {
                            xtype: 'checkbox',
                            itemId: 'showCostCheckbox',
                            boxLabel: App.localeRes("Show Cost"),
                            boxLabelAlign: 'after',
                            value: App.getUserSetting("USER_showMaterialItemCost")=="T",
                            listeners:{
                                change: function(field, newValue, oldValue){
                                    App.setUserSetting({"name":"USER_showMaterialItemCost", "value":newValue?"T":"F"});
                                    field.doUpdateCostCol();
                                }
                            },
                            doUpdateCostCol: function(){
                                var costColumn = me.down("#costColumn");
                                if(App.getUserSetting("USER_showMaterialItemCost")=="T"){
                                    costColumn.show();
                                }else{
                                    costColumn.hide();
                                }
                            }
                        },
                        {
                            xtype: 'label',
                            width: 50
                        },  
                        {
                            xtype: 'button',
                            itemId: 'itemAddBtn',
                            iconCls: 'silk-add',
                            disabled: true,
                            hidden: !App.isGranted(['PRICE_LIST_MAINTAIN']),
                            text: App.localeRes("New Band Item"),
                            handler: function(button, event){
                                App.loadModuleWin('materialItemWindow', App.localeRes("Item"), {
                                    params:{
                                        bandId: button.up("#itemGrid").bandId,
                                        formula: me.down("#itemGrid").formula,
                                        orderIdx: me.down("#itemGrid").getStore().data.length,
                                    },
                                    callbackOnClose: function () {
                                        me.down("#itemGrid").getStore().reload();
                                        me.down("#itemGrid").reconfigure(me.down("#itemGrid").getStore());
                                    }
                                });
                            }
                        }
                    ]
                },
                columns:[
                    {
                        xtype: 'rownumberer',
                        width: 60,
                    },
                    {
                        text: App.localeRes(''),
                        dataIndex: 'drag',
                        width: 30,
                        itemId: 'drag',
                        hidden: App.getUserSetting("USER_materialItemGroup")!="T",
                        /*
                        renderer: function(value, metaData, record, row, col, store, grid){
                            return "<font color='#AAA'>≡</font>"
                        }
                        */
                    },
                    {
                        text: App.localeRes('Name'),
                        dataIndex: 'name',
                        hidden: true,
                        sortable: false,
                        renderer: function(value, metaData, record, row, col, store, grid){
                            return "<b>"+value+"</b>"
                        }
                    },
                    {
                        text: App.localeRes('Bunch'),
                        dataIndex: 'forSearch',
                        minWidth: 250,
                        flex:1,
                        sortable: false,
                        field:{
                            xtype: 'textfield'
                        },
                        items:[
                            {
                                xtype: 'searchtrigger',
                                anyMatch: true,
                                autoSearch: true,
                                caseSensitive: false,
                            }
                        ],
                        renderer: function(value, metaData, record, row, col, store, grid){
                            if(!App.isGranted(['PRICE_LIST_MAINTAIN'])) return record.get("name");
                            var bunch = record.get('bunch');
                            if(bunch)
                                bunch=" - <font color='#c7a9ba'><i>"+bunch+"</font></i>";
                            else
                                bunch = '';

                            var fabricNum = record.get('fabricNum');
                            if(fabricNum)
                                fabricNum="  <font color='#89bcd6'>("+fabricNum+")</font> ";
                            else
                                fabricNum = '';

                            if (metaData) metaData.tdAttr = 'data-qtip="' 
                            + App.setCustTooltip(
                                record.get("name")
                                , record.get("bunch")
                                , record.get("fabricNum")
                            )+ '"';


                            return App.setClickableMaterial(
                                Ext.id(), 
                                { id: record.get("id"), formula: me.down("#itemGrid").formula, },
                                record.get("name")+bunch+fabricNum,
                                function(isSave){
                                    //me.doLoadItems();
                                    if(!isSave) return;
                                    me.doReloaditems();
                                }
                            );
                        }
                    },
                    /*
                    {
                        text: App.localeRes("Bunch"),
                        dataIndex: 'bunch',
                        field:{
                            xtype: 'textfield'
                        }
                    },
                    */
                    {
                        text: App.localeRes("Cost"),
                        itemId: 'costColumn',
                        dataIndex: 'cost',
                        hidden: true,
                        sortable: false,
                        field:{
                            xtype: 'textfield'
                        },
                        align: 'right',
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            if(!value) return;
                            return '$' + Ext.util.Format.number(value, '0,000.00');
                        }
                    },
                    /*
                    {
                        text: App.localeRes("Price"),
                        width: 200,
                        dataIndex: 'suitPrice',
                        field:{
                            xtype: 'textfield'
                        },
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            var suit = record.get("suitPrice")? "$"+Ext.util.Format.number(record.get("suitPrice"), '0,000.00'):"-";
                            var jacket = record.get("jacketPrice")? "$"+Ext.util.Format.number(record.get("jacketPrice"), '0,000.00'):"-";
                            var overcoat = record.get("overcoatPrice")? "$"+Ext.util.Format.number(record.get("overcoatPrice"), '0,000.00'):"-";
                            var pants = record.get("pantsPrice")? "$"+Ext.util.Format.number(record.get("pantsPrice"), '0,000.00'):"-";
                            var other = record.get("otherPrice")? "$"+Ext.util.Format.number(record.get("otherPrice"), '0,000.00'):"-";
                            
                            var htmlStr = '<table width="100%">';
                            htmlStr += '<tr><td>'+App.localeRes("Suit")+': </td><td style="text-align:right">' + suit + '</td></tr>';
                            htmlStr += '<tr><td>'+App.localeRes("Jacket")+': </td><td style="text-align:right">' + jacket + '</td></tr>';
                            htmlStr += '<tr><td>'+App.localeRes("Overcoat")+': </td><td style="text-align:right">' + overcoat + '</td></tr>';
                            htmlStr += '<tr><td>'+App.localeRes("Pants")+': </td><td style="text-align:right">' + pants + '</td></tr>';
                            htmlStr += '<tr><td>'+App.localeRes("Other")+': </td><td style="text-align:right">' + other + '</td></tr>';
                            htmlStr += '</table>';

                            return htmlStr;
                        }
                    },
                    */
                    
                    {
                        text: App.localeRes("Suit"),
                        dataIndex: 'suitPrice',
                        field:{
                            xtype: 'textfield'
                        },
                        sortable: false,
                        align: 'right',
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            if(!value) return;
                            return '$' + Ext.util.Format.number(value, '0,000.00');
                        }
                    },
                    {
                        text: App.localeRes("Jacket"),
                        dataIndex: 'jacketPrice',
                        field:{
                            xtype: 'textfield'
                        },
                        sortable: false,
                        align: 'right',
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            if(!value) return;
                            return '$' + Ext.util.Format.number(value, '0,000.00');
                        }
                    },
                    {
                        text: App.localeRes("Pants"),
                        dataIndex: 'pantsPrice',
                        field:{
                            xtype: 'textfield'
                        },
                        sortable: false,
                        align: 'right',
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            if(!value) return;
                            return '$' + Ext.util.Format.number(value, '0,000.00');
                        }
                    },
                    {
                        text: App.localeRes("Overcoat"),
                        dataIndex: 'overcoatPrice',
                        field:{
                            xtype: 'textfield'
                        },
                        sortable: false,
                        align: 'right',
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            if(!value) return;
                            return '$' + Ext.util.Format.number(value, '0,000.00');
                        }
                    },
                    {
                        text: App.localeRes("Other"),
                        dataIndex: 'otherPrice',
                        field:{
                            xtype: 'textfield'
                        },
                        sortable: false,
                        align: 'right',
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            if(!value) return;
                            return '$' + Ext.util.Format.number(value, '0,000.00');
                        }
                    },
                    
                    {
                        text: App.localeRes("Expected"),
                        dataIndex: 'cost',
                        align: 'right',
                        sortable: false,
                        hidden: true||!App.isGranted(["VIEW_EXPECTED_PRICE"]),
                        renderer: function(value, metaData, record, row, col, store, grid){
                            if(me.down("#itemGrid").formula){
                                let formula = me.down("#itemGrid").formula;
                                formula = formula.replace("M", value);
                                let v= me.evil(formula);
                                return '$' + Ext.util.Format.number(v, '0,000.00'); 
                            }
                            return "";
                        }
                    },
                    {
                        xtype: 'actioncolumn',
                        text: '',
                        width: 30,
                        align: 'center',
                        hidden: !App.isGranted(['PRICE_LIST_MAINTAIN']),
                        items: [
                            {
                                iconCls: 'silk-cross',
                                tooltip: App.localeRes('Delete'),
                                handler: function(view, rowIndex, colIndex, item, e, record) {
                                 
                                    if (App.isGranted(['PRICE_LIST_MAINTAIN']) == true) {
                                        Ext.Ajax.request({
                                            url: App.url('/common/material/item/delete'),
                                            params: { id: record.get('id') },
                                            success: function(response, opts) {
                                                //me.doLoadItems2();
                                                me.doReloaditems(true);
                                            },
                                            failure: function(response, opts) {
                                                App.showError('Cannot Delete : ' + response.status);
                                            },
                                        });
                                    } else {
                                        App.showError(
                                            'You Have No Authority To Process This Action!',
                                            'Authority Issue'
                                        );
                                    }

                                },
                            }
                        ]
                    }
                ]
            }
        ];
        me.callParent(arguments);
        me.doLoad();
    }
});


Ext.define('Fiddle.view.SearchTrigger', {
    extend: 'Ext.form.field.Text',
    alias: 'widget.searchtrigger',

    requires: [
         'Ext.form.trigger.Trigger'
    ],

    defaultListenerScope: true,

    triggers: {
        search: {
            handler: function (field, trigger, e) {
                this.setFilter(this.up().dataIndex, this.getValue());
            },
            cls: 'x-form-search-trigger'
        },
        clear: {
            handler: function (field, trigger, e) {
                this.setValue('');
                if (!this.autoSearch) this.setFilter(this.up().dataIndex, '');
            },
            cls: 'x-form-clear-trigger'
        }
    },
    listeners: {
        render: 'onTextfieldRender',
        change: 'onTextfieldChange'
    },

    onTextfieldRender: function (component, eOpts) {
        var me = this;
        me.ownerCt.on('resize', function () {
            me.setWidth(this.getEl().getWidth());
        });
    },

    onTextfieldChange: function (field, newValue, oldValue, eOpts) {
        if (this.autoSearch) this.setFilter(this.up().dataIndex, this.getValue());
    },

    setFilter: function (filterId, value) {
        var store = this.up('grid').getStore();
        if (value) {
            store.removeFilter(filterId, false);
            var filter = {
                id: filterId,
                property: filterId,
                value: value
            };
            if (this.anyMatch) filter.anyMatch = this.anyMatch;
            if (this.caseSensitive) filter.caseSensitive = this.caseSensitive;
            if (this.exactMatch) filter.exactMatch = this.exactMatch;
            if (this.operator) filter.operator = this.operator;
            console.log(this.anyMatch, filter);
            store.addFilter(filter);
        } else {
            store.filters.removeAtKey(filterId);
            store.reload();
        }
    }

});
