// var Supplier_Master = client.getTable('Supplier_Master');


var oTable4WSupplier = new sap.m.Table({
    growing: true,
    noDataText:oBundle.getText("No_Data"),
    growingTriggerText:oBundle.getText("More"),
    sticky:[sap.m.Sticky.ColumnHeaders,sap.m.Sticky.HeaderToolbar,sap.m.Sticky.InfoToolbar],
    growingThreshold: 25,
    growingScrollToLoad : false,
    columns: [
            new sap.m.Column({width:"100px",header: new sap.m.Label({text: oBundle.getText("Action"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Supplier_Number"),design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",sortIndicator:"Descending"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Supplier_Name"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("City"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Address"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Tax_Information"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Tax_Percentage"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
    ],
    headerToolbar:new sap.m.OverflowToolbar({
        content: [   
            new sap.m.Button({ 
                id:"createSupplierBtnID",
                text: oBundle.getText("Create_Supplier"), 
                type:sap.m.ButtonType.Emphasized,
                icon: sap.ui.core.IconPool.getIconURI("add"), 
                press: function(){
                    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('create_supplier') != -1)){
                        addUpdate4WSupplier(1);//Cretae
                    }else{
                        sap.m.MessageToast.show("Create Access not provided.");
                    }
                } 
            }),
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {
                    var oBinding = oTable4WSupplier.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [
                        new sap.ui.model.Filter("supplier_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("supplier_name", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("city", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("address", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("tax_information", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("tax_percentage", sap.ui.model.FilterOperator.Contains, searchStr),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
        
            }),
        ]
    })
});

var supplier4WTemplate = new sap.m.ColumnListItem({
    cells: [
        new sap.m.Button({
            type: "Emphasized",
            icon: "sap-icon://action",
            text: oBundle.getText("Action"),
            press: function (event) {
                var model = this.getModel();
                var path = event.getSource().getBindingContext().getPath();
                var obj = model.getProperty(path);
                displayMenu4WSupplier(event,obj);
            
            }
        }),
        new sap.m.Label({wrapping:true,text: "{supplier_number}"}),
        new sap.m.Label({wrapping:true,text: "{supplier_name}"}),
        new sap.m.Label({wrapping:true,text: "{status}"}),
        new sap.m.Label({wrapping:true,text: "{city}"}),
        new sap.m.Label({wrapping:true,text: "{address}"}),
        new sap.m.Label({wrapping:true,text: "{tax_information}"}),
        new sap.m.Label({wrapping:true,text: "{tax_percentage}"}),
    ]
});
  
//Display Action 
function displayMenu4WSupplier(event,obj){

    var oMenu = new sap.m.Menu({
        items: [
            new sap.m.MenuItem({visible:false, icon: "sap-icon://show",text: oBundle.getText("View"),key: "0"}),
            new sap.m.MenuItem({visible:false, icon: "sap-icon://edit",text: oBundle.getText("Update"),key: "1"}),
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "0") { 
                if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('view_supplier') != -1)){
                    addUpdate4WSupplier(3, obj);
                }else{
                    sap.m.MessageToast.show("View Access not provided.");
                };
            } else if (oItem == "1") {
                // if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_supplier') != -1)){
                    addUpdate4WSupplier(2, obj);
                // }else{
                //     sap.m.MessageToast.show("Modify Access not provided.");
                // }
                
            } else if (oItem == "2"){
                var oDialog = new sap.m.Dialog({
                    title: oBundle.getText("Alert"),
                    state: sap.ui.core.ValueState.Error,
                    content: [new sap.m.Label({ text: oBundle.getText("Sure_You_want_to_delete") })],
                    buttons: [
                                new sap.m.Button({text: oBundle.getText("Delete"),icon: "sap-icon://delete",
                                    press: function () {
                                        busyDialog.open();
                                        Supplier_Master.del({ id: obj['id'] }).done(function () {
                                            get4WSupplier();
                                            addHistoryTableData(obj['supplier_number'],"Delete","Supplier");
                                            oDialog.close();
                                            busyDialog.close();
                                        });
                                    }
                                }),
                                new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
                                    press: function () {
                                        oDialog.close();
                                    }
                                })
                            ]
                }).open();
            }
        }
    });
    if(hvi_default_type == '2'){
        oMenu.getItems()[2].setVisible(false)
    };

    //View
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('view_supplier') != -1)){
        oMenu.getItems()[0].setVisible(true);
    };

    //Modify
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_supplier') != -1)){
        oMenu.getItems()[1].setVisible(true);
    };
    //Delete
    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('delete_supplier') != -1)){
        getDeleteMenu(oMenu,"2");
    };
    oMenu.openBy(event.getSource());
};



//Add Update View
function addUpdate4WSupplier(src, obj){

    
    var reqLbl = new sap.m.Label({ required: true });
    var oLbl = new sap.m.Label({ });


    var o4WSupplierField1 = new sap.m.Input({});
    var o4WSupplierField2 = new sap.m.Input({
        minLength:1,
        maxLength: 50,
        liveChange: function (oEvent) {
            var sValue = oEvent.getParameter("value");
            if (sValue.length == 50) {
                sap.m.MessageToast.show("Maximum_character_limit_of_Supplier_Name_" + 50 + " reached.");
            }
        }
    });
    var o4WSupplierField3 = cityCB.clone();
    o4WSupplierField3.addEventDelegate({onAfterRendering: function(e) {o4WSupplierField3.$().find("input").attr("readonly", true);}});
    o4WSupplierField3.attachChange(function (oEvent) {
        let enteredValue = oEvent.getParameter("value");
        let isValid = o4WSupplierField3.getItems().some(item => item.getText() === enteredValue);

        if (!isValid) {
            sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_City")+" "+ oBundle.getText("Required"));
            o4WSupplierField3.setValue(oBundle.getText("BALI"));
        }
    });
    var o4WSupplierField4 = new sap.m.TextArea({width:"100%",height:"100px",rows : 4, wrapping : sap.ui.core.Wrapping.on,
        minLength:1,
        maxLength: 200,
        liveChange: function (oEvent) {
            var sValue = oEvent.getParameter("value");
            if (sValue.length == 200) {
                sap.m.MessageToast.show("Maximum character limit of Address " + 200 + " reached.");
            }
        }
    });
    // new sap.m.Input({
        // minLength:1,
        // maxLength: 200,
        // liveChange: function (oEvent) {
        //     var sValue = oEvent.getParameter("value");
        //     if (sValue.length == 200) {
        //         sap.m.MessageToast.show("Maximum character limit of Address " + 200 + " reached.");
        //     }
        // }
    // });
    var o4WSupplierField5 = new  sap.m.ComboBox({
        value:oBundle.getText("No"),
        items:[    
            new sap.ui.core.ListItem({key:"1",text:oBundle.getText("Yes")}),
            new sap.ui.core.ListItem({key:"2",text:oBundle.getText("No")}),
        ],
        change: function (oEvent) {
            let enteredValue = oEvent.getParameter("value");
            let isValid = o4WSupplierField5.getItems().some(item => item.getText() === enteredValue);
            
            if(o4WSupplierField5.getSelectedKey() == "1"){
                o4WSupplierField6.setEnabled(true);
                o4WSupplierField6.setValue("0");
            }else{
                o4WSupplierField6.setEnabled(false);
                o4WSupplierField6.setValue("0");
            }
            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_Tax_Information"));
                o4WSupplierField5.setValue(oBundle.getText("No"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {o4WSupplierField5.$().find("input").attr("readonly", true);}});

    var o4WSupplierField6 = new sap.m.Input({
        enabled:false,
        value:"0",
        minLength:0, 
        maxLength: 100,
        type:'Number',
        liveChange: function (oEvent) {
            var sValue = oEvent.getParameter("value");
            if (sValue.length == 100) {
                sap.m.MessageToast.show("Maximum character limit of  Tax Percentage " + 100 + " reached.");
            }
        }
    });
    var o4WSupplierField7 = new sap.m.ComboBox({
        value:oBundle.getText("Active"),
        items:[    
            new sap.ui.core.ListItem({key:"Active",text:oBundle.getText("Active")}),
            new sap.ui.core.ListItem({key:"Inactive",text:oBundle.getText("Inactive")}),
        ],
        change: function (oEvent) {
            let enteredValue = oEvent.getParameter("value");
            let isValid = o4WSupplierField7.getItems().some(item => item.getText() === enteredValue);
    
            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list_for_Status"));
                o4WSupplierField7.setValue(oBundle.getText("Active"));
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {o4WSupplierField7.$().find("input").attr("readonly", true);}});


    var oSupplierForm4w =  new sap.ui.layout.form.Form({
        editable: true,
        layout: new sap.ui.layout.form.ResponsiveGridLayout(),
        formContainers: [
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Supplier_Number")),fields: [o4WSupplierField1]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Supplier_Name")),fields: [o4WSupplierField2]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("City")),fields: [o4WSupplierField3]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Address")),fields: [o4WSupplierField4]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Tax_Information")),fields: [o4WSupplierField5]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Tax_Percentage")),fields: [o4WSupplierField6]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Status")),fields: [o4WSupplierField7]}),
                    
                ]
            }),
        ]
    });


    var add4WSupplierBtn = new sap.m.Button({ 
        text: oBundle.getText("Create"), 
        icon: "sap-icon://add",
        press: function(){
            let supplier_number = o4WSupplierField1.getValue();
            let supplier_name = o4WSupplierField2.getValue();
            let city = o4WSupplierField3.getValue();
            let address = o4WSupplierField4.getValue();
            let tax_information = o4WSupplierField5.getValue();
            let tax_percentage = o4WSupplierField6.getValue();
            let status = o4WSupplierField7.getValue();


            
            if (validation( supplier_number, oBundle.getText("Supplier_Number"))) { return; }
            if (validation( supplier_name, oBundle.getText("Supplier_Name"))) { return; }
            if (validation( city, oBundle.getText("City"))) { return; }
            if (validation( address, oBundle.getText("Address"))) { return; }
            if (validation( tax_information, oBundle.getText("Tax_Information"))) { return; }
            if (validateNumber( tax_percentage, oBundle.getText("Tax_Percentage"))) { return; }

            if(city == "Select City"){
                sap.m.MessageBox.error(oBundle.getText("Please_Select_City")); return;
            }

            // return;
            busyDialog.open();
            var current_date = getIndonesianTime();

            let insertItems = {
                master_email:emailUser,
                supplier_number:supplier_number,supplier_name:supplier_name, city:city, address:address,
                tax_information:tax_information, tax_percentage:tax_percentage,status:status,
                created_date:current_date, created_by:operatedID
            };


            Supplier_Master.insert(insertItems).done(function () {
                get4WSupplier();
                addHistoryTableData(insertItems['supplier_number'],"Insert","Supplier");
                busyDialog.close();
                oDialog.close();
            }, failure);
        }
    });
    var update4WSupplierBtn = new sap.m.Button({ 
        visible:false,
        text: oBundle.getText("Update"), 
        icon: "sap-icon://edit",
        press: function(){
            let supplier_number = o4WSupplierField1.getValue();
            let supplier_name = o4WSupplierField2.getValue();
            let city = o4WSupplierField3.getValue();
            let address = o4WSupplierField4.getValue();
            let tax_information = o4WSupplierField5.getValue();
            let tax_percentage = o4WSupplierField6.getValue();
            let status = o4WSupplierField7.getValue();


            if (validation( supplier_number, oBundle.getText("Supplier_Number"))) { return; }
            if (validation( supplier_name, oBundle.getText("Supplier_Name"))) { return; }
            if (validation( city, oBundle.getText("City"))) { return; }
            if (validation( address, oBundle.getText("Address"))) { return; }
            if (validation( tax_information, oBundle.getText("Tax_Information"))) { return; }
            if (validateNumber( tax_percentage, oBundle.getText("Tax_Percentage"))) { return; }

            if(city == "Select City"){
                sap.m.MessageBox.error(oBundle.getText("Please_Select_City")); return;
            }

            // return;
            busyDialog.open();
            var updated_date = getIndonesianTime();

            let updateItems = {
                id:obj['id'],
                supplier_name:supplier_name, city:city, address:address, tax_information:tax_information, tax_percentage:tax_percentage,status:status,
                updated_date:updated_date, updated_by:operatedID
            };

            Supplier_Master.update(updateItems).done(function () {
                get4WSupplier();
                addHistoryTableData(obj['supplier_number'],"Update","Supplier",obj,updateItems);
                busyDialog.close();
                oDialog.close();
            }, failure);
        }
    });


    let oDialog = new sap.m.Dialog({ contentWidth: "70%", contentHeight: "50%", draggable: true, resizable: true,
        title: oBundle.getText("Add_4W_Supplier"),
        content: [oSupplierForm4w],
        buttons: [add4WSupplierBtn,update4WSupplierBtn,
			new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline",press: function () { oDialog.close();}})
		]
    }).open();

    if(src == 1){
        
        Supplier_Master.where({master_email:emailUser}).take(1).orderByDescending("createdAt").read().done(function (results) {
            if(results.length > 0){
                let latestNumber = results[0]['supplier_number'];
                let numericPart = parseInt(latestNumber.slice(2));  // Extract the numeric part and convert to an integer
                let newsupplierNumber = numericPart + 1;          // Add 1 to the numeric part
                o4WSupplierField1.setValue("SP"+newsupplierNumber);
                o4WSupplierField1.setEnabled(false);
            }else{
                o4WSupplierField1.setValue("SP1001");
            }
        });

        

    }else if(src == 2){
        update4WSupplierBtn.setVisible(true);
        add4WSupplierBtn.setVisible(false);

        oDialog.setTitle("Update Supplier");
        o4WSupplierField1.setValue(obj["supplier_number"]);
        o4WSupplierField1.setEnabled(false);
        o4WSupplierField2.setValue(obj["supplier_name"]);
        o4WSupplierField3.setValue(obj["city"]);
        o4WSupplierField4.setValue(obj["address"]);
        o4WSupplierField5.setValue(obj["tax_information"]);
        o4WSupplierField6.setValue(obj["tax_percentage"]);
        o4WSupplierField7.setValue(obj["status"]);

        if(obj["tax_information"] == 'Yes'){
            o4WSupplierField6.setEnabled(true)
        }else{

            o4WSupplierField6.setValue('0')
            o4WSupplierField6.setEnabled(false)
        }

    }else if(src == 3){
        update4WSupplierBtn.setVisible(false);
        add4WSupplierBtn.setVisible(false);

        oDialog.setTitle("View Supplier");
        o4WSupplierField1.setValue(obj["supplier_number"]);
        o4WSupplierField2.setValue(obj["supplier_name"]);
        o4WSupplierField3.setValue(obj["city"]);
        o4WSupplierField4.setValue(obj["address"]);
        o4WSupplierField5.setValue(obj["tax_information"]);
        o4WSupplierField6.setValue(obj["tax_percentage"]);
        o4WSupplierField7.setValue(obj["status"]);

        o4WSupplierField1.setEnabled(false);
        o4WSupplierField2.setEnabled(false);
        o4WSupplierField3.setEnabled(false);
        o4WSupplierField4.setEnabled(false);
        o4WSupplierField5.setEnabled(false);
        o4WSupplierField6.setEnabled(false);
        o4WSupplierField7.setEnabled(false);
    }
}


var supplier4WJSONData = [];
function get4WSupplier(){
    oTable4WSupplier.setBusy(true);
    Supplier_Master.where({master_email:emailUser}).take(1000).orderByDescending("createdAt").read().done(function (results) {
        
        supplier4WJSONData = results;            

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTable4WSupplier.setModel(oModel);
        oTable4WSupplier.bindItems({ path: "/modelData", template : supplier4WTemplate });
        oTable4WSupplier.setBusy(false);


    })
};


var supplierPage4W = new sap.m.Page("supplier_page_4w", {
    title:oBundle.getText("Create_4W_Supplier"),
    showHeader:true,
    enableScrolling:true,
    content : [oTable4WSupplier] 
}); 