
Ext.define('App.view.CustomerContainer', {
    extend: 'Ext.container.Container',
    xtype: 'customerContainer',
    alias: 'widget.customerContainer',
    itemId: 'customerContainer',
    layout: 'vbox',
    defaults: {
        width: '100%',
        margin: '2 4 0 4'
    },
    scrollable: {
        alwaysShow: true,
    },
   
    params: {},

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

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

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

    initComponent: function() {
        var me = this;

        Ext.apply(me, {
            items: [
                {
                    xtype: 'form',
                    itemId: 'searchCriteriaForm',
                    bodyPadding: "15 15 0 15",
                    buttonAlign: 'left',
                    defaults: {
                        selectOnFocus: true,
                        margin: '0 4 0 4',
                    },
                    items: [
                        {
                            xtype: 'fieldcontainer',
                            margin: '0 4 0 4',
                            layout: {
                                type: 'table',
                                columns: 3
                            },
                            defaults: {
                                width: '95%',
                                margin: {
                                    bottom: 4,
                                },
                                listeners: {
                                    specialkey: function(field, e) {
                                        if (e.getKey() == e.ENTER) me.doSearch();
                                    }
                                }
                            },
                            items: [
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('First Name'),
                                    name: 'firstName'
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Surname'),
                                    name: 'surname'
                                },
                                {
                                    xtype: 'container',
                                    layout: 'hbox',
                                    items: [
                                        {
                                            xtype: 'orderTypeCombo',
                                            name: 'orderType',
                                            fieldLabel: App.localeRes('Order No.'),
                                            allowBlank: true,
                                            flex: 1
                                        },
                                        {
                                            xtype: 'textfield',
                                            name: 'orderCode',
                                            fieldLabel: App.localeRes(' '),
                                            labelWidth: 0,
                                            labelSeparator: '',
                                            maxLength: 200,
                                            flex:1,
                                            margin: '0 1 0 0',

                                        }
                                    ]
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Chinese Name'),
                                    name: 'nameCh'
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Contact'),
                                    name: 'contact'
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Email'),
                                    name: 'email'
                                },
                                {
                                    xtype: 'container',
                                    layout: 'hbox',
                                    items: [
                                        {
                                            xtype: 'datefield',
                                            name: 'fromDate',
                                            fieldLabel: App.localeRes('Target Date'),
                                            flex: 3
                                        },
                                        {
                                            xtype: 'datefield',
                                            name: 'toDate',
                                            fieldLabel: App.localeRes('to'),
                                            labelWidth: 15,
                                            labelSeparator: '',
                                            flex: 2,
                                            margin: '0 1 0 0',
                                        }
                                    ]
                                },
                                {
                                    xtype: 'container',
                                    layout: 'hbox',
                                    items: [
                                        {
                                            xtype: 'checkbox',
                                            fieldLabel: App.localeRes('On Hand')+" (O)",
                                            name: 'onHand',
                                            inputValue: '1',
                                            uncheckedValue: '0'
                                        },
                                        {
                                            xtype: 'checkbox',
                                            fieldLabel: App.localeRes('Balance')+" (B)",
                                            name: 'balance',
                                            margin: '0 0 0 60',
                                            inputValue: '1',
                                            uncheckedValue: '0'
                                        }
                                    ]
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Tags'),
                                    name: 'tag'
                                },
                            ]
                        }
                    ],
                    buttons: [
                        {
                            xtype: 'button',
                            text: App.localeRes('New Customer'),
                            ui: 'default',
                            itemId: 'newCustBtn',
                            iconCls: 'silk-add',
                            handler: function(button, event) {
                                App.loadModuleWin('customerWindow', App.localeRes('Customer'), {
                                    params: { record: null },
                                    callbackOnClose: function() {
                                        if(me.down("customerGrid").needReload)
                                            me.down("customerGrid").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: 'customerGrid',
                    itemId: 'customerGrid',
                }
            ]
        });
        me.callParent(arguments);
/*
        onScan.attachTo(document,{
            suffixKeyCodes: [13],
            reactToPaste: false,
            onScan: function(sCode,iQty ) {
                alert(iQty + 'x ' + sCode); 
            }
        });
*/
    },
});


Ext.define('App.view.CustomerGrid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.customerGrid',
    width: '100%',

    viewConfig : {
        enableTextSelection: true
    },
    needReload: false,

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

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

    initComponent: function() {
        var me = this;
        Ext.apply(me, {
            bbar: {
                xtype: 'pagingtoolbar',
                displayInfo: true
            },
            store: Ext.create('App.store.CustomerStore', {}),
            columns: [
                {
                    xtype: 'rownumberer',
                    width: 80
                },
                /*
                {
                    xtype: 'actioncolumn',
                    text: '',
                    width: 30,
                    align: 'center',
                    items: [
                        {
                            iconCls: 'silk-page-white-edit',
                            tooltip: App.localeRes('Edit'),
                            handler: function(view, rowIndex, colIndex, item, e, record) {
                                App.loadModuleWin('customerWindow', App.localeRes('Customer'), {
                                    params: { id: record.get('id') },
                                    callbackOnClose: function() {
                                        me.reloadStore();
                                    }
                                });
                            },
                            scope: me
                        }
                    ]
                },
                */
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'customerName',
                    text: App.localeRes('Customer'),
                    width: 180,
                    renderer: function(value, metaData, record, row, col, store, grid){
                        var str = App.setClickableCust(
                            Ext.id(), 
                            record.get('id'),
                            value,
                            function(){
                                me.reloadStore();
                            });
                        return str;
                    }
                },
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'customerName',
                    text: App.localeRes('Details'),
                    width: 300,
                    renderer: function(value, metaData, record, row, col, store, grid){
                        var contact = "";
                        var email = record.get('email'),
                            emailC = record.get("companyEmail");
                        var phone = record.get('phone1'),
                            phone2 = record.get('phone2'),
                            phoneC = record.get('companyPhone');

                        if(emailC)
                            email = email?email+"/ "+emailC: emailC;

                        if (phone && phone != '' && phone2) phone = phone + '/ ' + phone2;
                        else phone = (phone ? phone : '') + (phone2 ? phone2 : '');

                        if(phoneC)
                            phone = phone?phone + '/ ' +phoneC:phoneC; 

                            contact = (email?"<i class='far fa-envelope'></i>"+" : "+email:"");
                            contact += (contact?"<br/>":"")+(phone?"<i class='fas fa-phone'></i>"+" : "+phone:"");
                        return "<div style='color:gray;' >"+contact+"</div>";
                    }
                },
                {
                    xtype: 'actioncolumn',
                    text: '',
                    width: 40,
                    align: 'center',
                    hidden: !App.isGranted(['ORDER_MAINTAIN']),
                    items: [
                        {
                            iconCls: 'icon-table-multiple',
                            tooltip: App.localeRes('Customer Order List'),
                            handler: function(view, rowIndex, colIndex, item, e, record) {
                                App.loadModuleWin('customerOrderWindow', App.localeRes('Customer Order List'), {
                                    params: { id: record.get('id') },
                                    callbackOnClose: function() {
                                        me.reloadStore();
                                    }
                                });
                            },
                            scope: me
                        }
                    ]
                },
                {
                    xtype: 'actioncolumn',
                    text: '',
                    width: 40,
                    align: 'center',
                    hidden: !App.isGranted(['ORDER_MAINTAIN']),
                    items: [
                        {
                            iconCls: 'icon-table-add',
                            tooltip: App.localeRes('New Order'),
                            handler: function(view, rowIndex, colIndex, item, e, record) {
                                App.loadModuleWin("orderWindow", App.localeRes("New Order"), {
                                params: {
                                    custId: record.get("id"),
                                },
                                callbackOnClose: function() {
                                    me.reloadStore();
                                }
                            });
                            },
                            scope: me
                        }
                    ]
                },
                {
                    xtype: 'actioncolumn',
                    text: '',
                    width: 40,
                    align: 'center',
                    items: [
                            {
                            iconCls: 'icon-images',
                            tooltip: App.localeRes('Image Group'),
                            handler: function(view, rowIndex, colIndex, item, e, record) {
                                Ext.Ajax.request({
                                    url: App.url('/customer/order-list'),
                                    params: { custId: record.get('id') },
                                    success: function(response, opts) {
                                        var ids = [];
                                        var result = Ext.decode(response.responseText);
                                        if (result.records) {
                                            ids = result.records.ids.split(',');
                                        }
                                        if (ids.length == 0) {
                                            App.showInfo('No order record.');
                                            return;
                                        }
                                        me.popUpWin(record.get('id'), ids);
                                    },
                                    failure: function(response, opts) {
                                        App.showError('Error : ' + response.status);
                                    },
                                    scope: this
                                });
                            },
                            scope: me
                        }
                    ]
                },
                {
                    text: "O",
                    dataIndex: 'onHandOrderNum',
                    xtype: 'actioncolumn',
                    menuDisabled: true,
                    hideable: false,
                    align: 'center',
                    width:32,
                    items: [
                        {
                            iconCls: '',
                            tooltip: '',
                            getClass: function(value, metadata, record) {
                                if (record.get('onHandOrderNum') > 0) {
                                    metadata.tdAttr =
                                        'data-qtip="<strong>' + App.localeRes('Have On Hand Order.') + '</strong>"';
                                    return 'silk-exclamation';
                                } else {
                                    return '';
                                }
                            }
                        }
                    ]
                },
                {
                    text: "B",
                    dataIndex: 'isBalance',
                    xtype: 'actioncolumn',
                    menuDisabled: true,
                    hideable: false,
                    width:30,
                    align: 'center',
                    items: [
                        {
                            iconCls: '',
                            tooltip: '',
                            getClass: function(value, metadata, record) {
                                if (record.get('isBalance')) {
                                    return '';
                                } else {
                                    metadata.tdAttr =
                                        'data-qtip="<strong>' + App.localeRes('Not Balance') + '</strong>"';
                                    return 'silk-exclamation';
                                }
                            }
                        }
                    ]
                },
                
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'remarks',
                    text: App.localeRes('Remarks'),
                    width: 150,
                    renderer: function(value, metaData, record, row, col, store, grid){
                        var refCustomerName = record.get("refCustomerName")?record.get("refCustomerName"): "--";
                        var remarks = record.get("remarks")?record.get("remarks"): "--";
                        return refCustomerName+" | "+remarks;
                    }
                },
                
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'targetCompleteDate',
                    text: App.localeRes('Target Date'),
                    width: 100,
                    renderer: function(value, metaData, record, row, col, store, grid) {
                        if(!value) return "";
                        return App.convertTimestampToDate(value);
                    }
                },
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'nextMeetingDate',
                    text: App.localeRes('Meeting'),
                    width: 130,
                    renderer: function(value, metaData, record, row, col, store, grid) {
                        var lastMeetingDate = record.get('lastMeetingDate');
                        var nextMeetingDate = record.get('nextMeetingDate');
                        var str = "";
                        if(lastMeetingDate || nextMeetingDate ){
                            str += '<table>';
                            str += lastMeetingDate?'<tr style="color:#AAA"><td>'+App.localeRes('Last')+'</td><td> : ' + App.convertTimestampToDate(lastMeetingDate) + '</td></tr>':"";
                            str += nextMeetingDate?'<tr><td>'+App.localeRes('Next')+'</td><td> : ' + App.convertTimestampToDate(nextMeetingDate) + '</td></tr>':"";
                            str += '</table>';
                            return str;
                        }
                        return str;
                    }
                },
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'tag',
                    flex: 1,
                    text: App.localeRes('Tags')
                },
                {
                    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('/customer/get-auth'),
                                            onConfirm: function(){
                                                Ext.Ajax.request({
                                                    url: App.url('/customer/delete'),
                                                    params: { id: record.get('id') },
                                                    success: function(response, opts) {
                                                        App.showMsg('Customer 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'
                                    );
                                }
                            },
                            scope: me
                        }
                    ]
                },

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