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


var oTable4WApproval = 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("Approval_Level_ID"),design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Tablet",sortIndicator:"Descending"}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Approval_Amount"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Description"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
    ],
    headerToolbar:new sap.m.OverflowToolbar({
        content: [   
           
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {
                    var oBinding = oTable4WApproval.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [
                        new sap.ui.model.Filter("approver_level_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("approval_amount", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("description", sap.ui.model.FilterOperator.Contains, searchStr),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
        
            }),
        ]
    })
});

var approval4WTemplate = 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);
                displayMenu4WApproval(event,obj);
            
            }
        }),
        new sap.m.Label({wrapping:true,text: "{approval_level_id}"}),
        new sap.m.Label({wrapping:true,text: "{approval_amount}"}),
        new sap.m.Label({wrapping:true,text: "{description}"})
    ]
});
  
function displayMenu4WApproval(event,obj){
    
    var oMenu = new sap.m.Menu({
        items: [
            // new sap.m.MenuItem({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: "0"}),
        ],
        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('modify_approval_level') != -1)){
                    addUpdate4WApprover(2, obj); // Update
                }
            } 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();
                //                             oDialog.close();
                //                             busyDialog.close();
                //                         });
                //                     }
                //                 }),
                //                 new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
                //                     press: function () {
                //                         oDialog.close();
                //                     }
                //                 })
                //             ]
                // }).open();
            }
        }
    });
   
     //Modify
     if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('modify_approval_level') != -1)){
         oMenu.getItems()[0].setVisible(true);
     };
   
     // getDeleteMenu(oMenu,"1");
    oMenu.openBy(event.getSource());
}


function addUpdate4WApprover(src,obj){
    
    let reqLbl = new sap.m.Label({ required: true });
    let oLbl = new sap.m.Label({ });

    let o4WApprovalField1 = new sap.m.Input({});
    let o4WApprovalField2 = new sap.m.Input({});
    let o4WApprovalField3 = new sap.m.Input({});

    var oApprovalForm4w =  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("Approval_Level_ID")),fields: [o4WApprovalField1]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Approval_Amount")),fields: [o4WApprovalField2]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Description")),fields: [o4WApprovalField3]}),
                    
                ]
            }),
        ]
    });


    var add4WApprovalBtn = new sap.m.Button({ 
        text: oBundle.getText("Create"), 
        icon: "sap-icon://add",
        press: function(){
            let approval_level_id = o4WApprovalField1.getValue();
            let approval_amount = o4WApprovalField2.getValue();
            let description = o4WApprovalField3.getValue();


            if (validation( approval_level_id, oBundle.getText("Approval_Level_ID"))) { return; }
            if (validation( approval_amount, oBundle.getText("Approval_Amount"))) { return; }
            if (validation( description, oBundle.getText("Description"))) { return; }
            

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

            let insertItems = { master_email:emailUser,
                approval_level_id:approval_level_id, approval_amount:approval_amount, description:description,
                created_date:current_date, created_by:operatedID,approval_type:portal_type_flag
            };


            Approval_Master.insert(insertItems).done(function () {
                get4WApproval();
                addHistoryTableData(insertItems['approval_level_id'],"Insert","Approval");
                busyDialog.close();
                oDialog.close();
            }, failure);
        }
    });
    var update4WApprovalBtn = new sap.m.Button({ 
        visible:false,
        text: oBundle.getText("Update"), 
        icon: "sap-icon://edit",
        press: function(){
            let approval_level_id = o4WApprovalField1.getValue();
            let approval_amount = o4WApprovalField2.getValue();
            let description = o4WApprovalField3.getValue();


            if (validation( approval_level_id, oBundle.getText("Approval_Level_ID"))) { return; }
            if (validateNumber( approval_amount, oBundle.getText("Approval_Amount"))) { return; }
            if (validation( description, oBundle.getText("Description"))) { return; }
            

            let validUpdate = updateApprovalAmount(approval4WJSONData,approval_level_id,approval_amount);
            
            if(validUpdate){

                busyDialog.open();
                var current_date = getIndonesianTime();
    
                let updateItems = {
                    id:obj['id'], approval_amount:approval_amount, description:description,
                    updated_date:current_date, updated_by:operatedID,approval_type:portal_type_flag
                };
    
    
                Approval_Master.update(updateItems).done(function () {
                    get4WApproval();
                    updateTeamApprovalPriceAPI(approval_level_id,approval_amount);
                    addHistoryTableData(obj['approval_level_id'],"Update","Approval",obj,updateItems);
                    busyDialog.close();
                    oDialog.close();
                }, failure);
            }else{
                sap.m.MessageBox.error(oBundle.getText("Approval_amount_must_be_greater_than_all_lower_levels_and_less_than_all_higher_levels"));
                return;
            }
        }
    });


    let oDialog = new sap.m.Dialog({ contentWidth: "25%", contentHeight: "30%", draggable: true, resizable: true,
        title: oBundle.getText("Add_4W_Approver"),
        content: [oApprovalForm4w],
        buttons: [add4WApprovalBtn,update4WApprovalBtn,
			new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline",press: function () { oDialog.close();}})
		]
    }).open();


    if(src == 2){
        update4WApprovalBtn.setVisible(true);
        add4WApprovalBtn.setVisible(false);
        o4WApprovalField1.setEnabled(false);
        oDialog.setTitle(`Update Approver`)

        o4WApprovalField1.setValue(obj['approval_level_id'])
        o4WApprovalField2.setValue(obj['approval_amount'])
        o4WApprovalField3.setValue(obj['description'])
    }
}


// function updateTeamApprovalPriceAPI(approvalLevel,updatedPrice) {

//     busyDialog.open();
//     $.ajax({
//         type: "POST",
//         url: "https://prod-179.westeurope.logic.azure.com:443/workflows/3089d4f46f6a49da9960b50b5f4e0def/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=MnVxdG9n7134xdINgb6ClxSkRbXcR-2u6SdManGlth4",
//         contentType: 'application/json',
//         dataType: 'json',
//         data: JSON.stringify({
//                 "master_email": emailUser,
//                 "approval_level": approvalLevel,
//                 "updated_price": updatedPrice
//         }),
//         success: function (data) {
//             busyDialog.close();
//             sap.m.MessageBox.success(oBundle.getText("Approval_Amount_Updated")
//             ,{title: oBundle.getText("Success")});
//          }
//     });

// }



var approval4WJSONData = [];
function get4WApproval(){
    oTable4WApproval.setBusy(true);
    Approval_Master.where({master_email:emailUser,approval_type:portal_type_flag}).take(10).orderByDescending("createdAt").read().done(function (results) {
        
        approval4WJSONData = results;            
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTable4WApproval.setModel(oModel);
        oTable4WApproval.bindItems({ path: "/modelData", template : approval4WTemplate });
        oTable4WApproval.setBusy(false);

        var approvalAmountsArray = results.map(function (item) {
            return parseInt(item.approval_amount, 10); // Convert to integer
        }).sort(function (a, b) {
            return a - b; // Sort in ascending order
        });
        
        // console.log(approvalAmountsArray);
        
        // sessionStorage.setItem('oxmaint_approval_array', approvalAmountsArray);
        oxmaint_approval_array = approvalAmountsArray;
    })
};


function updateApprovalAmount(approvalLevels, approvalLevelId, newAmount) {
    // Find the level being updated
    const currentLevel = approvalLevels.find(level => level.approval_level_id === approvalLevelId);

    // Get the higher levels (greater than current ID) and lower levels (less than current ID)
    const higherLevels = approvalLevels.filter(level => level.approval_level_id > approvalLevelId);
    const lowerLevels = approvalLevels.filter(level => level.approval_level_id < approvalLevelId);

    // Validate the new amount
    const isValid = 
        lowerLevels.every(level => newAmount > parseFloat(level.approval_amount)) &&
        higherLevels.every(level => newAmount < parseFloat(level.approval_amount));

    if (isValid) {
        // Update the amount
        return true;
        currentLevel.approval_amount = newAmount.toString();
        console.log(`${approvalLevelId} approval amount updated successfully:`, currentLevel);
    } else {
        return false;
        console.error(
            `Validation failed: ${approvalLevelId} amount must be greater than all lower levels and less than all higher levels.`
        );
    }
}





var approvalPage4W = new sap.m.Page("approval_page_4w", {
    title:oBundle.getText("4W_Approver"),
    showHeader:true,
    enableScrolling:true,
    content : [oTable4WApproval] 
}); 