Ext.define("App.view.UserForm", {
    extend: "Ext.tab.Panel",
    xtype: "userForm",
    params: {},

    bodyPadding: "10px 30px 10px 30px",

    layout: "fit",
    deferredRender: false,

    defaults: {
        scrollable: "y",
        tab: {
            iconAlign: "top"
        }
    },

    tabBar: {
        layout: {
            pack: "center"
        }
    },

    onSaveBtnClick: function(button, event) {
        var me = this,
            bi = me
                .down("#firstTab")
                .down("#infoForm")
                .getForm(),
            biV = bi.getValues(),
            group = me
                .down("#firstTab")
                .down("#groupGrid").getStore()
            auth = me.down("#secondTab").down("userAuthGridLeft"),
            authV = auth.getStore().getUpdatedRecords();


        groupUpdatedRecordsData = new Array();
        authUpdatedRecordsData = new Array();
        if (bi.isValid()) {
            Ext.each(group.getModifiedRecords(),function(item){
                groupUpdatedRecordsData.push(item.data)
            });
            for (i in authV) {
                authUpdatedRecordsData.push(authV[i].data);
            }
            bi.submit({
                url: App.url("/user/save"),
                waitMsg: "Saving",
                params: {
                    groupUpdatedRecordsData: Ext.encode(groupUpdatedRecordsData),
                    authUpdatedRecordsData: Ext.encode(authUpdatedRecordsData)
                },
                success: function(form, action) {
                    App.showMsg("User saved");
                    me.up("userWindow").close();
                },
                failure: function(form, action) {
                    if (action.response.responseText == "DataIntegrityViolation") {
                        App.showError(
                            "Data Integrity Violation<br><br>Possible Causes:<br><br>1. Username is duplicated.<br>2. Data length exceeded max limit.<br>3. Other database error."
                        );
                    } else {
                        App.showError("Action Failed!");
                    }
                }
            });
        } else {
            App.showError("Please Enter The Correct value");
        }
    },

    // onSaveAsBtnClick: function(button, event) {
    //     var me = this,
    //         bi = me.down("#firstTab").down("#basicInfoForm"),
    //         biV = bi.getForm().getValues(),
    //         part = me.down("#secondTab").down("equipmentFormPartGridRight"),
    //         partV = part.getStore().getData().items,
    //         updatedRecordsData = new Array();

    //     ab = bi.down("#id").setValue(null);
    //     if (bi.isValid()) {
    //         for (i in partV) {
    //             updatedRecordsData.push(partV[i].data);
    //         }
    //         bi.submit({
    //             url: App.url("/common/equipment/save"),
    //             waitMsg: "Saving",
    //             params: { updatedRecordsData: Ext.encode(updatedRecordsData) },
    //             success: function(form, action) {
    //                 App.showMsg("Equipment saved");
    //                 me.up("equipmentWindow").close();
    //             },
    //             failure: function(form, action) {
    //                 if (action.response.responseText == "DataIntegrityViolation") {
    //                     App.showError(
    //                         "Data Integrity Violation<br><br>Possible Causes:<br><br>1. Username is duplicated.<br>2. Data length exceeded max limit.<br>3. Other database error."
    //                     );
    //                 } else {
    //                     App.showError("Action Failed!");
    //                 }
    //             }
    //         });
    //     } else {
    //         App.showError("Please Enter The Correct value");
    //     }
    // },

    initComponent: function() {
        var me = this;

        Ext.apply(me, {
            style: {
                "border-radius": "0px",
                "box-shadow": null
            },
            items: [
                {
                    title: App.localeRes("Information"),
                    iconCls: "x-fa fa-info",
                    tabIndex: 0,
                    itemId: "firstTab",
                    layout: {
                        type: "hbox",
                        align: "stretch"
                    },
                    items: [
                        {
                            xtype: "form",
                            itemId: "infoForm",
                            defaultType: "textfield",
                            flex: 2,
                            layout: "fit",
                            width: "100%",
                            defaults: {
                                labelWidth: 10,
                                labelSeparator: "",
                                anchor: "100%"
                            },
                            style: {
                                "border-radius": "0px",
                                "box-shadow": null
                            },
                            items: [
                                {
                                    xtype: "fieldset",
                                    title: App.localeRes("Basic Information"),
                                    layout: {
                                        type: "vbox",
                                        align: "strech"
                                    },
                                    defaults: {
                                        width: 380
                                    },
                                    bodyPadding: 20,
                                    items: [
                                        {
                                            xtype: "hidden",
                                            name: "id"
                                        },
                                        {
                                            xtype: "hidden",
                                            name: "versionId"
                                        },
                                        {
                                            xtype: "hidden",
                                            name: "companyId",
                                            value: 1
                                        },
                                        {
                                            xtype: "textfield",
                                            name: "username",
                                            fieldLabel: App.localeRes("User Name"),
                                            allowBlank: false,
                                            minLength: 3,
                                            maxLength: 32
                                        },
                                        {
                                            xtype: 'button',
                                            text: App.localeRes('Reset Password'),
                                            hidden: !me.params.id,
                                            margin: 4,
                                            handler: function(button, event){
                                                Ext.Ajax.request({
                                                    url: App.url("/user/reset-password"),
                                                    params:{
                                                        userId: me.down('#infoForm').getForm().getValues().id
                                                    },
                                                    success: function(response, opts) {
                                                        var result = Ext.decode(response.responseText);
                                                        App.showInfo('New Password: '+result.data);
                                                        me.up('window').loadWindow();
                                                    },
                                                    failure: function(response, opts) {},
                                                    scope: this
                                                });
                                            }
                                        },
                                        {
                                            xtype: "fieldcontainer",
                                            fieldLabel: App.localeRes("Name"),
                                            layout: {
                                                type: "hbox"
                                            },
                                            items: [
                                                {
                                                    xtype: "textfield",
                                                    name: "firstname",
                                                    emptyText: App.localeRes("first name"),
                                                    maxLength: 45,
                                                    flex: 10
                                                },
                                                {
                                                    xtype: "container",
                                                    flex: 1
                                                },
                                                {
                                                    xtype: "textfield",
                                                    name: "lastname",
                                                    emptyText: App.localeRes("last name"),
                                                    maxLength: 30,
                                                    flex: 10
                                                }
                                            ]
                                        },
                                        {
                                            xtype: "textfield",
                                            name: "fullname",
                                            fieldLabel: App.localeRes("Full Name"),
                                            allowBlank: false,
                                            maxLength: 90,
                                            listeners: {
                                                focus: function(field, e, opts) {
                                                    if (!field.getValue()) {
                                                        var firstname = me.down("field[name=firstname]").getValue(),
                                                            lastname = me.down("field[name=lastname]").getValue();
                                                        field.setValue(Ext.String.trim(firstname + " " + lastname));
                                                    }
                                                }
                                            }
                                        },
                                        {
                                            xtype: "localeCombo",
                                            name: "locale",
                                            value: 'en',
                                            hidden: true
                                        },
                                        // {
                                        //     xtype: 'deptCombo',
                                        //     name: 'deptId',
                                        //     editable: true
                                        // },
                                        {
                                            xtype: "textfield",
                                            name: "title",
                                            fieldLabel: App.localeRes("Title"),
                                            maxLength: 60
                                        },
                                        {
                                            xtype: "textfield",
                                            name: "email",
                                            fieldLabel: App.localeRes("Email"),
                                            vtype: "email",
                                            maxLength: 120
                                        },
                                        {
                                            xtype: "fieldcontainer",
                                            fieldLabel: App.localeRes("Phone"),
                                            layout: {
                                                type: "hbox"
                                            },
                                            items: [
                                                {
                                                    xtype: "textfield",
                                                    name: "phone1",
                                                    emptyText: App.localeRes("Phone 1"),
                                                    selectOnFocus: true,
                                                    maxLength: 30,
                                                    flex: 10
                                                },
                                                {
                                                    xtype: "container",
                                                    flex: 1
                                                },
                                                {
                                                    xtype: "textfield",
                                                    name: "phone2",
                                                    emptyText: App.localeRes("Phone 2"),
                                                    selectOnFocus: true,
                                                    maxLength: 30,
                                                    flex: 10
                                                }
                                            ]
                                        },
                                        {
                                            xtype: "textarea",
                                            name: "remarks",
                                            fieldLabel: App.localeRes("Remarks"),
                                            grow: true,
                                            growMax: 150,
                                            selectOnFocus: false,
                                            maxLength: 600
                                        },
                                        {
                                            xtype: "checkbox",
                                            name: "locked",
                                            fieldLabel: App.localeRes("Block")
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            xtype: "grid",
                            flex: 1,
                            itemId: "groupGrid",
                            margin: "20px 10px 10px 10px",
                            title: App.localeRes("Group"),
                            collapsible: true,
                            store: Ext.create("App.store.GroupStore", {}),
                            columns: [
                                {
                                    xtype: 'checkcolumn',
                                    dataIndex: 'v',
                                    text: '',
                                    menuDisabled: true,
                                    width: 50
                                },
                                {
                                    xtype: "gridcolumn",
                                    dataIndex: "name",
                                    text: App.localeRes("Name"),
                                    flex: 3
                                }
                            ],
                            listeners: {
                                added: function(panel, parent, pos, opts) {
                                    this.getStore().load();
                                }
                            }
                        }
                    ]
                },
                {
                    title: App.localeRes("User Authority"),
                    iconCls: "x-fa fa-shield",
                    layout: "fit",
                    tabIndex: 1,
                    itemId: "secondTab",
                    items: [
                        {
                            xtype: "container",
                            layout: {
                                type: "hbox",
                                align: "stretch"
                            },
                            width: "100%",
                            defaults: {
                                style: {
                                    margin: "5px"
                                }
                            },
                            items: [
                                {
                                    xtype: "userAuthGridLeft",
                                    title: App.localeRes("Authority"),
                                    flex: 1
                                },
                                {
                                    xtype: "userAuthGrid",
                                    title: App.localeRes("Selected Authority"),
                                    flex: 1,
                                    params: me.params
                                }
                            ]
                        }
                    ]
                }
            ],
            dockedItems: [
                {
                    xtype: "toolbar",
                    itemId: "bottomtoolbar",
                    dock: "bottom",
                    ui: "tools",
                    margin: 8,
                    height: 42,
                    padding: "0px 30px 0px 30px",
                    items: [
                        // {
                        //     iconCls: "x-fa fa-chevron-circle-left",
                        //     weight: -20,
                        //     handler: function(button) {
                        //         var tabIndex = me.getActiveTab().tabIndex;
                        //         tabIndex -= 1;
                        //         me.setActiveTab(tabIndex);
                        //     }
                        // },
                        // {
                        //     iconCls: "x-fa fa-chevron-circle-right",
                        //     weight: -10,
                        //     handler: function(button) {
                        //         var tabIndex = me.getActiveTab().tabIndex;
                        //         tabIndex += 1;
                        //         me.setActiveTab(tabIndex);
                        //     }
                        // },
                        "->",
                        {
                            text:  App.localeRes('Save'),
                            ui: "blue",
                            handler: me.onSaveBtnClick,
                            margin: "2px 10px 0px 0px",
                            scope: me
                        }
                        // {
                        //     text: "Save As New",
                        //     ui: "blue",
                        //     handler: me.onSaveAsBtnClick,
                        //     scope: me
                        // }
                    ]
                }
            ]
        });

        me.callParent(arguments);
    }
});

// Locale Combo
Ext.define("App.view.LocaleCombo", {
    extend: "Ext.form.field.ComboBox",
    alias: "widget.localeCombo",

    fieldLabel: App.localeRes("Locale"),
    editable: false,
    displayField: "text",
    valueField: "value",

    //tpl: '<tpl for="."><div class="x-boundlist-item">{text}</div></tpl>',

    initComponent: function() {
        var me = this;
        if (!me.store) me.store = Ext.create("App.store.LocaleStore");
        me.callParent(arguments);
    }
});
