Ext.define("App.view.CustomerOrderGrid", {
    extend: "Ext.grid.Panel",
    xtype: "customerOrderGrid",
    params: {},

    loadStore: function(){
        var me = this;
        var store = me.getStore();
        var sumLabel = me.down('#sum');
        var custId = me.params.custId;
        if(!custId)return;
        Ext.apply(store.getProxy().extraParams, {
            custId:custId, 
            //showIgnored: me.down('checkbox').getValue()
        });

        store.loadPage(1, {
            params: { start: 0 },
            callback: function (records, operation, success) {
                var data= Ext.decode(operation._response.responseText);
                var sum = data.totalAmount;
                sumLabel.setHtml('Total: ' + " $"+ Ext.util.Format.number(sum, '0,000.00'));
            }
        });
        me.reconfigure(store);
    },
    setGridParams: function(params){
        this.params=params;
        this.loadStore();
    },

    reloadStore: function() {
        var me = this;
        me.getStore().reload();
        me.reconfigure(me.getStore());
        me.getStore().fireEvent('datachanged', me.getStore());
    },

    initComponent: function () {
        var me = this;
        Ext.apply(me, {
            tbar: {
                defaultButtonUI: 'default',
                padding: 0,
                items: [
                    {
                        xtype: 'button',
                        text: App.localeRes('New Order'),
                        margin: '0 0 16 0',
                        itemId: 'newOrderBtn',
                        handler: function(button, event){
                            App.loadModuleWin('orderWindow', App.localeRes("Order"), {
                                params: {
                                    custId: me.params.custId
                                },
                                callbackOnClose: function () {
                                    me.loadStore();
                                }
                            });
                        }
                    },
                    {
                        xtype: 'label',
                        itemId: 'sum',
                        padding: 10,
                        html:'<b>' + '0' + '</b>'

                    },
                    '->',
                    /*
                    {
                        xtype: 'checkbox',
                        fieldLabel: App.localeRes('Show Ignored'),
                        labelAlign: 'right',
                        labelSeparator: '',
                        value:'0',
                        inputValue: '1',
                        uncheckedValue: '0',
                        handler: function(checkbox, event){
                            me.loadStore(me.params.custId);
                        }
                    },
                    */
                    {
                        xtype: 'button',
                        text: App.localeRes('Stock Out'),
                        ui: 'soft-purple',
                        itemIdviewBtn: 'viewBtn',
                        iconCls: 'fas fa-tasks',
                        margin: '0 5 0 0',
                        handler: function(button, event) {
                            var records = [];
                            me.store.each(function(record) {
                                if (record.get('view')) records.push({
                                    id:record.get('id'),
                                    code:record.get('code'),
                                    type:record.get('type'),
                                    orderNo:record.get('orderNo'),
                                    outDate:record.get('inDate')?null:record.get('outDate'),
                                    outRemark:record.get('inDate')?null:record.get('outRemark'),
                                    inRemark:null,
                                    inDate:null,
                                });
                            });

                            App.loadModuleWin('dateRemarkWindow-2', App.localeRes('Stock Out'), {
                                params: {
                                    records: records,
                                },
                                callbackOnClose: function() {
                                    me.loadStore();
                                }
                            });
                        }
                    },
                    {
                        xtype: 'button',
                        text: App.localeRes('Stock In'),
                        ui: 'soft-purple',
                        itemIdviewBtn: 'viewBtn',
                        iconCls: 'fas fa-tasks',
                        margin: '0 5 0 0',
                        handler: function(button, event) {
                            var records = [];
                            me.store.each(function(record) {
                                if (record.get('view')) records.push({
                                    id:record.get('id'),
                                    code:record.get('code'),
                                    type:record.get('type'),
                                    orderNo:record.get('orderNo'),
                                    outDate:record.get('outDate'),
                                    outRemark:record.get('outRemark'),
                                    inRemark:record.get('inRemark'),
                                    inDate:record.get('inDate'),
                                });
                            });
                            
                            App.loadModuleWin('dateRemarkWindow', App.localeRes('Stock In'), {
                                params: {
                                    records: records,
                                },
                                callbackOnClose: function() {
                                    me.loadStore();
                                }
                            });
                        }
                    },
                    {
                        xtype: 'button',
                        text: App.localeRes('Images'),
                        ui: "soft-purple",
                        itemId: 'viewBtn',
                        iconCls: 'fas fa-tasks',
                        margin: '0 5 0 0',
                        handler: function(button, event){
                            var ids = [];
                            me.store.each(function(record){
                                if(record.get('view'))
                                    ids.push(record.get("id"));
                            });
    
                            if(ids.length == 0) return;

                            App.loadModuleWin('imageGroupWindow', App.localeRes("Image Group"), {
                                params: {
                                    orders:{
                                        refType: 'order',
                                        ids: ids,
                                    },
                                },
                                callbackOnClose: function () {
                                    me.loadStore();
                                }
                            });

                        }
                    },
                    {
                        xtype: 'button',
                        text: "<b>"+App.localeRes('Change Status')+"</b>",
                        itemId: 'changeStatusBtn',
                        width: 85,
                        ui: 'green',
                        margin: '0 5 0 0',
                        handler: function(button, event) {
                            var ids = [];
                            var havePayment = false;
                            var str = '';
                            me.store.each(function(record) {
                                if (record.get('changeStatus')) {
                                    ids.push(record.get('id'));
                                    if (record.get('havePayment')) {
                                        str = str == '' ? record.get('orderNo') : str + ', ' + record.get('orderNo');
                                        havePayment = true;
                                    }
                                }
                            });

                            if (ids.length == 0) return;
                            //call change Status Window
                            App.loadModuleWin('orderChangeStatusWindow', App.localeRes('Change Status'), {
                                params: {
                                    ids: ids,
                                    havePayment: havePayment,
                                    havePaymentOrderStr:str
                                },
                                callbackOnClose: function() {
                                    me.loadStore();
                                    me.selModel.deselectAll();
                                }
                            });
                        }
                    },
                    /*
                    {
                        xtype: 'button',
                        text: App.localeRes('Complete'),
                        ui: "soft-green",
                        itemId: 'completeBtn',
                        width: 95,
                        margin: '0 5 0 0',
                        handler: function(button, event){
                            var ids = [];
                            me.store.each(function(record){
                                if(record.get('complete'))
                                    ids.push(record.get("id"));
                            });
    
                            if(ids.length == 0) return;
    
                            Ext.Ajax.request({
                                url: App.url("/order/list/complete"),
                                params: { ids: ids },
                                success: function(response, opts) {
                                    App.showMsg("Record Completed");
                                    me.loadStore(me.params.custId);
                                },
                                failure: function(response, opts) {
                                    App.showError('Cannot Complete : ' + response.status);
                                },
                                scope: this
                            });
                        }
                    },
                    {
                        xtype: 'button',
                        text: App.localeRes('Cancel'),
                        ui: "soft-red",
                        itemId: 'cancelBtn',
                        width: 95,
                        margin: '0 5 0 0',
                        doCancel: function(ids){
                            Ext.Ajax.request({
                                url: App.url("/order/list/cancel"),
                                params: { ids: ids },
                                success: function (response, opts) {
                                    App.showMsg("Record Cancelled");
                                    me.reloadStore();
                                    me.selModel.deselectAll();
                                },
                                failure: function (response, opts) {
                                    App.showError('Cannot Cancel : ' + response.status);
                                },
                                scope: this
                            });
                        },
                        handler: function(button, event){
                            var ids = [];
                            var pass = true;
                            var str = "";
                            me.store.each(function(record){
                                if(record.get('cancel')){
                                    ids.push(record.get("id"));
                                    if (record.get("havePayment")) {
                                        str = str == "" ? record.get("orderNo") : str+", " + record.get("orderNo");
                                        pass = false;
                                    }
                                }
                            });
    
                            if(ids.length == 0) return;
    
                            if (!pass) {
                                App.confirm(str+" have payment.",
                                 "Do you want to Cancel record?",
                                 function(buttonId, text, opt){
                                    if (buttonId === "yes") {
                                        button.doCancel(ids);
                                    }
                                 });
                            }else{
                                button.doCancel(ids);
                            }
                        }
                    },
                    */
                ]
            },
            bbar: {
                xtype: 'pagingtoolbar',
                displayInfo: true
            },
            store: Ext.create('App.store.OrderStore', {}),
            columns: [
                {
                    xtype: 'rownumberer',
                    width: 50,
                },
                /*
                {
                    xtype: 'actioncolumn',
                    text: '',
                    width: 30,
                    align: 'center',
                    items: [
                        {
                            iconCls: 'silk-page-white-edit',
                            tooltip: 'Edit',
                            handler: function (view, rowIndex, colIndex, item, e, record) {
                                App.loadModuleWin('orderWindow', App.localeRes('Order'), {
                                    params: { id: record.get('id') },
                                    callbackOnClose: function () {
                                        me.loadStore(me.params.custId);
                                    }
                                });
                            },
                            scope: me
                        }
                    ]
                },
                */
                {
                    xtype: 'datecolumn',
                    dataIndex: 'date',
                    text: App.localeRes('Order Date'),
                },
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'orderNo',
                    text: App.localeRes('Order No.'),
                    renderer: function (value, metaData, record, row, col, store, grid) {
                        return App.setClickableOrder(Ext.id(), 
                        record.get("id"),
                        //record.get('ignoreC'),
                        record.get('status')==-2,
                        record.get('type'),
                        value,
                        function(){
                            me.reloadStore();
                            //me.reconfigure(me.getStore());
                        });
                    },
                },
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'amount',
                    align: 'right',
                    text: App.localeRes('Amount'),
                    flex: 1,
                    renderer: function(value, metaData, record, row, col, store, grid) {
                        if(record.get("refNo")) return value+"<br/>&#160;";
                        var str = "<b>"+value+"</b><br/>&#160;";
                        if(record.get("outstanding"))
                            str += ""+App.localeRes('Outstanding')+" : "+record.get("outstanding")+"</font>";
                        return str;
                    }
                 
                },
                {
                    xtype: 'widgetcolumn',
                    text: App.localeRes('Invoice'),
                    width: 100,
                    align: 'center',
                    widget: {
                        xtype: "container",
                        layout: 'vbox',
                        items:[
                            {
                                xtype: 'button',
                                itemId : 'invoiceBtn',
                                text: App.localeRes('Invoice'),
                                handler: function(){
                                    App.loadModuleWin('invoiceWindow', App.localeRes('Invoice'), {
                                        params: {
                                            orderId: this.orderId,
                                            custId: this.custId,
                                        },
                                        callbackOnClose: function() {}
                                    });
                                }
                            },
                        ]
                    },
                    onWidgetAttach: function(column, widget, record){
                        if(record.get("ref")){
                            widget.setHidden(true);
                        }else{
                            widget.setHidden(false);
                            widget.down('#invoiceBtn').orderId = record.id;
                            widget.down('#invoiceBtn').custId = record.get("custId");
                        }
                    }
               },
                {
                    text: App.localeRes('Stock'),
                    dataIndex: 'outDate',
                    xtype: 'gridcolumn',
                    width: 130,
                    align: 'right',
                    renderer: function(value, metaData, record, row, col, store, grid) {
                        var outColorCode = '#E9573E';
                        if(record.get("outStatus") == 2)
                            outColorCode = '#44A720';

                        var inColorCode = '#E9573E';
                        if(record.get("inStatus") == 2)
                            inColorCode = '#44A720';
                        if(!value) return "";
                        //if(record.get("inDate")) return "";
                        var str = "<b>"+App.localeRes('Out')+" : <font  color='"+outColorCode+"'>" + App.convertTimestampToDate(value) + '</font></b>';
                        str+="<br/>";
                        if(record.get("inDate"))
                            str+="<b>"+App.localeRes('In')+" : <font  color='"+inColorCode+"'>" + App.convertTimestampToDate(record.get("inDate")) + '</font></b>';
                        else
                            str+="<b>"+App.localeRes('In')+" : --&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;</b>";
                        return str;
                    }
                },
                {
                    text: App.localeRes('Target Date'),
                    dataIndex: 'targetCompleteDate',
                    xtype: 'gridcolumn',
                    renderer: function(value, metaData, record, row, col, store, grid) {
                        if(!value||record.get('status') != StatusCombo.STATUS_ON_HAND)
                            return "";
                        let today = new Date();
                        today.setHours(0,0,0,0);
                        let data = new Date(value);
                        if(today.getTime()>data.getTime())
                            return "<font  color='#AAA'>" + value+"</font>"
                        return value;
                    }
                },
                /*
                {
                    xtype: 'datecolumn',
                    dataIndex: 'status',
                    text: App.localeRes('Status'),
                    renderer: function (value, metaData, record, row, col, store, grid) {
                        return StatusCombo.convertToString(value);
                    },
                },
                */
                {
                    xtype: 'checkcolumn',
                    menuDisabled: true,
                    sortable: false,
                    dataIndex: 'view',
                    columnHeaderCheckbox: true,
                    width: 80,
                    text: "<b><i class='fas fa-tasks'></i></b>",
                    style:{
                        color: "#925e8b"
                    },
                },
                {
                    xtype: 'checkcolumn',
                    menuDisabled: true,
                    sortable: false,
                    dataIndex: 'changeStatus',
                    style:{
                        color: "#16b603"
                    },
                    width: 85,
                    text: "<b>"+App.localeRes('Change Status')+"</b>",
                    //text: "<b>"+App.localeRes('Change Status')+"</b> <button type='button'>Button</button>",
                    renderer: function(value, metaData, record, row, col, store, grid) {
                        let statusStr = StatusCombo.convertToString(record.get("status"));
                        if(App.localeRes("On Hand")==statusStr){
                            statusStr = "<i><b>" + statusStr+"</b></i>";
                        }
                        let status = "<p>"+statusStr+"</p>";
                        if (record.get('ref')) return status;
                        return new Ext.ux.CheckColumn().renderer(value)+status;
                    }
                },
                /*
                {
                    xtype: 'checkcolumn',
                    menuDisabled : true,
                    sortable: false,
                    dataIndex: 'complete',
                    text: App.localeRes("Complete"),
                    renderer: function (value, metaData, record, row, col, store, grid) {
                        if(record.get('ref') || record.get('status') != StatusCombo.STATUS_ON_HAND)
                            return '';
                        return (new Ext.ux.CheckColumn()).renderer(value);
                    }
                },
                {
                    xtype: 'checkcolumn',
                    menuDisabled : true,
                    sortable: false,
                    dataIndex: 'cancel',
                    text: App.localeRes("Cancel"),
                    renderer: function (value, metaData, record, row, col, store, grid) {
                        if(record.get('ref') || record.get('status') != StatusCombo.STATUS_ON_HAND)
                            return '';
                        return (new Ext.ux.CheckColumn()).renderer(value);
                    }
                }
                */
            ],
            listeners:{
                cellclick:function(view, cell,cellIdx, record, row){
                    view.up('window').down("customerOrderItemGrid").loadStore(record.get('id'));
                },
                beforecontainermousedown  : function(view, record, index, eOpts ){
                    return false;
                }

            }
        });

        me.callParent(arguments);
    }
});
