let url = readWebConfig();
let data;
$(document).ready(function () {
  
});


$(function () {
    if ($('#btn-search-by').text().toLowerCase() == 'barcode') {
        arrdata = arrbarcode
    } else if ($('#btn-search-by').text().toLowerCase() == 'name') {
        arrdata = arrname
    } else if ($('#btn-search-by').text().toLowerCase() == 'description') {
        arrdata = arrdesc
    }

    $("#input-search").autocomplete({
        source: arrdata,
        select: function (event, ui) {
            if ($('#btn-search-by').text().toLowerCase() == 'barcode') {
                inventory = data['item'].filter((e) => e['barcode'].toLowerCase().trim() == $("#input-search").val().toLowerCase().trim())
            } else if ($('#btn-search-by').text().toLowerCase() == 'name') {
                inventory = data['item'].filter((e) => e['name'].toLowerCase().trim() == $("#input-search").val().toLowerCase().trim())
            } else if ($('#btn-search-by').text().toLowerCase() == 'description') {
                inventory = data['item'].filter((e) => e['description'].toLowerCase().trim() == $("#input-search").val().toLowerCase().trim())
            }

            if (inventory.length == 0) {
                Swal.fire({
                    icon: "warning",
                    text: "Item Not Found",
                    timer: 1500
                }).then(function () {
                    $('#input-barcode').val('')
                    $('#input-name').val('')
                    $('#input-desc').val('')
                    $('#input-qoh').val('0.00')
                    $('#input-barcode').focus()
                    tblBody.innerHTML = ''
                });
                return;
            }

            loadDatainTable(inventory[0]['barcode'])
        }
    });

  
});

$('input[type=search]').on('click', '#search-clear', function () {
    //console.log("aw")
    //$(document).on('click', '#search-clear', function () { console.log("aw") });
    //$('#label-search').text($(this)[0].innerText)
    //$('#input-search').attr("placeholder", "Search " + $(this)[0].innerText);

    //$('#input-search').val('')
    //$('#input-barcode').val('')
    //$('#input-name').val('')
    //$('#input-desc').val('')
    //$('#input-qoh').val('')

    //let tblBody = document.getElementById('tbl-body')
    //tblBody.innerHTML = '';
});

$(document).on('click', '#search-clear', function () {
 
    $('#label-search').text($(this)[0].innerText)
    $('#input-search').attr("placeholder", "Search " + $(this)[0].innerText);

    $('#input-search').val('')
    $('#input-barcode').val('')
    $('#input-name').val('')
    $('#input-desc').val('')
    $('#input-qoh').val('')

    let tblBody = document.getElementById('tbl-body')
    tblBody.innerHTML = '';
})

$(document).on('click', '#ul-search li', function () {

    document.getElementById('btn-search-by').innerText = $(this)[0].innerText;
  

    $('#label-search').text($(this)[0].innerText)
    $('#input-search').attr("placeholder", "Search " + $(this)[0].innerText);

    $('#input-search').val('')
    $('#input-barcode').val('')
    $('#input-name').val('')
    $('#input-desc').val('')
    $('#input-qoh').val('')

    let tblBody = document.getElementById('tbl-body')
    tblBody.innerHTML = '';

    let arrdata = [];

    if ($('#btn-search-by').text().toLowerCase() == 'barcode') {

        arrdata = arrbarcode
    } else if ($('#btn-search-by').text().toLowerCase() == 'name') {

        arrdata = arrname
    } else if ($('#btn-search-by').text().toLowerCase() == 'description') {

        arrdata = arrdesc
    }

    $("#input-search").autocomplete({
        source: arrdata
    });
    
});

//$(document).on("click", "#ui-id-11", function () {
  
//    let inventory;
//    data = generateInventoryWithQOH();
//    //$('#input-search').val($(this)[0].innerText)
    

//    if ($('#btn-search-by').text().toLowerCase() == 'barcode') {

//        inventory = data['item'].filter((e) => e['barcode'].toLowerCase().trim() == $(this)[0].innerText.toLowerCase().trim());
//    } else if ($('#btn-search-by').text().toLowerCase() == 'name') {

//        inventory = data['item'].filter((e) => e['name'].toLowerCase().trim() == $(this)[0].innerText.toLowerCase().trim());
//    } else if ($('#btn-search-by').text().toLowerCase() == 'description') {

//        inventory = data['item'].filter((e) => e['description'].toLowerCase().trim() == $(this)[0].innerText.toLowerCase().trim());
//    }
  
//    $("#input-barcode").val(inventory[0]['barcode']);
//    $("#input-name").val(inventory[0]['name']);
//    $("#input-desc").val(inventory[0]['description']);
//    $("#input-qoh").val(inventory[0]['qoh']);

//    if (inventory[0]['qoh'] == 0) {
//        return;
//    }

//    loadICADetails(inventory[0]['barcode'])
//})

function loadData() {
    data = generateInventoryWithQOH();
    // data = generateInventoryWithQOH();
    $("#input-number-unit").attr('readonly', true)  
    $("#input-search").on("keypress", function (e) {
        if (e.key === 'Enter') {          
            if ($('#btn-search-by').text().toLowerCase() == 'barcode') {
                inventory = data['item'].filter((e) => e['barcode'].toLowerCase().trim() == $("#input-search").val().toLowerCase().trim())
            } else if ($('#btn-search-by').text().toLowerCase() == 'name') {
                inventory = data['item'].filter((e) => e['name'].toLowerCase().trim() == $("#input-search").val().toLowerCase().trim())
            } else if ($('#btn-search-by').text().toLowerCase() == 'description') {
                inventory = data['item'].filter((e) => e['description'].toLowerCase().trim() == $("#input-search").val().toLowerCase().trim())
            }     

            if (inventory.length == 0) {
                Swal.fire({
                    icon: "warning",
                    text: "Item Not Found",
                    timer: 1500
                }).then(function () {
                    $('#input-barcode').val('')
                    $('#input-name').val('')
                    $('#input-desc').val('')
                    $('#input-qoh').val('0.00')
                    $('#input-barcode').focus()
                    tblBody.innerHTML = ''
                });
                return;
            }

            loadDatainTable(inventory[0]['barcode'])
        }
    });

    $(document).on('click', '#btn-adjust', function () {
        loadDropDownGoupUnit();
        $('#input-number-unit').attr('readonly', true);
        $('#input-number-unit').val('0');
        $('#input-inqty').attr('readonly', false);
        $('#input-inqty').val('1');
        $("#input-unitcost").val('')
        $('#input-unitcost').attr("placeholder", "0.00");

        let labelElement = document.getElementById("lblNo");
        labelElement.innerHTML = 'No.'

        if ($('#input-barcode').val() == "") {
            Swal.fire({
                icon: "error",
                text: "Please scan barcode",
            }).then(function () {
                $('#input-barcode').trigger("focus");

            });
            return;
        }
        $('#modalstockadjust').modal('show');
    });


    //dropdown
    $(document).on('click', '#dd-groupunit li', function () {
        document.getElementById('btn-groupunit').innerText = $(this)[0].innerText;
        //let stockgroupunit = JSON.parse(sessionStorage.getItem('stockgroupunit'));
        let stockgroupunit = data['stockgroupunit'];
        let groupunit = stockgroupunit.filter((e) => e['groupunitname'].trim().toLowerCase() == $(this)[0].innerText.trim().toLowerCase());
        let unit = groupunit[0]['units'];

        if (groupunit[0]['groupunitid'] == '1') {
            $('#input-number-unit').attr('readonly', true);
            $('#input-number-unit').val('0');
            $('#input-inqty').attr('readonly', false);
            $('#input-inqty').val('1');
            $("#btn-unit").prop("disabled", true);

        } else {
            $('#input-number-unit').val('1');
            $('#input-number-unit').attr('readonly', false);
            $('#input-inqty').attr('readonly', true);
            $('#input-inqty').val(unit[0]['totalqty']);
            $("#btn-unit").prop("disabled", false);
        }

        if ($(this)[0].innerText.toLowerCase() != 'loose') {
            let labelElement = document.getElementById("lblNo");
            labelElement.innerHTML = 'No. of ' + $(this)[0].innerText.trim() + ":"
            //$('#lblNo').value = 'sample'
        } else {
            let labelElement = document.getElementById("lblNo");
            labelElement.innerHTML = 'No.'
        }

        loadDropDownUnit(JSON.stringify(unit))

    });

    $("#input-number-unit").on("keyup", function () {
        $('#input-inqty').attr('readonly', false);
        if ($(this).val() == '') {
            return;
        }

        let unitname = document.getElementById('btn-unit').innerText.trim();
        //let groupunit = JSON.parse(sessionStorage.getItem('stockgroupunit'))
        let groupunit = data['stockgroupunit']
        let unit = groupunit.filter((e) => e['groupunitname'].toLowerCase().trim() == document.getElementById('btn-groupunit').innerText.toLowerCase().trim());

        let selectedunit = unit[0]['units'].filter((e) => e['unitname'].toLowerCase().trim() == document.getElementById('btn-unit').innerText.toLowerCase().trim());
        let totalqty = parseFloat($(this).val()) * parseFloat(selectedunit[0]['totalqty']);

        $('#input-inqty').val(totalqty);
        $('#input-inqty').attr('readonly', true);
    });

    $(document).on('click', '#dd-unit li', function () {
        document.getElementById('btn-unit').innerText = $(this)[0].innerText

        /*let units = JSON.parse(sessionStorage.getItem('arrUnit'));
        let unit = units.filter((e) => e['stockunitname'].trim().toLowerCase() == $(this)[0].innerText.trim().toLowerCase());*/
        //let stockgroupunit = JSON.parse(sessionStorage.getItem('stockgroupunit'));
        let stockgroupunit = data['stockgroupunit'];
        let groupunit = stockgroupunit.filter((e) => e['groupunitname'].trim().toLowerCase() == document.getElementById('btn-groupunit').innerText.toLowerCase().trim());
        let unit = groupunit[0]['units'].filter((e) => e['unitname'].trim().toLowerCase() == document.getElementById('btn-unit').innerText.toLowerCase().trim());
        $("#input-number-unit").val('1')

        $('#input-inqty').val(unit[0]['totalqty']);
    });

    $(document).on('click', '#btn-stockin', function () {

        if ($('#input-number-unit').val() == '') {
            $('#input-inqty').attr('readonly', false);
            $('#input-number-unit').val('1');
            let unitname = document.getElementById('btn-unit').innerText.trim();
            let units = JSON.parse(sessionStorage.getItem('arrUnit'));
            let unit = units.filter((e) => e['stockunitname'] == unitname.toLowerCase().trim());
            let totalqty = parseFloat($(this).val()) * parseFloat(unit[0]['totalqty']);
            $('#input-inqty').val(totalqty);
            $('#input-inqty').attr('readonly', true);
        }


        if ($('#input-inqty').val() == '' || $('#input-inqty').val() == '0' || $('#input-inqty').val() == '0.00') {
            Swal.fire({
                icon: "error",
                text: "Invalid value for Quanity",
            }).then(function () {
                $("#input-inqty").trigger("focus");
            });
            return;
        }

        if ($('#input-unitcost').val() == '') {
            Swal.fire({
                icon: "error",
                text: "Invalid value for Cost",
            }).then(function () {
                $('#input-unitcost').focus();

            });
            return;
        }

        

        let items =  generateInventoryWithQOH()['item'];;
        let item = items.filter((e) => e['barcode'].trim().toLowerCase() == $('#input-barcode').val().toLowerCase().trim());
        let barcode = $('#input-barcode').val();
        
        let id = item[0]['inventoryid'];
        let qty = parseFloat($('#input-inqty').val());
        let cost = parseFloat($('#input-unitcost').val());
        let batchid = getBatchID();
        let expdate = getDateTime();
        let date = getDateTime();
        let notes = 'Adj In';
        let alarm = 0;
        let isbatchexist = item[0]['icadetail'].filter((e) => e['batchid'].trim() == batchid.trim());

        //if (document.getElementById('btnalarm').innerHTML.toLowerCase().trim() == 'yes') {
        //    alarm = 1;
        //}

        if (isbatchexist.toString()) {
            Swal.fire({
                text: "Something went wrong. Please stock in again",
                icon: "warning",
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
            }).then((result) => {
                $('#modalInventoryAdjust').modal('hide');
            });
            return;
        }

        postdata = {
            "inventoryid": id,
            "batchid": batchid,
            "inqty": qty,
            "outqty": 0,
            "unitcost": cost,
            "stockdate": date,
            "notes": notes,
            "expirydate": expdate,
            "expiryalarm": alarm
        }

        inventoryadjust = {
            "inventoryid": id,
            "adjustquantity": qty,
            "unitcost": cost,
            "notes": notes,
            "dateadjusted": date,
            "employeeid": 0,
            "userid": alarm
        }

        //console.log(postdata)
        //console.log(inventoryadjust)
        if (parseFloat($('#input-unitcost').val()) <= 0) {
            Swal.fire({
                //title: "Are you sure you want to stock in with zero cost?",
                text: "Are you sure you want to stock in with zero cost?",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Yes"
            }).then((result) => {
                if (result.isConfirmed) {
                    postInventoryCostAverageDetail(postdata);
                    postInventoryAdjust(inventoryadjust);
                    data = generateInventoryWithQOH();
                    loadDatainTable(barcode);
                    $('#modalstockadjust').modal('hide');
                    Swal.fire({
                        position: "center",
                        icon: "success",
                        text: "Stock successfully adjust",
                        showConfirmButton: false,
                        timer: 1500
                    }).then((result) => {
                        //generateInventoryWithQOH();
                        //loadtblInventory();
                        //generateInventoryCostAverageDetailRow(id);
                        //$('#modalInventoryAdjust').modal('hide');
                    });
                }
            });
            return;
        }

        Swal.fire({
            //title: "Are you sure you want to stock in with zero cost?",
            text: "Are you sure you want to confirm stock in?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes"
        }).then((result) => {
            if (result.isConfirmed) {
                postInventoryCostAverageDetail(postdata);
                postInventoryAdjust(inventoryadjust);
                $('#input-barcode').trigger(jQuery.Event('keypress', { which: 13 }));
                Swal.fire({
                    position: "center",
                    icon: "success",
                    text: "Stock successfully adjust",
                    showConfirmButton: false,
                    timer: 1500
                }).then((result) => {
                    //generateInventoryWithQOH();               
                    //generateInventoryCostAverageDetailRow(id);

                    //debugger
                    data = generateInventoryWithQOH();
                    loadDatainTable(barcode);
                    $('#modalstockadjust').modal('hide');
                });
            }
            return;
        });
    })

    $(document).on('click', '#btn-stockout', function () {
        let batchid = $(this).closest("tr").find('td:eq(0)').text();

        $('#modalstockout').on('shown.bs.modal', function () {     
            $('#input-outqty').focus();
            $('#input-outqty').val('');
            $('#input-outqty').attr("placeholder", "0.00");
        })    
        
        $('#input-batchid').val(batchid)            
        $('#modalstockout').modal('show')
    });

    $(document).on('click', '#btn-confirmstockout', function () {
        let batchid = $('#input-batchid').val();

        let items = data['item'];
        let item = items.filter((e) => e['barcode'].trim().toLowerCase() == $('#input-barcode').val().trim().toLowerCase());
        let icadetail = item[0]['icadetail'].filter((e) => e['batchid'] == batchid)
        let barcode = $('#input-barcode').val();

        let id = item[0]['inventoryid']
        let cost = icadetail[0]['unitcost']
        let expdate = icadetail[0]['expirydate']
        let date = getDateTime();
        let notes = 'Adj Out';
        let alarm = '0'
        let qty = $('#input-outqty').val();

        Swal.fire({
            //title: "Are you sure you want to stock in with zero cost?",
            text: "Are you sure you want to confirm stock out?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes"
        }).then((result) => {
            if (result.isConfirmed) {
                postdata = {
                    "inventoryid": id,
                    "batchid": batchid,
                    "inqty": 0,
                    "outqty": qty,
                    "unitcost": cost,
                    "stockdate": date,
                    "notes": notes,
                    "expirydate": expdate,
                    "expiryalarm": alarm
                }

                inventoryadjust = {
                    "inventoryid": id,
                    "adjustquantity": -Math.abs(qty),
                    "unitcost": cost,
                    "notes": notes,
                    "dateadjusted": date,
                    "employeeid": alarm,
                    "userid": 0
                }

                postInventoryCostAverageDetail(postdata);
                postInventoryAdjust(inventoryadjust);

                Swal.fire({
                    position: "center",
                    icon: "success",
                    text: "Stock successfully adjust",
                    showConfirmButton: false,
                    timer: 1500
                }).then((result) => {
                    //generateInventoryWithQOH();
                    //generateInventoryCostAverageDetailRow(id);
                    //$('#modalstockout').modal('hide');
                    data = generateInventoryWithQOH();
                    loadDatainTable(barcode);
                    $('#modalstockout').modal('hide');
                });
            }
            return;
        });

    })

}

function loadDatainTable(barcode) {
    let tblBody = document.getElementById('tbl-body')
    data = '';
    data = generateInventoryWithQOH();
    loadDropDownGoupUnit();
    let scannedbarcode = this.value;

    let inventory = data['item'].filter((e) => e['barcode'].toLowerCase().trim() == barcode.toLowerCase().trim());
    if (inventory.length == 0) {
        Swal.fire({
            icon: "warning",
            text: "Item Not Found",
            timer: 1500
        }).then(function () {
            $('#input-barcode').val('')
            $('#input-name').val('')
            $('#input-desc').val('')
            $('#input-qoh').val('0.00')
            $('#input-barcode').focus()
            tblBody.innerHTML = ''
        });
        return;
    }
    //console.log(data)
    //inventory
    $("#input-barcode").val(inventory[0]['barcode']);
    $("#input-name").val(inventory[0]['name']);
    $("#input-desc").val(inventory[0]['description']);
    $("#input-qoh").val(inventory[0]['qoh']);

    if (inventory[0]['qoh'] == 0) {
        return;
    }

    loadICADetails(inventory[0]['barcode'])

}

function getInventory() {

    var response = $.ajax({
        type: "POST",
        url: "MobileInventoryBatchAdjust.aspx/getInventories",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () {
            //modalLoad.style.display = "block";
        },
        complete: function (result) {
            // modalLoad.style.display = "none";
        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        },
        success: function (result) {
            //console.log(result.d)
            //sessionStorage.setItem('arrData', result.d);
            //generateInventoryWithQOH();
            //loadtblInventory();
        }
    });
    return response.responseJSON.d;
};

function getCategory() {
    var response = $.ajax({
        type: "POST",
        url: "MobileInventoryBatchAdjust.aspx/getCategories",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () { },
        complete: function (result) {
            // modalLoad.style.display = "none";

        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        },
        success: function (result) {
            // sessionStorage.setItem('category', result.d);
        }
    });
    return response.responseJSON.d;
}

function getInventoryCostAverage() {
    var response = $.ajax({
        type: "POST",
        url: "MobileInventoryBatchAdjust.aspx/getInventoryCostAverage",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () {
            //modalLoad.style.display = "block";
        },
        complete: function (result) {
            // modalLoad.style.display = "none";
        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) { console.log(errorThrown); },
        success: function (result) { }
    });
    return response.responseJSON.d;
}

/*function getGroupUnit() {
    let url = readWebConfig();
    let token = bearertoken();
    let db = loadDB();
    var groupunit;
    var settings = {
        "url": url + "/api/" + db + "/StockAdjustGroupUnit/GetStockAdjustGroupUnit",
        "method": "GET",
        "timeout": 0,
        "async": false,
        "headers": {
            "Authorization": token
        },
    };

    $.ajax(settings).done(function (response) {
        groupunit = response
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("error");
    });
    return JSON.parse(groupunit);
}

function getUnit() {
    let url = readWebConfig();
    let token = bearertoken();
    let db = loadDB();
    var unit;
    var settings = {
        "url": url + "/api/" + db + "/StockAdjustUnit/GetStockAdjustUnit",
        "method": "GET",
        "timeout": 0,
        "async": false,
        "headers": {
            "Authorization": token
        },
    };

    $.ajax(settings).done(function (response) {
        unit = response
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("error");
    });
    return JSON.parse(unit);
}*/

function getStockAdjustGroupUnit() {
    var response = $.ajax({
        type: "POST",
        url: "MobileInventoryBatchAdjust.aspx/getStockAdjustGroupUnit",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () {
            //modalLoad.style.display = "block";
        },
        complete: function (result) {
            // modalLoad.style.display = "none";
        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        },
        success: function (result) {
            //sessionStorage.setItem('arrGroupUnit', result.d)
        }
    });
    return response.responseJSON.d;
}

function getStockAdjustUnit() {
    var response = $.ajax({
        type: "POST",
        url: "MobileInventoryBatchAdjust.aspx/getStockAdjustUnit",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () {
            //modalLoad.style.display = "block";
        },
        complete: function (result) {
            // modalLoad.style.display = "none";
        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        },
        success: function (result) {
            //sessionStorage.setItem('arrUnit', result.d)
        }
    });
    return response.responseJSON.d;
}

function getInventoryStockAdjustDetail() {
    var response = $.ajax({
        type: "POST",
        url: "MobileInventoryBatchAdjust.aspx/getInventoryCostAverageDetail",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () {
            //modalLoad.style.display = "block";
        },
        complete: function (result) {
            // modalLoad.style.display = "none";

        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        },
        success: function (result) {
        }
    });
    return response.responseJSON.d;
}


let arrbarcode = [];
let arrname = [];
let arrdesc = [];
function generateInventoryWithQOH() {

    /*let categories = getCategories();
    let inventories = getInventories();
    let ica = getICA();
    let icadetails = getICAD();*/

    let categories = JSON.parse(getCategory());
    let inventories = JSON.parse(getInventory());
    let ica = JSON.parse(getInventoryCostAverage());
    let icadetails = JSON.parse(getInventoryStockAdjustDetail());
    


    let inventory = inventories.filter((e) => e['Active'] != 0 && e['Barcode'].toLowerCase() != 'round' && e['Class'] == '0');
    let category = categories.filter((e) => e['Active'] != 0 && e['CategoryName'].toLowerCase() != 'round');
    let icadetail = icadetails;
    let arrinventory = [];
    let arricadetail = [];
    arrbarcode = [];
    arrname = []
    arrdesc = []
    category.forEach(function (category) {
        inventory.forEach(function (inventory) {
            if (category['CategoryID'] == inventory['CategoryID']) {
                ica.forEach(function (ica) {
                    if (ica['InventoryID'] == inventory['InventoryID']) {
                        arricadetail = [];
                        icadetail.forEach(function (detail) {
                            if (detail['inventoryid'] == ica['InventoryID']) {
                                let icadetail = {
                                    'stockid': detail['stockid'],
                                    'inventoryid': detail['inventoryid'],
                                    'batchid': detail['batchid'].trim(),
                                    'inqty': detail['inqty'],
                                    'outqty': detail['outqty'],
                                    'unitcost': detail['unitcost'],
                                    'stockdate': detail['stockdate'].trim(),
                                    'notes': detail['notes'].trim(),
                                    'expirydate': detail['expirydate'].trim(),
                                    'expiryalarm': detail['expiryalarm']
                                }
                                arricadetail.push(icadetail);
                            }
                        });

                        let inqty = 0;
                        let outqty = 0;

                        arricadetail.forEach(function (x) {
                            inqty = inqty + x.inqty;
                            outqty = outqty + x.outqty;

                        });

                        let item = {
                            'inventoryid': inventory['InventoryID'],
                            'barcode': inventory['Barcode'].trim(),
                            'name': inventory['InventoryName'].trim(),
                            'description': inventory['Description'].trim(),
                            'categoryid': category['CategoryID'],
                            'category': category['CategoryName'].trim(),
                            //'pquantity': ica['PQuantity'],
                            //'retailqty': ica['RetailQTY'],
                            //'qoh': parseFloat(ica['PQuantity']) - parseFloat(ica['RetailQTY']),
                            'totalinqty': inqty,
                            'totaloutqty': outqty,
                            'qoh': parseFloat(inqty) - parseFloat(outqty),
                            'icadetail': arricadetail
                        }
                        arrinventory.push(item);
                        arrbarcode.push(inventory['Barcode'].trim())
                        arrname.push(inventory['InventoryName'].trim())
                        arrdesc.push(inventory['Description'].trim())
                    }
                });
            }
        });
    });

    let setting = {
        'branch': loadDB()
    }

    let data = {
        setting: setting,
        categories: category,
        stockgroupunit: generateStockAdjustUnit(),
        item: arrinventory
    }

    //$("#hiddenloader").hide()
    return data;
    //sessionStorage.setItem('data', JSON.stringify(data))
    //sessionStorage.setItem('inventory', JSON.stringify(arrinventory))
}

function generateStockAdjustUnit() {
//getGroupUnit
    //let groupunit = getGroupUnit();
    //let unit = getUnit();
    let groupunit = JSON.parse(getStockAdjustGroupUnit());
    let unit = JSON.parse(getStockAdjustUnit());
    let arrgroupunit = [];
    let arrunit = [];

    groupunit.forEach(function (groupunit) {
        arrunit = [];
        unit.forEach(function (unit) {
            if (groupunit['id'] == unit['stockgroupunitid']) {
                let unitdata = {
                    'unitid': unit['id'],
                    'unitname': unit['stockunitname'],
                    'totalqty': unit['totalqty']
                }
                arrunit.push(unitdata);
            }
        });

        let groupunitdata = {
            'groupunitid': groupunit['id'],
            'groupunitname': groupunit['stockgroupunitname'],
            'units': arrunit
        }
        arrgroupunit.push(groupunitdata)
    });
    return arrgroupunit;
    //sessionStorage.setItem('stockgroupunit', JSON.stringify(arrgroupunit))
}

//function loadDropDownGoupUnit() {
//    //let stockgroupunit = JSON.parse(sessionStorage.getItem('stockgroupunit'));
//    let stockgroupunit = data['stockgroupunit']
//    //console.log(stockgroupunit)
//    let unit = stockgroupunit[0]['units'];
//    document.getElementById('dd-groupunit').innerHTML = '';
//    document.getElementById('btn-groupunit').innerText = stockgroupunit[0]['groupunitname'];

//    for (const item of stockgroupunit) {
//        var li = document.createElement('li')
//        li.id = "gu" + item['groupunitid']
//        document.getElementById('dd-groupunit').appendChild(li)

//        var a = document.createElement('a')
//        a.className = 'dropdown-item'
//        a.innerHTML = item['groupunitname']
//        document.getElementById(li.id).appendChild(a)
//    }
//    loadDropDownUnit(JSON.stringify(unit))
//}

function loadDropDownGoupUnit() {

    //let stockgroupunit = JSON.parse(sessionStorage.getItem('stockgroupunit'));
    let stockgroupunit = data['stockgroupunit']
    let unit = stockgroupunit[0]['units'];
    document.getElementById('dd-groupunit').innerHTML = '';
    document.getElementById('btn-groupunit').innerText = stockgroupunit[0]['groupunitname'];

    for (const item of stockgroupunit) {
        var li = document.createElement('li')
        li.id = "gu" + item['groupunitid']
        document.getElementById('dd-groupunit').appendChild(li)

        var a = document.createElement('a')
        a.className = 'dropdown-item'
        a.innerHTML = item['groupunitname']
        document.getElementById(li.id).appendChild(a)
    }

    loadDropDownUnit(JSON.stringify(unit))
}

function loadDropDownUnit(data) {
    let unit = JSON.parse(data);

    document.getElementById('dd-unit').innerHTML = ""
    document.getElementById('btn-unit').innerText = unit[0]['unitname']
    for (const item of unit) {

        var li = document.createElement('li')
        li.id = "u" + item['unitid']
        document.getElementById('dd-unit').appendChild(li)

        var a = document.createElement('a')
        a.className = 'dropdown-item'
        a.innerHTML = item['unitname']
        document.getElementById(li.id).appendChild(a)
    }
}

function loadICADetails(barcode) {

    const tblBody = document.getElementById('tbl-body');
    tblBody.innerHTML = ''

    let inventories = data['item'].filter((e) => e['barcode'].trim().toLowerCase() == barcode.trim().toLowerCase());
    let inventory = inventories.filter((e) => e['inventoryid'] == inventories[0]['inventoryid']);
    const sortedbyBatch = (a, b) => b['batchid'] > a['batchid'] ? 1 : -1;

    inventory[0]['icadetail'].sort(sortedbyBatch);

    //console.log(inventory[0]['icadetail'].sort(sortedbyBatch))
    let qtyin = inventory[0]['icadetail'].reduce((accumulator, qty) => accumulator + qty['inqty'], 0);
    let qtyout = inventory[0]['icadetail'].reduce((accumulator, qty) => accumulator + qty['outqty'], 0);
    let onhand = parseFloat(qtyin) - parseFloat(qtyout)

    //console.log(qtyin)
    //console.log(qtyout)

    let output = inventory[0]['icadetail'].reduce((accumulator, currentItem) => {
        const matchedItem = accumulator.find((item) => item['batchid'] === currentItem['batchid']);

        if (!matchedItem) {
            return [...accumulator, currentItem];
        } else {
            matchedItem['inqty'] += currentItem['inqty']
            matchedItem['outqty'] += currentItem['outqty']
            return accumulator
        }
    }, []);

    //console.log(output)
    $.each(output, function (key, detail) {

        let qoh = parseFloat(detail['inqty']) - parseFloat(detail['outqty']);
        const tblBody = document.getElementById('tbl-body');

        if (qoh > 0 || qoh < 0) {
            const tr = document.createElement("tr");
            let tdbatchid = document.createElement('td')
            tdbatchid.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center'
            let batchid = document.createTextNode(detail['batchid'].toString().trim());

            let tddate = document.createElement("td")
            tddate.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center'
            tddate.style = "font-size:12px";
            let date = document.createTextNode(detail['stockdate'].substring(0, 10).toString().trim());

            let tdstockin = document.createElement("td")
            tdstockin.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center'
            let stockin = document.createTextNode(detail['inqty'])

            let tdstockout = document.createElement("td")
            tdstockout.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center'
            let stockout = document.createTextNode(detail['outqty'])

            let tdqoh = document.createElement("td")
            tdqoh.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center'
            let qoht = document.createTextNode(qoh.toFixed(2))

            let tdcost = document.createElement("td")
            tdcost.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center'
            let cost = document.createTextNode(detail['unitcost'].toFixed(2))

            let tdstockoutbutton = document.createElement("td")
            tdstockoutbutton.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center'

            let btnstockout = document.createElement("button")
            btnstockout.type = 'button'
            btnstockout.id = 'btn-stockout'
            if (qoh <= 0) {
                btnstockout.className = 'btn btn-outline-danger btn-xs m-0 disabled'
            } else {
                btnstockout.className = 'btn btn-outline-danger btn-xs m-0'
            }
            btnstockout.innerText = 'Stock Out'

            tdbatchid.appendChild(batchid);
            tddate.appendChild(date);
            //tdstockin.appendChild(stockin);
            //tdstockout.appendChild(stockout)
            tdcost.appendChild(cost)
            tdqoh.appendChild(qoht);
            tdstockoutbutton.appendChild(btnstockout);

            tr.appendChild(tdbatchid);
            tr.appendChild(tddate)
            //tr.appendChild(tdstockin);
            //tr.appendChild(tdstockout);
            tr.appendChild(tdcost)
            tr.appendChild(tdqoh);
            tr.appendChild(tdstockoutbutton);
            tblBody.appendChild(tr);
        }

    });

}

function putInventoryCostAverage(data) {
    let db = loadDB();
    let token = bearertoken();
    var settings = {
        "url": url + "/api/" + db + "/DFDownload/UpdateInventoryCostAverage",
        "method": "PUT",
        "async": false,
        "timeout": 0,
        "headers": {
            "Content-Type": "application/json",
            "Authorization": token
        },
        "data": JSON.stringify(data),
    };

    $.ajax(settings).done(function (response, textStatus, xhr) {
        if (xhr.status == '200') {
            //getInventoryCostAverage()
            //generateInventoryWithQOH();
        }
    });
}

function postInventoryCostAverageDetail(postdata) {
    let db = loadDB();
    let token = bearertoken();
    var settings = {
        "url": url + "/api/InventoryCostAverageDetail?clientdb='" + db + "'",
        "method": "POST",
        "async": false,
        "timeout": 0,
        "headers": {
            "Content-Type": "application/json",
            "Authorization": token
        },
        "data": JSON.stringify(postdata),
    };

    $.ajax(settings).done(function (response, textStatus, xhr) {
        if (xhr.status == '200') {
            //let arrInventoryCostAverage = JSON.parse(sessionStorage.getItem('arrInventoryCostAverage'));
            //let itemInventoryCostAverage = arrInventoryCostAverage.filter((e) => e['InventoryID'] == data['inventoryid']);
            //let inventories = JSON.parse(sessionStorage.getItem('inventory'));
            let inventories = data['item'];
            let invetory = inventories.filter((e) => e['inventoryid'] == postdata['inventoryid']);

            let newpquantity = parseFloat(invetory[0]['pquantity']) + (parseFloat(data['inqty']) - parseFloat(data['outqty']));
            var putdata = {
                "inventoryid": data['inventoryid'],
                "pquantity": parseFloat(newpquantity),
                "dbname": db
            }
            putInventoryCostAverage(putdata);

        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown)
        console.log("error");
    }).always(function (jqXHR, textStatus, errorThrown) {

    })
}

function postInventoryAdjust(data) {
    let db = loadDB();
    let token = bearertoken();
    var settings = {
        "url": url + "/api/InventoryAdjust?clientdb=" + db,
        "method": "POST",
        "timeout": 0,
        "async": true,
        "headers": {
            "Content-Type": "application/json",
            "Authorization": token
        },
        "data": JSON.stringify(data),
    };

    $.ajax(settings).done(function (response) {

    });
}




