Ext.define("App.view.WorkshopContainer", {
    extend: "Ext.container.Container",
    xtype: "workshopContainer",
    alias: "widget.workshopContainer",

    layout: 'vbox',

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

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

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

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

    params: {},

    initComponent: function() {
        var me = this;

        Ext.apply(me, {
            items: [
                {
                    xtype: 'form',
                    itemId: 'searchCriteriaForm',
                    bodyPadding: 15,
                    buttonAlign: 'left',
                    defaults: {
                        selectOnFocus: true,
                    },
                    items: [
                        {
                            xtype: 'fieldcontainer',
                            layout: {
                                type: 'table',
                                columns: 3,
                            },
                            defaults: {
                                width: '95%',
                                listeners: {
                                    specialkey: function(field, e) {
                                        if (e.getKey() == e.ENTER) me.doSearch();
                                    }
                                }
                            },
                            items: [
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes("Order No."),
                                    name: 'orderNo',
                                    flex: 1,
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('First Name'),
                                    name: 'firstName',
                                    flex: 1,
                                    hidden:  true
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Surname'),
                                    name: 'surname',
                                    flex: 1,
                                    hidden:  true
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Chinese Name'),
                                    name: 'nameCh',
                                    hidden:  true
                                },
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes('Email')+"/"+App.localeRes('Phone'),
                                    name: 'emailPhone',
                                    hidden:  true
                                },
                                {
                                    xtype: 'stockInOutStatusCombo',
                                    name: 'stockInStatus',
                                    fieldLabel: App.localeRes('Stock In'),
                                },
                                {
                                    xtype: 'workshopStatusCombo',
                                    name: 'workshopStatus',
                                    fieldLabel: App.localeRes('Status'),
                                },
                                {
                                    xtype: 'container',
                                    layout: 'hbox',
                                    items: [
                                        {
                                            xtype: 'datefield',
                                            name: 'fromOutDate',
                                            fieldLabel: App.localeRes('Received Date'),
                                            width: 230,
                                        },
                                        {
                                            xtype: 'datefield',
                                            name: 'toOutDate',
                                            fieldLabel: App.localeRes("to"),
                                            labelWidth: 15,
                                            labelSeparator: '',
                                            width: 150,
                                        }
                                    ],
                                },
                                {
                                    xtype: 'container',
                                    layout: 'hbox',
                                    items: [
                                        {
                                            xtype: 'datefield',
                                            name: 'workshopTargetDateFrom',
                                            fieldLabel: App.localeRes('Target Date'),
                                            width: 230,
                                        },
                                        {
                                            xtype: 'datefield',
                                            name: 'workshopTargetDateTo',
                                            fieldLabel: App.localeRes("to"),
                                            labelWidth: 15,
                                            labelSeparator: '',
                                            width: 150,
                                        }
                                    ],
                                },
                            ]
                        },
                    ],
                    buttons: [
                        {
                            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: "workshopGrid",
                    itemId: "workshopGrid",
                    flex: 1
                }
            ],
        });

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

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

        reloadStore: function () {
            var me = this;
            me.up('workshopContainer').doSearch();
        },

        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,{
                tbar: {
                    layout: 'hbox',
                    padding: 0,
                    items: [
                        '->',
                        {
                            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/workshop/list/complete'),
                                    params: { ids: ids },
                                    success: function(response, opts) {
                                        App.showMsg('Completed');
                                        me.reloadStore();
                                        me.selModel.deselectAll();
                                    },
                                    failure: function(response, opts) {
                                        App.showError('Fail : ' + response.status);
                                    },
                                    scope: this
                                });
                            }
                        },
                        {
                            xtype: 'button',
                            text: App.localeRes('Stock In'),
                            ui: 'soft-purple',
                            itemId: 'stockInBtn',
                            width: 175,
                            margin: '0 5 0 0',
                            handler: function(button, event) {
                                var ids = [];
                                me.store.each(function(record) {
                                    if (record.get('stockInCheck')) ids.push(record.get('id'));
                                });

                                if (ids.length == 0){
                                    App.showInfo(App.localeRes(' Please select record at "Stock In" column. '), "Info");
                                    return;
                                }

                                var count = ids.length;
                                for(var i=0; i<ids.length; i++){
                                    Ext.Ajax.request({
                                        url: App.url('/order/workshop/updateindate'),
                                        params: { 
                                            id: ids[i],
                                            outStatus: StockInOutStatusCombo.StockInOutStatus_RECEIVED,
                                        },
                                        success: function(response, opts) {
                                            count--;
                                            if(count ==0){
                                                App.showMsg('Saved');
                                                me.reloadStore();
                                                me.selModel.deselectAll();
                                            }
                                        },
                                        failure: function(response, opts) {
                                            App.showError('Cannot Save : ' + response.status);
                                        },
                                        scope: this
                                    });
                                }
                            }
                        },
                        {
                            xtype: 'button',
                            text: App.localeRes('Stock Out'),
                            ui: 'soft-purple',
                            itemId: 'stockOutBtn',
                            width: 175,
                            margin: '0 5 0 0',
                            handler: function(button, event) {
                                var ids = [];
                                me.store.each(function(record) {
                                    if (record.get('stockOutCheck')) ids.push(record.get('id'));
                                });
    
                                if (ids.length == 0){
                                    App.showInfo(App.localeRes(' Please select record at "Stock Out" column. '), "Info");
                                    return;
                                }

                                var count = ids.length;
                                for(var i=0; i<ids.length; i++){
                                    Ext.Ajax.request({
                                        url: App.url('/order/workshop/updateoutdate'),
                                        params: { 
                                            id: ids[i],
                                            inStatus: StockInOutStatusCombo.StockInOutStatus_PENDING,
                                            inDate: new Date(),
                                            inRemarks: "",
                                        },
                                        success: function(response, opts) {
                                            count--;
                                            if(count ==0){
                                                App.showMsg('Saved');
                                                me.reloadStore();
                                                me.selModel.deselectAll();
                                            }
                                        },
                                        failure: function(response, opts) {
                                            App.showError('Cannot Save : ' + response.status);
                                        },
                                        scope: this
                                    });
                                }
                            }
                        }
                    ]
                },

                store: Ext.create('App.store.WorkshopStore', {}),

                columns: [
                    {
                        xtype: 'rownumberer',
                        text: App.localeRes(''),
                        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('workshopWindow', 'Workshop details', {
                                        params: { data: record.data },
                                        callbackOnClose: function() {
                                             me.reloadStore();
                                        }
                                    });
                                },
                                scope: me
                            }
                        ],
                    },
                    */
                    {
                        xtype: 'datecolumn',
                        dataIndex: 'targetCompleteDate',
                        text: App.localeRes('Target Date'),
                    },
                    {
                        xtype: 'gridcolumn',
                        dataIndex: 'customerName',
                        text: App.localeRes('Customer'),
                        width: 200,
                        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',
                        text: App.localeRes('Order No.'),
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            return App.setClickableWorkshop(Ext.id(), 
                            record.data,
                            //record.get('ignoreC'),
                            record.get('status')==-2,
                            record.get('type'),
                            value,
                            function(){
                                me.reloadStore();
                            });
                        },
                    },
                    {
                        xtype: 'actioncolumn',
                        text: '',
                        width: 40,
                        align: 'center',
                        items: [
                            {
                                iconCls: 'icon-images',
                                tooltip: 'Image Group',
                                handler: function(view, rowIndex, colIndex, item, e, record) {
                                    Ext.Ajax.request({
                                        url: App.url('/customer/order-list'),
                                        params: { 
                                            custId: record.get('custId'),
                                            ignoreOrderId:record.get('id')
                                        },
                                        success: function(response, opts) {
                                            var ids = [];
                                            var result = Ext.decode(response.responseText);
                                            if (result.records) {
                                                ids=result.records.ids.split(',');
                                            }
                                            ids.unshift(record.get('id'));
                                            if (ids.length == 0) {
                                                App.showInfo('No order record.');
                                                return;
                                            }
                                            me.popUpWin(record.get('custId'), ids);
                                        },
                                        failure: function(response, opts) {
                                            App.showError('Error : ' + response.status);
                                        },
                                        scope: this
                                    });
                                },
                                scope: me
                            }
                        ]
                    },
                    /*
                    {
                        xtype: 'gridcolumn',
                        dataIndex: 'refNo',
                        width: 150,
                        text: App.localeRes('Ref No.'),
                    },
                    */
                    {
                        xtype: 'gridcolumn',
                        dataIndex: 'outRemark',
                        text: App.localeRes('Remarks'),
                        flex: 1
                    },
                    /*
                    {
                        xtype: 'gridcolumn',
                        dataIndex: 'outStatus',
                        text: App.localeRes('Stock In'),
                        hidden:true,
                        renderer: function (value, metaData, record, row, col, store, grid) {
                            return " ("+StockInOutStatusCombo.convertToString(record.get("outStatus"))+")";
                        }
                    },
                    {
                        xtype: 'gridcolumn',
                        dataIndex: 'workshopStatus',
                        text: App.localeRes('Status'),
                        hidden: true,
                        renderer: function (value, metaData, record, row, col, store, grid) {
                            return  WorkshopStatusCombo.convertToString(value);
                        }
                    }, 
                    */
                    {
                        xtype: 'checkcolumn',
                        menuDisabled: true,
                        sortable: false,
                        dataIndex: 'complete',
                        style:{
                            color: "#16b603"
                        },
                        text: App.localeRes('Status'),
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            if (record.get('workshopStatus') != WorkshopStatusCombo.WS_STATUS_PENDING) 
                                return '<div style="padding: 10px 0px 0px 0px;">'
                                    +WorkshopStatusCombo.convertToString(record.get("workshopStatus"))+'</div>';
                            return WorkshopStatusCombo.convertToString(record.get("workshopStatus"))
                                    +" "
                                    +new Ext.ux.CheckColumn().renderer(value);
                        }
                    },
                    {
                        xtype: 'checkcolumn',
                        menuDisabled: true,
                        sortable: false,
                        dataIndex: 'stockInCheck',
                        columnHeaderCheckbox: true,
                        width: 180,
                        text: "<b>"+App.localeRes('Stock In')+"</b>",
                        style:{
                            color: "#925e8b"
                        },
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            if (record.get('outStatus') == StockInOutStatusCombo.StockInOutStatus_RECEIVED){
                                return '<div style="padding: 10px 0px 0px 0px;">'
                                + App.convertTimestampToDate(record.get("outDate"))
                                +" ("+StockInOutStatusCombo.convertToString(record.get("outStatus"))+") "
                                +'</div>';
                            }
                            return App.convertTimestampToDate(record.get("outDate"))
                                +" ("+StockInOutStatusCombo.convertToString(record.get("outStatus"))+") "
                                +new Ext.ux.CheckColumn().renderer(value);
                        }
                    },
                    {
                        xtype: 'checkcolumn',
                        menuDisabled: true,
                        sortable: false,
                        dataIndex: 'stockOutCheck',
                        columnHeaderCheckbox: true,
                        text: "<b>"+App.localeRes('Stock Out')+"</b>",
                        width: 180,
                        style:{
                            color: "#925e8b"
                        },
                        renderer: function(value, metaData, record, row, col, store, grid) {
                            if(record.get("inStatus") != null){
                                return '<div style="padding: 10px 0px 0px 0px;">'
                                + App.convertTimestampToDate(record.get("inDate"))
                                +" ("+StockInOutStatusCombo.convertToString(record.get("inStatus"))+") "
                                +'</div>';
                            }
                            return new Ext.ux.CheckColumn().renderer(value);
                        }
                    },
                ],
                bbar: {
                    xtype: 'pagingtoolbar',
                    displayInfo: true
                },

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