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

    layout: 'vbox',

    scrollable: {
        alwaysShow: true
    },

    defaults: {
        width: '100%',
        margin: '2 4 0 4'
    },

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

        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());
    },

    params: {},
    initComponent: function() {
        var me = this;

        Ext.apply(me, {
            items: [
                {
                    xtype: 'form',
                    itemId: 'searchCriteriaForm',
                    bodyPadding: 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: {
                                    top: 2,
                                    bottom: 2,
                                    left: 5,
                                    right:5
                                },
                                listeners: {
                                    specialkey: function(field, e) {
                                        if (e.getKey() == e.ENTER) me.doSearch();
                                    }
                                }
                            },
                            items: [
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Order No.'),
                                    name: 'orderNo',
                   
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('First Name'),
                                    name: 'firstName',
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Surname'),
                                    name: 'surname',
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Chinese Name'),
                                    name: 'nameCh',
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Email')+"/"+App.localeRes('Phone'),
                                    name: 'emailPhone',
                                },
                                {
                                    xtype: 'orderStatusCombo',
                                    fieldLabel: App.localeRes("Status"),
                                    name: 'status',
                                },
                                {
                                    xtype: 'container',
                                    layout: 'hbox',
                                    items: [
                                        {
                                            xtype: 'datefield',
                                            name: 'fromDate',
                                            fieldLabel: App.localeRes('Order Date'),
                                            flex: 3
                                        },
                                        {
                                            xtype: 'datefield',
                                            name: 'toDate',
                                            fieldLabel: App.localeRes('to'),
                                            labelWidth: 15,
                                            labelSeparator: '',
                                            flex: 2
                                        }
                                    ]
                                },
                                {
                                    xtype: 'container',
                                    layout: 'hbox',
                                    items: [
                                        {
                                            xtype: 'datefield',
                                            name: 'targetCompleteDateFrom',
                                            fieldLabel: App.localeRes('Target Date'),
                                            flex: 3
                                        },
                                        {
                                            xtype: 'datefield',
                                            name: 'targetCompleteDateTo',
                                            fieldLabel: App.localeRes('to'),
                                            labelWidth: 15,
                                            labelSeparator: '',
                                            flex: 2
                                        }
                                    ]
                                },
                                {
                                    xtype: 'container',
                                    layout: 'hbox',
                                    items: [
                                        {
                                            xtype: 'checkbox',
                                            fieldLabel: App.localeRes('Not Balance'),
                                            padding: '0 20 0 0',
                                            name: 'balance',
                                            inputValue: '1',
                                            uncheckedValue: '0'
                                        },
                                        /*
                                        {
                                            xtype: 'checkbox',
                                            fieldLabel: App.localeRes('Show Ignored'),
                                            name: 'showIgnored',
                                            padding: '0 0 0 20',
                                            value:'0',
                                            inputValue: '1',
                                            uncheckedValue: '0'
                                        },
                                        */
                                    ]
                                },
                                
                            ]
                        }
                    ],
                    buttons: [
                        {
                            xtype: 'button',
                            text: App.localeRes('New Order'),
                            itemId: 'newOrderBtn',
                            ui: 'default',
                            iconCls: 'silk-add',
                            handler: function(button, event) {
                                App.loadModuleWin('orderWindow', App.localeRes('Order'), {
                                    params: {},
                                    callbackOnClose: function() {
                                        if(me.down("orderGrid").needReload)
                                            me.down("orderGrid").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: 'orderGrid',
                    itemId: 'orderGrid',
                    //flex: 1
                }
            ]
        });

        me.callParent(arguments);
        //me.doSearch();
    }
});

Ext.define('App.view.OrderGrid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.orderGrid',
    width: '100%',
    //height: '100%',
    scrollable: {
        alwaysShow: true
    },
    viewConfig : {
        enableTextSelection: true
    },

    needReload: false,

    reloadStore: function() {
        var me = this;
        me.needReload = true;
        me.getStore().reload();
        me.reconfigure(me.getStore());
    },

    initComponent: function() {
        var me = this;
        Ext.apply(me, {
            tbar: {
                layout: 'hbox',
                padding: 0,
                items: [
                    '->',
                    {
                        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'),
                                    outStatus:StockInOutStatusCombo.StockInOutStatus_PENDING,
                                    inRemark:null,
                                    inDate:null,
                                    inStatus:StockInOutStatusCombo.StockInOutStatus_BLANK,
                                });
                            });

                            App.loadModuleWin('dateRemarkWindow-2', App.localeRes('Stock Out'), {
                                params: {
                                    records: records,
                                },
                                callbackOnClose: function() {
                                    me.reloadStore();
                                }
                            });
                        }
                    },
                    {
                        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'),
                                    outStatus:record.get('outStatus'),
                                    inRemark:record.get('inRemark'),
                                    inDate:record.get('inDate'),
                                    inStatus:StockInOutStatusCombo.StockInOutStatus_RECEIVED,
                                });
                            });

                            App.loadModuleWin('dateRemarkWindow', App.localeRes('Stock In'), {
                                params: {
                                    records: records,
                                },
                                callbackOnClose: function() {
                                    me.reloadStore();
                                }
                            });
                        }
                    },
                    {
                        xtype: 'button',
                        text: App.localeRes('Images'),
                        iconCls: 'fas fa-tasks',
                        ui: 'soft-purple',
                        itemId: 'viewBtn',
                        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){
                                App.showInfo(' Please select record at <b><i style="color:#925e8b" class="fas fa-tasks"></i> </b> column. ', App.localeRes('Info'));
                                return;
                            } 

                            App.loadModuleWin('imageGroupWindow', App.localeRes('Image Group'), {
                                params: {
                                    orders: {
                                        refType: 'order',
                                        ids: ids
                                    },
                                },
                                callbackOnClose: function() {
                                    me.reloadStore();
                                }
                            });
                        }
                    },
                    {
                        xtype: 'button',
                        text: "<b>"+App.localeRes('Change Status')+"</b>",
                        itemId: 'changeStatusBtn',
                        width: 85,
                        ui: "green",
                        margin: '0 30 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.reloadStore();
                                    me.selModel.deselectAll();
                                }
                            });
                        }
                    },
                    /*
                    {
                        xtype: 'button',
                        text: App.localeRes('Complete'),
                        ui: 'soft-green',
                        itemId: 'completeBtn',
                        width: 85,
                        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.reloadStore();
                                    me.selModel.deselectAll();
                                },
                                failure: function(response, opts) {
                                    App.showError('Cannot Complete : ' + response.status);
                                },
                                scope: this
                            });
                        }
                    },
                    {
                        xtype: 'button',
                        text: App.localeRes('Cancel'),
                        ui: 'soft-red',
                        itemId: 'cancelBtn',
                        width: 75,
                        margin: '0 18 0 0',
                        doCancel: function(ids) {
                            if (App.isGranted(['ORDER_CANCEL']) == true) {
                                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
                                });
                            } else {
                                App.showError('You Have No Authority To Process This Action!', 'Authority Issue');
                            }
                        },
                        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: 80
                },
                /*
                {
                    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.reloadStore();
                                    }
                                });
                            },
                            scope: me
                        }
                    ]
                },
                */
                {
                    xtype: 'datecolumn',
                    dataIndex: 'date',
                    text: App.localeRes('Order Date')
                },
                {
                    xtype: 'gridcolumn',
                    text: App.localeRes('Customer'),
                    dataIndex: 'customerName',
                    flex: 1,
                    renderer: function(value, metaData, record, row, col, store, grid){
                        if (metaData) metaData.tdAttr = 'data-qtip="' 
                            + App.setCustTooltip(
                                record.get("customerName")
                                , record.get("phone")
                                , record.get("email")
                            )+ '"';
                            
                         return App.setClickableCustOrder(
                            Ext.id(), 
                            record.get('custId'),
                            value,
                            function(){
                                me.reloadStore();
                            });
                    }
                },
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'orderNo',
                    width: 110,
                    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();
                            });
                    }
                },
                {
                    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: 'gridcolumn',
                    dataIndex: 'outstanding',
                    align: 'right',
                    text: App.localeRes('Outstanding'),
                    flex: 1
                },
                */
                {
                    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: 'gridcolumn',
                    dataIndex: 'status',
                    text: App.localeRes('Status'),
                    width: 90,
                    renderer: function(value, metaData, record, row, col, store, grid) {
                        return StatusCombo.convertToString(value);
                    }
                },
                */
               {
                    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");
                        }
                    }
               },
                {
                    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',
                    width: 85,
                    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',
                    width: 80,
                    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);
                    }
                }
                */

                {
                    xtype: 'actioncolumn',
                    text: '',
                    width: 30,
                    align: 'center',
                    hidden: !App.isGranted(['CUSTOMER_DELETE']),
                    items: [
                        {
                            iconCls: 'silk-cross',
                            tooltip: App.localeRes('Delete'),
                            handler: function(view, rowIndex, colIndex, item, e, record) {
                                if (App.isGranted(['CUSTOMER_DELETE']) == true) {
                                    App.loadModuleWin(
                                        "confirmWithPasswordWindow",
                                        "Confirm Delete", 
                                        {
                                            authUrl: App.url('/order/get-auth'),
                                            onConfirm: function(){
                                                Ext.Ajax.request({
                                                    url: App.url('/order/delete'),
                                                    params: { id: record.get('id') },
                                                    success: function(response, opts) {
                                                        App.showMsg('Order Deleted');
                                                    },
                                                    failure: function(response, opts) {
                                                        App.showError('Cannot Delete : ' + response.status);
                                                    },
                                                });
                                            },
                                            callbackOnClose: function(){
                                                me.getStore().reload();
                                            }
                                        }
                                    );
                                }else {
                                    App.showError(
                                        'You Have No Authority To Process This Action!',
                                        'Authority Issue'
                                    );
                                }
                            },
                        }
                    ]
               },

            ],
            listeners: {}
        });
        me.callParent(arguments);
    }
});
