
var oDateGrabReport1 = new sap.m.DatePicker({width: "100%",displayFormat: "dd-MMM-yyyy",valueFormat: "dd-MMM-yyyy"});
var oDateGrabReport2 = oDateGrabReport1.clone();
var oDateGrabReport3 = oDateGrabReport1.clone();
var oDateGrabReport4 = oDateGrabReport1.clone();

var oDateGrabReport5 = oDateGrabReport1.clone();
var oDateGrabReport6 = oDateGrabReport1.clone();
var oDateGrabReport7 = oDateGrabReport1.clone();
var oDateGrabReport8 = oDateGrabReport1.clone();

var oDateGrabReport9 = oDateGrabReport1.clone();
var oDateGrabReport10 = oDateGrabReport1.clone();
var oDateGrabReport11 = oDateGrabReport1.clone();
var oDateGrabReport12 = oDateGrabReport1.clone();

var oDateGrabReport13 = oDateGrabReport1.clone();
var oDateGrabReport14 = oDateGrabReport1.clone();

function formatCustomDate(dateStr, addOneDay = false) {
    // Map of month abbreviations to month numbers
    const months = {
      Jan: 0, Feb: 1, Mar: 2, Apr: 3,
      May: 4, Jun: 5, Jul: 6, Aug: 7,
      Sep: 8, Oct: 9, Nov: 10, Dec: 11
    };
  
    const [day, monthAbbr, year] = dateStr.split("-");
    const monthIndex = months[monthAbbr];
  
    if (monthIndex === undefined) {
      throw new Error(`Invalid month abbreviation: ${monthAbbr}`);
    }
  
    // Create JS Date object
    const dateObj = new Date(parseInt(year), monthIndex, parseInt(day));
  
    // Add 1 day if required
    if (addOneDay) {
      dateObj.setDate(dateObj.getDate() + 1);
    }
  
    // Convert to desired format
    const yyyy = dateObj.getFullYear();
    const mm = String(dateObj.getMonth() + 1).padStart(2, '0');
    const dd = String(dateObj.getDate()).padStart(2, '0');
  
    return `${yyyy}-${mm}-${dd} 00:00:00.0000000 +00:00`;
  }

  
var secondRowReport = new sap.ui.layout.BlockLayoutRow({
    content: [
        new sap.ui.layout.BlockLayoutCell({width: 1,titleAlignment:"Center",title: oBundle.getText("Inspection_Detail"),
            content: [
                new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                    items: [ new sap.m.Label({required: true, width:"100%",text: oBundle.getText("Start_Date")}),
                            new sap.m.Label({width:"20px",text: ""}),oDateGrabReport5]
                }),
                new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                    items: [new sap.m.Label({required: true, text: oBundle.getText("End_Date")}),
                            new sap.m.Label({width:"20px",text: ""}),oDateGrabReport6]
                }),
                new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                    items: [
                        new sap.m.Button({width:"100%",text:oBundle.getText("Excel_Export"),icon: "sap-icon://excel-attachment",
                            press: function () {
                               
                                    var startDate = oDateGrabReport5.getValue();
                                    var endDate = oDateGrabReport6.getValue();
                                    
                                    if (!nullCheckAll(startDate) || !nullCheckAll(endDate) || !oDateGrabReport5.isValidValue() || !oDateGrabReport6.isValidValue()) {
                                        sap.m.MessageBox.error(oBundle.getText("Select_Valid_Start_and_End_Date"));
                                        return;
                                    }else{

                                        const diffMs = new Date(endDate) - new Date(startDate);
                                        const diffDays = diffMs / (86400000);
                                        if (diffDays > 31) {
                                            sap.m.MessageBox.error("You can pull data for a maximum of 30 days only.");
                                            return;
                                        }

                                        busyDialogGetData.open();
                                        var changedStart = formatCustomDate(startDate);
                                        var changedEnd = formatCustomDate(endDate,true);
                                        reportInspectionData(changedStart,changedEnd);;
                                    }


                               
                            }
                        })]
                })
            ]
        }),
        new sap.ui.layout.BlockLayoutCell({width: 1,titleAlignment:"Center",title: oBundle.getText("Inspection_Summary"),
            content: [
                new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                    items: [ new sap.m.Label({required: true, width:"100%",text: oBundle.getText("Start_Date")}),
                            new sap.m.Label({width:"20px",text: ""}),oDateGrabReport7]
                }),
                new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                    items: [new sap.m.Label({required: true, text: oBundle.getText("End_Date")}),
                            new sap.m.Label({width:"20px",text: ""}),oDateGrabReport8]
                }),
                new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                    items: [
                        new sap.m.Button({width:"100%",text:oBundle.getText("Excel_Export"),icon: "sap-icon://excel-attachment",
                            press: function () {
                                var startDate = oDateGrabReport7.getValue();
                                var endDate = oDateGrabReport8.getValue();
                                
                                if (!nullCheckAll(startDate) || !nullCheckAll(endDate) || !oDateGrabReport7.isValidValue() || !oDateGrabReport8.isValidValue()) {
                                    sap.m.MessageBox.error(oBundle.getText("Select_Valid_Start_and_End_Date"));
                                    return;
                                }else{

                                    const diffMs = new Date(endDate) - new Date(startDate);
                                    const diffDays = diffMs / (86400000);
                                    if (diffDays > 31) {
                                        sap.m.MessageBox.error("You can pull data for a maximum of 30 days only.");
                                        return;
                                    }

                                    busyDialogGetData.open();
                                    var changedStart = formatCustomDate(startDate);
                                    var changedEnd = formatCustomDate(endDate,true);
                                    reportInspectionItemsData(changedStart,changedEnd);

                                }
                            }
                        })]
                })
            ]
        })
        
    ]
});
var thirdRowReport = new sap.ui.layout.BlockLayoutRow({
    content: [
        new sap.ui.layout.BlockLayoutCell({width: 1,titleAlignment:"Center",title: oBundle.getText("CP_Attendance"),
            content: [
                new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                    items: [ new sap.m.Label({required: true, width:"100%",text: oBundle.getText("Start_Date")}),
                            new sap.m.Label({width:"20px",text: ""}),oDateGrabReport9]
                }),
                new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                    items: [new sap.m.Label({required: true, text: oBundle.getText("End_Date")}),
                            new sap.m.Label({width:"20px",text: ""}),oDateGrabReport10]
                }),
                new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                    items: [
                        new sap.m.Button({width:"100%",text:oBundle.getText("Excel_Export"),icon: "sap-icon://excel-attachment",
                            press: function () {
                               
                                    var startDate = oDateGrabReport9.getValue();
                                    var endDate = oDateGrabReport10.getValue();
                                    
                                    if (!nullCheckAll(startDate) || !nullCheckAll(endDate) || !oDateGrabReport5.isValidValue() || !oDateGrabReport6.isValidValue()) {
                                        sap.m.MessageBox.error(oBundle.getText("Select_Valid_Start_and_End_Date"));
                                        return;
                                    }else{

                                        const diffMs = new Date(endDate) - new Date(startDate);
                                        const diffDays = diffMs / (86400000);
                                        // if (diffDays > 31) {
                                        //     sap.m.MessageBox.error("You can pull data for a maximum of 30 days only.");
                                        //     return;
                                        // }

                                        busyDialogGetData.open();
                                        var changedStart = formatCustomDate(startDate);
                                        var changedEnd = formatCustomDate(endDate,true);
                                        reportInspectionSchedule(changedStart,changedEnd);;
                                    }


                               
                            }
                        })]
                })
            ]
        }),
        new sap.ui.layout.BlockLayoutCell({width: 1,titleAlignment:"Center",title:"",// oBundle.getText("Workorder Status Count"),
            content: [
                // new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                //     items: [ new sap.m.Label({required: true, width:"100%",text: oBundle.getText("Start_Date")}),
                //             new sap.m.Label({width:"20px",text: ""}),oDateGrabReport11]
                // }),
                // new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                //     items: [new sap.m.Label({required: true, text: oBundle.getText("End_Date")}),
                //             new sap.m.Label({width:"20px",text: ""}),oDateGrabReport12]
                // }),
                // new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                //     items: [
                //         new sap.m.Button({width:"100%",text:oBundle.getText("Excel_Export"),icon: "sap-icon://excel-attachment",
                //             press: function () {
                               
                //                     var startDate = oDateGrabReport11.getValue();
                //                     var endDate = oDateGrabReport12.getValue();
                                    
                //                     if (!nullCheckAll(startDate) || !nullCheckAll(endDate) || !oDateGrabReport5.isValidValue() || !oDateGrabReport6.isValidValue()) {
                //                         sap.m.MessageBox.error(oBundle.getText("Select_Valid_Start_and_End_Date"));
                //                         return;
                //                     }else{

                //                         const diffMs = new Date(endDate) - new Date(startDate);
                //                         const diffDays = diffMs / (86400000);
                //                         if (diffDays > 31) {
                //                             sap.m.MessageBox.error("You can pull data for a maximum of 30 days only.");
                //                             return;
                //                         }

                //                         busyDialogGetData.open();
                //                         var changedStart = formatCustomDate(startDate);
                //                         var changedEnd = formatCustomDate(endDate,true);
                //                         reportWorkorderStatus(changedStart,changedEnd);;
                //                     }


                               
                //             }
                //         })]
                // })
            ]
        }),
        
    ]
});
var grabReportForm1 =  new sap.ui.layout.BlockLayout({
    background: sap.ui.layout.BlockBackgroundType.Dashboard,
    content: [
        new sap.ui.layout.BlockLayoutRow({
            content: [
                new sap.ui.layout.BlockLayoutCell({width: 1,titleAlignment:"Center",title: oBundle.getText("Workorder_Detail"),
                    content: [
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [ new sap.m.Label({required: true, width:"100%",text: oBundle.getText("Start_Date")}),
                                    new sap.m.Label({width:"20px",text: ""}),oDateGrabReport1]
                        }),
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [new sap.m.Label({required: true, text: oBundle.getText("End_Date")}),
                                    new sap.m.Label({width:"20px",text: ""}),oDateGrabReport2]
                        }),
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [
                                new sap.m.Button({width:"100%",text:oBundle.getText("Excel_Export"),icon: "sap-icon://excel-attachment",
                                    press: function () {
                                       
                                        var startDate = oDateGrabReport1.getValue();
                                        var endDate = oDateGrabReport2.getValue();
                                        
                                        if (!nullCheckAll(startDate) || !nullCheckAll(endDate) || !oDateGrabReport1.isValidValue() || !oDateGrabReport2.isValidValue()) {
                                            sap.m.MessageBox.error(oBundle.getText("Select_Valid_Start_and_End_Date"));
                                            return;
                                        }else{
                                            const diffMs = new Date(endDate) - new Date(startDate);
                                            const diffDays = diffMs / (86400000);
                                            if (diffDays > 31) {
                                                sap.m.MessageBox.error("You can pull data for a maximum of 30 days only.");
                                                return;
                                            }
                                            workorderDetailAPi(startDate,endDate);
                                        }
                                    }
                                })]
                        })
                    ]
                }),
                new sap.ui.layout.BlockLayoutCell({width: 1,titleAlignment:"Center",title: oBundle.getText("Workorder Detail Supplier"),
                    content: [
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [ new sap.m.Label({required: true, width:"100%",text: oBundle.getText("Start_Date")}),
                                    new sap.m.Label({width:"20px",text: ""}),oDateGrabReport13]
                        }),
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [new sap.m.Label({required: true, text: oBundle.getText("End_Date")}),
                                    new sap.m.Label({width:"20px",text: ""}),oDateGrabReport14]
                        }),
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [
                                new sap.m.Button({width:"100%",text:oBundle.getText("Excel_Export"),icon: "sap-icon://excel-attachment",
                                    press: function () {
                                       
                                        var startDate = oDateGrabReport13.getValue();
                                        var endDate = oDateGrabReport14.getValue();
                                        
                                        if (!nullCheckAll(startDate) || !nullCheckAll(endDate) || !oDateGrabReport13.isValidValue() || !oDateGrabReport14.isValidValue()) {
                                            sap.m.MessageBox.error(oBundle.getText("Select_Valid_Start_and_End_Date"));
                                            return;
                                        }else{
                                            const diffMs = new Date(endDate) - new Date(startDate);
                                            const diffDays = diffMs / (86400000);
                                            if (diffDays > 31) {
                                                sap.m.MessageBox.error("You can pull data for a maximum of 30 days only.");
                                                return;
                                            }
                                            workorderDetailSupplierAPi(startDate,endDate);
                                        }                  
                                    }
                                })]
                        })
                    ]
                }),
                new sap.ui.layout.BlockLayoutCell({width: 1,titleAlignment:"Center",title: oBundle.getText("Workorder_Summary"),
                    content: [
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [ new sap.m.Label({required: true, width:"100%",text: oBundle.getText("Start_Date")}),
                                    new sap.m.Label({width:"20px",text: ""}),oDateGrabReport3]
                        }),
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [new sap.m.Label({required: true, text: oBundle.getText("End_Date")}),
                                    new sap.m.Label({width:"20px",text: ""}),oDateGrabReport4]
                        }),
                        new sap.m.FlexBox({alignItems: "Center",justifyContent: "Center",
                            items: [
                                new sap.m.Button({width:"100%",text:oBundle.getText("Excel_Export"),icon: "sap-icon://excel-attachment",
                                    press: function () {
                                        // if(subscription_status != 'Inactive' && subscription_status != 'Cancelled'){
                                        //     funGrabWorkorderReport(2);
                                        // }else{
                                        //     sap.m.MessageBox.error(oBundle.getText("Your_subscription_is_inactive_please_buy_subscription"));
                                        //     return;
                                        // }
                                        var startDate = oDateGrabReport3.getValue();
                                        var endDate = oDateGrabReport4.getValue();
                                        
                                        if (!nullCheckAll(startDate) || !nullCheckAll(endDate) || !oDateGrabReport3.isValidValue() || !oDateGrabReport4.isValidValue()) {
                                            sap.m.MessageBox.error(oBundle.getText("Select_Valid_Start_and_End_Date"));
                                            return;
                                        }else{
                                            const diffMs = new Date(endDate) - new Date(startDate);
                                            const diffDays = diffMs / (86400000);
                                            if (diffDays > 31) {
                                                sap.m.MessageBox.error("You can pull data for a maximum of 30 days only.");
                                                return;
                                            };
                                            funGrabWorkorderReport(2);

                                        }
                                    }
                                })]
                        })
                    ]
                })
                
            ]
        }),
        secondRowReport,
        thirdRowReport
    ]
}).addStyleClass('homeLayout');

if(oxmaint_role == 'Workshop Group Admin' || oxmaint_role == 'Workshop' || oxmaint_role == 'Supplier'){
    secondRowReport.setVisible(false)
}

var grab_report_flag = true;

//---------------------------------------------------------Workorder Detail-------------------------------------------------------
{

    
    async function funGetWorkorderReportDR( startDate, endDate) {
        dbData = [];
        grab_report_flag = true;
    
        // OData-compatible filter syntax
        let filterQuery = `master_email eq '${emailUser}' and createdAt ge '${startDate}' and createdAt le '${endDate}'`;
    
        if (oxmaint_role == "Workshop") {
            filterQuery += ` and workshop_number eq '${oxmaint_workshop_number}'`;
        }else if(oxmaint_role == "Workshop Group Admin"){
            filterQuery += ` and ws_group_number eq '${oxmaint_ws_group_number}'`;
        }
    
        // console.log("Filter Query:", filterQuery); // Debugging the final filter
    
        try {
            for (let i = 0; grab_report_flag; i++) {
                const skipRow = i * 2000;
    
                // console.log(`Fetching batch ${i + 1}, skipping ${skipRow} records`);
    
                const results = await Car_Workorder
                    .where(filterQuery)       
                    .skip(skipRow).take(2000).orderByDescending("createdAt").read();
    
                // console.log(`Batch ${i + 1} fetched, records: ${results.length}`);
    
                dbData.push(...results);
    
                if (results.length < 2000) {
                    grab_report_flag = false;
                    // console.log("No more data to fetch.");
                }
            }
        } catch (error) {
            console.error("Error fetching workorder report:", error.message || error);
        }
    }
    
    
    
    
    
    async function funSetGrabWorkorderReportDR(startDate, endDate, type) {
        await funGetWorkorderReportDR(startDate, endDate);
        if (dbData.length > 0) {
            if(type == 1){
                reportGrabWODetail(dbData);
            }else{
                reportGrabWOSummary(dbData);
            }
        } else {
            sap.m.MessageBox.information(oBundle.getText("No_record_found"));
        }
        busyDialogGetData.close();
    }
    
    function funGrabWorkorderReport(type) {
        const datePickers = type === 1 
            ? [oDateGrabReport1, oDateGrabReport2] 
            : [oDateGrabReport3, oDateGrabReport4];
    
        const [startDatePicker, endDatePicker] = datePickers;
    
        if (!startDatePicker.isValidValue() || !endDatePicker.isValidValue()) {
            return sap.m.MessageBox.error(oBundle.getText("Select_Valid_Start_and_End_Date"));
        }
    
        const startDate = `${startDatePicker.getValue()} 12:00 AM`;
        const endDate = `${endDatePicker.getValue()} 11:59 PM`;
    
        busyDialogGetData.open();
        funSetGrabWorkorderReportDR(startDate, endDate, type);
    }
    
    
    function reportGrabWODetail(aData, type) {

        const xlsHeader = [
            oBundle.getText("Workshop Group Name"), 
            oBundle.getText("City"), 
            oBundle.getText("Work Order Number"),
            oBundle.getText("User Name"),
            oBundle.getText("Created Date"),
            oBundle.getText("Work Order Status"),
            oBundle.getText("Workorder Completed Date"),
            oBundle.getText("License Plate"),
            oBundle.getText("Chassis Number"),
            oBundle.getText("Engine Number"),
            oBundle.getText("Odometer"),
            oBundle.getText("Make Name"),
            oBundle.getText("Model Name"),
            oBundle.getText("Workshop Number"),
            oBundle.getText("Workshop Name"),
            oBundle.getText("Regular Service"),
            oBundle.getText("Service KM"),
            oBundle.getText("Service Needed"),
            oBundle.getText("Part Name"),
            oBundle.getText("Invoice Number"),
            oBundle.getText("Invoice Date"),
            oBundle.getText("GRN Number"),
            oBundle.getText("GRN Date"),
            oBundle.getText("Tax Information"),
            oBundle.getText("Total Part Cost"),
            oBundle.getText("Total Labor Cost"),
            oBundle.getText("VAT Percentage"),
            oBundle.getText("VAT (Amount)"),
            oBundle.getText("Total Wo Cost"),
            oBundle.getText("Final Material Cost"),
            oBundle.getText("Final Labor Cost"),
            oBundle.getText("Tax Value"),
            oBundle.getText("Final Total Cost"),
            oBundle.getText("Note"),
            oBundle.getText("Memo"),
            
            // oBundle.getText("Supplier Invoice Number"),

            // // oBundle.getText("Workshop Estimate"),
            // oBundle.getText("Created By"),
        ];
    
        const dataObject = aData.map(item => ({
            "1": item['ws_group_name'],
            "2": item['city'],
            "3": item['wo_number'],
            "4": item['user_name'],
            "5": item['created_date'],
            "6": item['wo_status'],
            "7": item['completion_date'],
            "8": item['license_number'],
            "9": item['chassis_number'],
            "10": item['engine_number'],
            "11": item['meter_reading'],
            "12": item['make'],
            "13": item['model'],
            "14": item['workshop_number'],
            "15": item['workshop_name'],
            "16": item['regular_service'],
            "17": item['service_km'],
            "18": item['task_type'],
            "19": item['part_name'],
            "20": item['invoice_number'],
            "21": item['invoice_date'],
            "22": item['grn_number'],
            "23": item['grn_date'],
            "24": nullCheckAll(item['tax'])?"Yes":"No",
            "25": item['total_parts_cost'],
            "26": item['labor_item_cost'],
            "27": item['tax'],
            "28": item['tax_value'],
            "29": item['total_cost'],
            "30": item['item_final_material_cost'],
            "31": item['item_total_labor_cost'],
            "32": item['item_tax_value'],
            "33": item['item_final_total_cost'],
            "34": item['note'],
            "35": item['wo_memo']
            

        }));
    
        const createXLSLFormatObj = [xlsHeader, ...dataObject.map(Object.values)];
    
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);
    
        XLSX.utils.book_append_sheet(wb, ws, "Data");
        XLSX.writeFile(wb, "WorkorderDetailExport.xlsx");
        busyDialog.close();
    };

    function reportGrabSupplierWODetail(aData, type) {

        const xlsHeader = [
            oBundle.getText("Workshop Group Name"), 
            oBundle.getText("City"), 
            oBundle.getText("Work Order Number"),
            oBundle.getText("User Name"),
            oBundle.getText("Created Date"),
            oBundle.getText("Work Order Status"),
            oBundle.getText("Workorder Completed Date"),
            oBundle.getText("License Plate"),
            oBundle.getText("Chassis Number"),
            oBundle.getText("Engine Number"),
            oBundle.getText("Odometer"),
            oBundle.getText("Make Name"),
            oBundle.getText("Model Name"),
            oBundle.getText("Workshop Number"),
            oBundle.getText("Workshop Name"),
            oBundle.getText("Regular Service"),
            oBundle.getText("Service KM"),
            oBundle.getText("Service Needed"),
            oBundle.getText("Part Name"),
            oBundle.getText("Supplier Invoice Number"),
            // oBundle.getText("Invoice Date"),
            // oBundle.getText("GRN Number"),
            // oBundle.getText("GRN Date"),
            // oBundle.getText("Tax Information"),
            // oBundle.getText("Total Part Cost"),
            // oBundle.getText("Total Labor Cost"),
            // oBundle.getText("VAT Percentage"),
            // oBundle.getText("VAT (Amount)"),
            oBundle.getText("Total Cost"),
            // oBundle.getText("Final Material Cost"),
            // oBundle.getText("Final Labor Cost"),
            // oBundle.getText("Tax Value"),
            // oBundle.getText("Final Total Cost"),
            oBundle.getText("Note"),
            oBundle.getText("Memo"),
        ];
    
        const dataObject = aData.map(item => ({
            "1": item['ws_group_name'],
            "2": item['city'],
            "3": item['wo_number'],
            "4": item['user_name'],
            "5": item['created_date'],
            "6": item['wo_status'],
            "7": item['completion_date'],
            "8": item['license_number'],
            "9": item['chassis_number'],
            "10": item['engine_number'],
            "11": item['meter_reading'],
            "12": item['make'],
            "13": item['model'],
            "14": item['workshop_number'],
            "15": item['workshop_name'],
            "16": item['regular_service'],
            "17": item['service_km'],
            "18": item['task_type'],
            "19": item['part_name'],
            "20": item['supplier_invoice_number'],
            // "21": item['invoice_date'],
            // "22": item['grn_number'],
            // "23": item['grn_date'],
            // "24": nullCheckAll(item['tax'])?"Yes":"No",
            // "25": item['total_parts_cost'],
            // "26": item['labor_item_cost'],
            // "27": item['tax'],
            // "28": item['tax_value'],
            "21": item['total_cost'],
            // "30": item['item_final_material_cost'],
            // "31": item['item_total_labor_cost'],
            // "32": item['item_tax_value'],
            // "33": item['item_final_total_cost'],
            "22": item['note'],
            "23": item['wo_memo']
            

        }));
    
        const createXLSLFormatObj = [xlsHeader, ...dataObject.map(Object.values)];
    
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);
    
        XLSX.utils.book_append_sheet(wb, ws, "Data");
        XLSX.writeFile(wb, "SupplierWorkorderDetailExport.xlsx");
        busyDialog.close();
    };
    
    function reportGrabWOSummary(aData, type) {

        // console.log(aData)

        const xlsHeader = [
            oBundle.getText("Work Order Number"),
            oBundle.getText("License Plate"),
            oBundle.getText("Workshop Group Name"), 
            oBundle.getText("Workshop Name"),
            oBundle.getText("Created Date"),
            oBundle.getText("Work Order Status"),
            oBundle.getText("Make Name"),
            oBundle.getText("Model Name"),
            oBundle.getText("Part Cost"),
            oBundle.getText("Labor Cost"),
            oBundle.getText("VAT (Amount)"),
            oBundle.getText("Total Wo Cost"),
        ];
    
        const dataObject = aData.map(item => ({
            "1": item['wo_number'],
            "2": item['license_number'],
            "3": item['ws_group_name'],
            "4": item['workshop_name'],
            "5": item['created_date'],
            "6": item['wo_status'],
            "7": item['make'],
            "8": item['model'],
            "9": item['total_parts_cost'],
            "10": item['total_labor_cost'],
            "11": item['tax_value'],
            "12": item['total_wo_cost']
        }));
    
        const createXLSLFormatObj = [xlsHeader, ...dataObject.map(Object.values)];
    
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);
    
        XLSX.utils.book_append_sheet(wb, ws, "Data");
        XLSX.writeFile(wb, "WorkorderSummaryExport.xlsx");
    }

}
//---------------------------------------------------------Workorder Detail-------------------------------------------------------

//--------------------------------------------------------Inspection -------------------------------------------------------
function grabInspectionDetail(aData, type) {

    const xlsHeader = [
        oBundle.getText("Inspection Date"),
        oBundle.getText("Report Number"),
        oBundle.getText("License Number"),
        oBundle.getText("Vehicle Model"),
        oBundle.getText("Chassis Number"),
        oBundle.getText("Engine Number"),
        oBundle.getText("Form Name"),
        oBundle.getText("Vehicle Status"),
        oBundle.getText("Meter Reading"),
        oBundle.getText("Location"),
        oBundle.getText("Inspector ID"),
        oBundle.getText("Inspector Name"),
        oBundle.getText("Inspection Time"),
        oBundle.getText("Repair"),
        oBundle.getText("Replace"),
        oBundle.getText("Repair Note"),
        oBundle.getText("Replace Note"),
        oBundle.getText("Remark"),
        oBundle.getText("Safe To Use"),
        oBundle.getText("Overall Condition"),
        oBundle.getText("Maintenance Required"),
        oBundle.getText("Maintenance Priority"),
        oBundle.getText("PDF URL"),
        oBundle.getText("Workorder")
    ];

    const dataObject = aData.map(item => ({
        "1": item['inspection_date'],
        "2": item['report_number'],
        "3": item['license_number'],
        "4": item['vehicle_model'],
        "5": item['chassis_number'],
        "6": item['engine_number'],
        "7": item['group_name'], // alias as form_name
        "8": item['vehicle_status'],
        "9": item['meter_reading'],
        "10": item['location'],
        "11": item['inspector_id'],
        "12": item['inspector_name'],
        "13": item['inspection_time'],
        "14": item['repair'],
        "15": item['replace'],
        "16": item['repair_note'],
        "17": item['replace_note'],
        "18": item['remark'],
        "19": item['safe_to_use'],
        "20": item['overall_condition'],
        "21": item['maintenance_required'],
        "22": item['maintenance_priority'],
        "23": item['pdf_url'],
        "24": item['workorder']
    }));

    const createXLSLFormatObj = [xlsHeader, ...dataObject.map(Object.values)];

    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);

    XLSX.utils.book_append_sheet(wb, ws, "Inspection Detail");
    XLSX.writeFile(wb, "Inspection_Detail_Export.xlsx");
    busyDialog.close();
};

function grabInspectionSummary(aData, type) {

    const xlsHeader = [
        oBundle.getText("License Number"),
        oBundle.getText("Vehicle Model"),
        oBundle.getText("Task Name"),
        oBundle.getText("Task Type"),
        oBundle.getText("Inspection Note"),
        oBundle.getText("Reported Date"),
        oBundle.getText("Reported By"),
        oBundle.getText("Inspection Number")
    ];

    const dataObject = aData.map(item => ({
        "1": item['license_number'],
        "2": item['vehicle_model'],
        "3": item['task_name'],
        "4": item['task_type'],
        "5": item['inspection_note'],
        "6": item['reported_date'],
        "7": item['reported_by'],
        "8": item['inspection_number']
    }));

    const createXLSLFormatObj = [xlsHeader, ...dataObject.map(Object.values)];

    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);

    XLSX.utils.book_append_sheet(wb, ws, "Inspection Summary");
    XLSX.writeFile(wb, "Inspection_Summary_Export.xlsx");
    busyDialog.close();
}

//--------------------------------------------------------Inspection -------------------------------------------------------


//--------------------------------------------------------Inspection Scheduling Start-------------------------------------------------------
function grabInspectionScheduleDetail(aData){
    console.log(aData)
    const xlsHeader = [
        // oBundle.getText("City Name"),
        // oBundle.getText("Driver Name"),
        // oBundle.getText("Faulty Item Repair"),
        // oBundle.getText("Faulty Item Replace"),
        // oBundle.getText("Inspection Actual Date"),
        // oBundle.getText("Inspection Actual Location"),
        // oBundle.getText("Inspection Booked Date"),
        // oBundle.getText("Inspection Booked Location"),
        // oBundle.getText("Inspection Number"),
        // oBundle.getText("leasing Company Name"),
        // oBundle.getText("license Number"),
        // oBundle.getText("Notes"),
        // oBundle.getText("Overall Condition"),
        // oBundle.getText("Product Category"),
        // oBundle.getText("Vehicle Model"),
        // oBundle.getText("Workshop Name"),
        // oBundle.getText("Workshop Number")
        oBundle.getText("Booking ID"),
        oBundle.getText("Inspection Report Number"),
        oBundle.getText("PDF URL"),
        oBundle.getText("Grab Public Driver ID"),
        oBundle.getText("Driver Name"),
        oBundle.getText("Start Date"),
        oBundle.getText("Due Date"),
        oBundle.getText("Scheduled Date"),
        oBundle.getText("Status"),
        oBundle.getText("Checkpoint Location"),
        oBundle.getText("City"),
        oBundle.getText("Driver Type")
        // oBundle.getText("Handover Date")
    ];

    const dataObject = aData.map(item => ({
        // "1":  item['city_name'],
        // "2":  item['driver_name'],
        // "3":  item['faulty_item_repair'],
        // "4":  item['faulty_item_replace'],
        // "5":  item['inspection_actual_date'],
        // "6":  item['inspection_actual_location'],
        // "7":  item['inspection_booked_date'],
        // "8":  item['inspection_booked_location'],
        // "9":  item['inspection_report_number'],
        // "10": item['leasing_company_name'],
        // "11": item['license_number'],
        // "12": item['notes'],
        // "13": item['overall_condition'],
        // "14": item['product_category'],
        // "15": item['vehicle_model'],
        // "16": item['workshop_name'],
        // "17": item['workshop_number']
        
        "1": item['booking_id'] || '-',
        "2": item['inspection_report_number'],
        "3": item['pdf_url'],
        "4": item['jaya_driver_id'],
        "5": item['driver_name'],
        "6": item['start_date'],
        "7": item['due_date'],
        "8": item['scheduled_date'],
        "9": item['status'],
        "10": item['checkpoint_location'],
        "11": item['city_name'],
        "12": item['driver_type'],
        // "1": item[''],

    }));

    const createXLSLFormatObj = [xlsHeader, ...dataObject.map(Object.values)];

    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);

    XLSX.utils.book_append_sheet(wb, ws, "Inspection Detail");
    XLSX.writeFile(wb, "CP_Attendance_Export.xlsx");
    busyDialog.close();
    
}
//--------------------------------------------------------Inspection Scheduling END-------------------------------------------------------
function grabWorkorderStatusExcel(aData){

    const xlsHeader = [
        oBundle.getText("grand_total_per_location"),
        oBundle.getText("Location"),
        oBundle.getText("Month"),
        oBundle.getText("Wo Status"),
        oBundle.getText("Workorder Count"),
        oBundle.getText("Year"),
    ];

    const dataObject = aData.map(item => ({
        "1":  item['grand_total_per_location'],
        "2":  item['location'],
        "3":  item['month'],
        "4":  item['wo_status'],
        "5":  item['workorder_count'],
        "6":  item['year'],
    }));

    const createXLSLFormatObj = [xlsHeader, ...dataObject.map(Object.values)];

    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);

    XLSX.utils.book_append_sheet(wb, ws, "Workorder_Status_Count");
    XLSX.writeFile(wb, "Inspection_Summary_Export.xlsx");
    busyDialog.close();
    
}

