Ext.define("App.view.OrderForm", {
    extend: "Ext.form.Panel",
    xtype: "orderForm",
    params: {},
    layout: "vbox",
    scrollable: true,

    onSave: function() {
        var me = this,
            f = me.getForm();

        if (f.isValid()) {
            f.submit({
                url: App.url("/order/save") + "?_csrf=" + App.csrf,
                method: "POST",
                submitEmptyText: false,
                success: function(form, action) {
                    App.showMsg("Saved");
                    if (me.callbackOnSave) {
                        me.callbackOnSave(action.result.id);
                    }
                }
            });
        }else{
            App.showError(App.localeRes("Invalid information"));
        }
    },

    loadForm: function(params) {
        if (!params) return;
        var me = this;
        me.getForm().load({
            url: App.url("/order/load"),
            method: "POST",
            params: {
                id: params.id
            },
            success: function(form, action) {
                Ext.apply(me.params, {id: params.id});
                me.down('#refId').setValue(params.id);
                me.down("filefield").setDisabled(false);
                me.down("#newSheetBtn").setDisabled(false);
                me.down("#trackSheetBtn").setDisabled(false);
                me.down("#removeSheetBtn").setDisabled(false);
                me.down('#photoList').loadPanel();
                if (me.callbackOnLoad) {
                    me.callbackOnLoad(form.getValues());
                }
            }
        });
    },

    uploadFile: function() {
        var me = this;
        if (me.down("filefield").getValue() == "") return;
        me.getForm().submit({
            method: "POST",
            waitMsg: "Uploading...",
            url: App.url("/file/measurement-sheet/ul") + "?orderId="+me.params.id+"&_csrf=" + App.csrf,
            success: function(f, action) {
                App.showMsg("Uploaded");
                me.down("filefield").setValue("");
                me.down('#photoList').loadPanel();
            },
            failure: function(f, action) {
                alert("Uploaded failure");
                me.down("filefield").setValue("");
            }
        });
        console.log(App.url("/file/measurement-sheet/ul") + "?orderId="+me.params.id+"&_csrf=" + App.csrf)
    },

    initComponent: function() {
        var me = this;

        Ext.apply(me, {
            bbar: {
                defaultButtonUI: "default",
                layout: "hbox",
                padding: 0,
                items: [
                    "->",
                    /*
                    {
                        xtype: 'checkbox',
                        fieldLabel: App.localeRes('Ignored'),
                        //name: 'ignoreC',
                        inputValue: '1',
                        uncheckedValue: '0',
                    },
                    */
                    {
                        xtype: "button",
                        text: App.localeRes("Save"),
                        ui: "blue",
                        margin: "0 0 16 0",
                        formBind: true,
                        handler: function(button, event) {
                            me.onSave();
                        }
                    }
                ]
            },
            items: [
                {
                    xtype: "hidden",
                    itemId: 'idfield',
                    name: "id"
                },
                {
                    xtype: "fieldcontainer",
                    width: "100%",
                    margin: "0 0 10 0",
                    layout: "hbox",
                    items: [
                        {
                            xtype: "orderTypeCombo",
                            fieldLabel: App.localeRes("Order No.")+" * ",
                            name: "type",
                            width: "40%",
                            value: 'S-',
                            allowBlank: false,
                            listeners:{
                                change: function(combo, newValue,oldValue){
                                    me.down("#orderCodeField").checkValidOrderNo();
                                }
                            }
                        },
                        {
                            xtype: "textfield",
                            fieldLabel: "&nbsp",
                            labelSeparator: "",
                            itemId: 'orderCodeField',
                            labelWidth: 5,
                            name: "code",
                            flex: 1,
                            maxLength: 30,
                            allowBlank: false,
                            enableKeyEvents: true,
                            isPressing: false,
                            checkValidOrderNo: function(){
                                var field = me.down("#orderCodeField");
                                var type = me.down("orderTypeCombo").getValue();
                                var code = me.down("#orderCodeField").getValue();
                                var id = me.down("#idfield").getValue();

                                if(!code){
                                    me.down('#validResult').setHtml('<i class="fas fa-exclamation-circle" style="color:red" ></i>');
                                    return;
                                }

                                Ext.Ajax.request({
                                    url: App.url("/order/check-order-no"),
                                    params:{
                                        id: id,
                                        type: type,
                                        code: code
                                    },
                                    success: function(response, opts) {
                                        var result = Ext.decode(response.responseText);
                                        if(result.success){
                                            me.down('#validResult').setHtml('<i class="fas fa-check-circle" style="color:green" ></i>');
                                            field.setValidation();
                                        }else{
                                            me.down('#validResult').setHtml('<i class="fas fa-exclamation-circle" style="color:red" ></i>');
                                            field.setValidation("Order No. has been used.");
                                        }
                                    },
                                    failure: function(response, opts) {
                                        me.down('#validResult').setHtml('<i class="fas fa-exclamation-circle" style="color:red" ></i>');
                                        field.setValidation(response);
                                    },
                                });
                            },
                            listeners:{
                                change: {
                                    fn:function(field, newValue, oldValue){
                                        field.checkValidOrderNo();
                                        field.isPressing = false;
                                    },
                                    buffer: 1000,
                                },
                                keydown: function(field){
                                    if(field.isPressing) return;
                                    me.down('#validResult').setHtml('<i class="fas fa-spinner fa-pulse"></i>');
                                    field.isPressing = true;
                                }
                            }
                            
                        },{
                            xtype: 'label',
                            html: '<i class="fas fa-spinner fa-pulse" style="color:white"></i>',
                            itemId: 'validResult',
                            padding: '8 4 8 4',
                        }
                    ]
                },
                {
                    xtype: "orderCombo",
                    fieldLabel: App.localeRes("Ref. To"),
                    width: '100%',
                    name: "ref",
                    listeners: {
                        change: function(combo, newValue, oldValue) {
                            if (combo.getSelection()) {
                                me.down("#refNoField").setValue(combo.getSelection().get("orderNo"));
                            } else {
                                me.down("#refNoField").setValue(null);
                            }
                        }
                    }
                },
                {
                    xtype: "hidden",
                    itemId: "refNoField",
                    name: "refNo"
                },
                {
                    xtype: 'fieldcontainer',
                    layout: 'hbox',
                    margin: "0 0 10 0",
                    width: '100%',
                    items: [
                        {
                            xtype: "customerCombo",
                            fieldLabel: App.localeRes("Customer")+" * ",
                            name: "custId",
                            flex: 1,
                            allowBlank: false
                        },
                        {
                            xtype: 'button',
                            text: 'New',
                            handler: function(button){
                                App.loadModuleWin('orderForm_CreateCustomerWindow', App.localeRes("Quick Create Customer Window"), {
                                    callbackOnClose: function (isSave, customerId) {
                                        if(isSave){
                                            me.down("customerCombo").getStore().load();
                                            me.down("customerCombo").setValue(customerId);
                                        }
                                    }
                                });
                                
                            }
                        }
                    ]
                },
                {
                    xtype: "datefield",
                    fieldLabel: App.localeRes("Order Date")+" * ",
                    name: "date",
                    width: "100%",
                    value: new Date(),
                    allowBlank: false
                },
                {
                    xtype: "orderStatusCombo",
                    fieldLabel: App.localeRes("Status")+" * ",
                    name: "status",
                    width: "100%",
                    value: 0,
                    allowBlank: false
                },
                {
                    xtype: "textarea",
                    fieldLabel: App.localeRes("Remarks"),
                    name: "remarks",
                    width: "100%",
                    height: 80,
                    maxLength: 200
                },
                {
                    xtype: "datefield",
                    fieldLabel: App.localeRes("Target Date"),
                    name: "targetCompleteDate",
                    width: "100%",
                },
                {
                    xtype: 'fieldset',
                    title: App.localeRes("Item(s)"),
                    width: '100%',
                    items: [
                        {
                            xtype: 'container',
                            width: '100%',
                            layout: 'hbox',
                            items: [
                                {
                                    xtype: "datefield",
                                    fieldLabel: App.localeRes("Stock Out"),
                                    name: "outDate",
                                    labelAlign: 'top',
                                    flex:1,
                                },
                                {
                                    xtype: "datefield",
                                    fieldLabel: App.localeRes("Stock In"),
                                    labelAlign: 'top',
                                    name: "inDate",
                                    flex:1,
                                },
                            ]
                        },
                        {
                            xtype: 'container',
                            width: '100%',
                            layout: 'hbox',
                            items: [
                                {
                                    xtype: "textarea",
                                    name: "outRemark",
                                    emptyText: App.localeRes("Remarks"),
                                    submitEmptyText: false,
                                    width: "100%",
                                    height: 60,
                                    flex:1,
                                },
                                {
                                    xtype: "textarea",
                                    name: "inRemark",
                                    emptyText: App.localeRes("Remarks"),
                                    submitEmptyText: false,
                                    width: "100%",
                                    height: 60,
                                    flex:1,
                                },
                            ]
                        },
                        {
                            xtype: 'container',
                            width: '100%',
                            layout: 'hbox',
                            items: [
                                {
                                    xtype: "stockInOutStatusCombo",
                                    name: "outStatus",
                                    width: "100%",
                                    flex:1,
                                },
                                {
                                    xtype: "stockInOutStatusCombo",
                                    name: "inStatus",
                                    width: "100%",
                                    flex:1,
                                },
                            ]
                        },
                    ]
                },
                {
					xtype: 'hidden',
					name: 'refType',
					value: 'order'
				},
				{
					xtype: 'hidden',
                    name: 'refId',
                    itemId: 'refId'
                },
                {
                    xtype: 'label',
                    html: '<b>'+App.localeRes("Measurement Sheet")+'</b>',
                },
                {
                    xtype: 'container',
                    layout: 'hbox',
                    width: '100%',
                    items: [
                        {
                            xtype: "filefield",
                            disabled: true,
                            buttonText: App.localeRes("Upload"),
                            buttonConfig:{
                                iconCls: 'fas fa-upload',
                            },
                            ui: "soft-blue",
                            name: "multipartFile",
                            margin: 4,
                            buttonOnly: true,
                            accept: "image/*",
                            listeners: {
                                change: function(field, value, eOpts) {
                                    me.uploadFile();
                                }
                            }
                        },
                        {
                            xtype: 'button',
                            itemId: 'newSheetBtn',
                            disabled: true,
                            ui: 'soft-purple',
                            iconCls: 'fas fa-download',
                            margin: 4,
                            text: App.localeRes("Measurement Sheet"),
                            handler: function(button, event){
                                if(!me.params.id) return;
                                window.open( App.url("/report/measurement-sheet.pdf")+'?orderId=' + me.params.id);
                            }
                        },
                        {
                            xtype: 'button',
                            itemId: 'trackSheetBtn',
                            disabled: true,
                            ui: 'soft-blue',
                            margin: 4,
                            iconCls: "fas fa-history",
                            text: App.localeRes('Track'),
                            handler: function(button, event){
                                if(!me.params.id) return;
                                App.loadModuleWin('orderSheetWindow', App.localeRes("Track Window"), {
                                    params: {
                                        id: me.params.id
                                    },
                                    callbackOnClose: function (isSave) {
                                        me.down('#photoList').loadPanel();
                                    }
                                });
                            }
                        },
                        {
                            xtype: 'container',
                            flex: 1,
                        },
                        {
                            xtype: 'button',
                            itemId: 'removeSheetBtn',
                            disabled: true,
                            iconCls: 'fas fa-trash',
                            ui: 'soft-red',
                            margin: 4,
                            text: App.localeRes('Remove'),
                            handler: function(button, event){
                                if(!me.params.id) return;
                                var deleteRecord = [];
                                me.down('#photoList').items.items
                                    .forEach(function(item, index, array){
                                        if(item.selected){
                                            deleteRecord.push({
                                                fileId: item.fileId,
                                                refId: me.refId,
                                                refType: me.refType,
                                                skey: item.skey,
                                            });
                                        }
                                    });
                        
                                if(deleteRecord.length<=0) return;
                        
                                Ext.Ajax.request({
                                    url: App.url("/order/save"),
                                    params: { 
                                        id: me.params.id,
                                        fileId:'',
                                    },
                                    success: function(response, opts) {
                                        App.showMsg('Removed');
                                        me.down('#photoList').loadPanel();
                                    },
                                    failure: function(response, opts) {
                                        App.showError('Message : ' + response.status);
                                    },
                                    scope: this
                                });
                            }
                        },
                    ]
                },
                {
                    xtype: "container",
                    itemId: "photoList",
                    items: [],
                    loadPanel: function() {
                        var container = this;
                        if(!me.params.id) return;
                        Ext.Ajax.request({
                            url: App.url("/order/get-current-ms.json"),
                            params: { 
                                orderId: me.params.id
                            },
                            success: function(response, opts) {
                                var result = Ext.decode(response.responseText);
                                container.removeAll(true);
                                result.records.forEach(function(item, index, array) {
                                    container.add({
                                       xtype: 'imagefield',
                                       name: item.filename,
                                       thumbnailPath: App.url("/file/thumbnail/"+item.id+"/"+item.skey+"/"+item.filename),
                                       path: App.url("/file/dl/"+item.id+"/"+item.skey+"/"+item.filename),
                                       imageWidth: item.imageWidth,
                                       imageHeight: item.imageHeight,
                                       fileId: item.id,
                                       skey: item.skey,
                                   });
                                });
                            },
                            failure: function(response, opts) {
                                App.showError('Message : ' + response.status);
                            },
                            scope: this
                        });
                    }
                },
                {
                    xtype: 'label',
                    width: '100%',
                    html: '<br/><hr />',
                },
                {
                    xtype: 'photoPanel',
                    itemId: 'orderPhotoPanel2',
                    width: '100%',
                    refType: 'order',
                    url: App.url("/order/image-list.json"),
                },
            ]
        });

        me.callParent(arguments);
    }
});


Ext.define("App.view.OrderForm_CreateCustomerWindow", {
    extend: "Ext.window.Window",
    alias: "widget.orderItemWindow",
    xtype: "orderForm_CreateCustomerWindow",
    title: App.localeRes("Quick Create Customer"),
    width: 600,
    modal: true,

    resizable: true,
    layout: "fit",
    constrainHeader: true,

    onSave: function(){
        var me = this;
        var form = me.down('form');
        form.submit({
            waitMsg: 'Please wait...',
            url: App.url('/order/create-cust'),
            success: function(f, action) {
                App.showMsg('Created');
                me.savedId = action.result.id;
                me.isSave = true;
                me.close();
            },
            failure: function(f, action) {
                alert('Action failure');
            }
        });
    },

    initComponent: function () {
        var me = this;
        Ext.apply(me, {
            items: [
                {
                    xtype: "form",
                    width: '100%',
                    layout: 'vbox',
                    padding: 4,
                    bbar: {
                        defaultButtonUI: "default",
                        layout: "hbox",
                        padding: 0,
                        items: [
                            "->",
                            {
                                xtype: "button",
                                text: App.localeRes("Save"),
                                ui: "blue",
                                margin: "0 0 16 0",
                                formBind: true,
                                handler: function(button, event) {
                                    me.onSave();
                                }
                            }
                        ]
                    },
                    items: [
                        {
                            xtype: 'container',
                            width: '100%',
                            margin: '20 0 10 0',
                            layout: 'hbox',
                            items: [
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes("Name"),
                                    emptyText: App.localeRes("Surname")+" *",
                                    name: 'surname',
                                    width: '100%',
                                    flex: 5,
                                    maxLength: 200,
                                    allowBlank: false
                                },
                                {
                                    xtype: 'textfield',
                                    emptyText: App.localeRes("First Name"),
                                    fieldLabel: App.localeRes("&nbsp"),
                                    labelSeparator: '',
                                    labelWidth: 5,
                                    name: 'firstName',
                                    width: '100%',
                                    flex: 4,
                                    maxLength: 200
                                },
                            ]
                        },
                        {
                            xtype: 'textfield',
                            fieldLabel: App.localeRes("Chinese Name"),
                            name: 'nameCh',
                            width: '100%',
                            maxLength: 200
                        },
                        {
                            xtype: 'container',
                            width: '100%',
                            margin: '0 0 10 0',
                            layout: 'hbox',
                            items: [
                                {
                                    xtype: 'textfield',
                                    fieldLabel: App.localeRes("Mobile"),
                                    name: 'phone1',
                                    flex: 5,
                                    maxLength: 200
                                },
                                {
                                    xtype: 'textfield',
                                    name: 'phone2',
                                    fieldLabel: App.localeRes("/"),
                                    labelWidth: 5,
                                    labelSeparator: '',
                                    flex: 4,
                                    maxLength: 200
                                }
                            ]
                        },
                        {
                            xtype: 'textfield',
                            fieldLabel: App.localeRes("Email"),
                            name: 'email',
                            width: '100%',
                            maxLength: 200
                        },
                        {
                            xtype: 'textarea',
                            fieldLabel: App.localeRes("Address"),
                            name: 'address',
                            width: '100%',
                            height: 80,
                            maxLength: 200
                        },
                    ],
                },
            ],
            listeners: {
                show: function () {
                    if(me.params && me.params.record){
                        me.down('orderItemForm').loadRecord(me.params.record);
                    }else if(me.params && me.params.orderId){
                        me.down('#orderId').setValue(me.params.orderId);
                    }
                },
                close: function (window, opts) {
                    if (me.callbackOnClose) {
                        me.callbackOnClose(window.isSave, window.savedId);
                    }
                }
            }
        });
        me.callParent(arguments);
    }
});


