let inventorydetaildata;
let receivedata;
let branches = [];
$(document).ready(function () {
    const urlParams = new URL(window.location.href).searchParams;
    const db = urlParams.get('ToBranch');
    const transferno = urlParams.get('TransferNo');

    branches = JSON.parse(sessionStorage.getItem('branchlist'))
    let branch = branches.filter((e) => e['fullname'].toLowerCase().trim() == $('#input-branchto').val().toLowerCase().trim())
    receivedata = JSON.parse(GET_ReceiveStockList(db))
    receivedata = receivedata.filter((e) => e['transferno'].toLowerCase().trim() == transferno.toLowerCase().trim())

    let frombranch = branches.filter((e) => e['branchid'] == receivedata[0]['frombranchid'])
    let tobranch = branches.filter((e) => e['branchid'] == receivedata[0]['tobranchid'])
    //inventorydetaildata = JSON.parse(GET_InventoryDetail(tobranch[0]['name']));

    inventorydetaildata = InventoryWithCostDetail(tobranch[0]['name']);
    $('#input-transfernumber').val(receivedata[0]['transferno']);
    $('#input-date').val(getDateTime());
    $('#input-senddate').val(receivedata[0]['senddatetime'].substring(0, 10));
    $('#input-branchfrom').val(frombranch[0]['fullname']);
    $('#input-branchto').val(tobranch[0]['fullname']);
    $('#input-confirmno').val(receivedata[0]['confirmno']);
    $('#textarea-notes').val(receivedata[0]['tnotes']);
    //$('#input-confirmstatus').val(receivedata[0]['confirmno']);

    //loadReceiveStockDetail( receivedata[0]['tobranchid'],receivedata)
    loaditemlist(receivedata)
    if (receivedata[0]['confirmflag'] == 1) {
        $('#input-confirmstatus').val('Confirmed');
        $('#btn-confirm').attr('disabled', 'disabled');
        $('#textarea-notes').attr('disabled', 'disabled');
        $('#table-body-transfer-item tr').css({
            'pointer-events': 'none',
        }); 
    }

    $('#table-body-transfer-item tr td:eq(8)').css({
        'pointer-events': 'none',
    });
   // console.log(JSON.parse(GET_ReceiveStockList('da8', 1)))
    //console.log(JSON.parse(GET_ReceiveStock('da8', 3))['transferid']);
    
})

$('#table-body-transfer-item').on('change keyup input', '#input-acceptqty', function (event) {

    let sendqty = $(this).closest('tr').find('td:eq(8)').text();

    if (parseFloat($(this).val()) <= parseFloat(sendqty)) {
        let rejectqty = parseFloat(sendqty) - parseFloat($(this).val())
        $(this).closest('tr').find('#input-rejectqty').val(rejectqty);
    }

});



$('#table-body-transfer-item').on('click input', '#input-acceptqty', function (event) {
    $(this).select()
});


$('#btn-confirm').on('click', function (event) {
    const urlParams = new URL(window.location.href).searchParams;
    const db = urlParams.get('ToBranch');

    let branch = branches.filter((e) => e['fullname'].toLowerCase().trim() == $('#input-branchto').val().toLowerCase().trim())
    receivedata = JSON.parse(GET_ReceiveStockList(db))
    let tobranch = branches.filter((e) => e['branchid'] == receivedata[0]['tobranchid'])
    let frombranch = branches.filter((e) => e['branchid'] == receivedata[0]['frombranchid'])
    let receivestockdetail = receivedata.filter((e) => e['confirmno'] != "")
    let confirmno = 0;
    let confirmnolength = '0000000';
    let newconfirmno;

    let hasreturn = false;
    receivestockdetail = receivestockdetail.sort((a, b) => {
        //return b['confirmno'] - a['confirmno']
        if (a['confirmno'] < b['confirmno']) return -1;
        if (a['confirmno'] > b['confirmno']) return 1;
        return 0;
    });

    if (receivestockdetail.length > 0) {
        confirmno = receivestockdetail.slice(-1)[0]['confirmno'];
        confirmno = confirmno.split('-')
        confirmno = parseInt(confirmno[1]) + 1;

        newconfirmno = confirmnolength + confirmno;
        newconfirmno = newconfirmno.substring(newconfirmno.length - confirmnolength.length);

        newconfirmno = tobranch[0]['prefix'].toUpperCase().trim() + "-" + newconfirmno;
    } else {
        confirmno = parseInt(confirmno) + 1;
        newconfirmno = confirmnolength + confirmno;
        newconfirmno = tobranch[0]['prefix'].toUpperCase().trim() + "-" + newconfirmno.substring(newconfirmno.length - confirmnolength.length);
    }


    Swal.fire({
        text: "Are you sure you want to confirm transfer?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "Yes"
    }).then((result) => {
        if (result.isConfirmed) {
            receivedata = receivedata.filter((e) => e['transferno'].toLowerCase().trim() == $('#input-transfernumber').val().toLowerCase().trim())

            let jsondata = {
                "receiveid": receivedata[0]['receiveid'],
                "confirmdatetime": getDateTime(),
                "confirmno": newconfirmno,
                "confirmflag": 1,
                "tnotes": $('#textarea-notes').val(),
                "dbname": tobranch[0]['name']
            }

            //Update Receive Stock
            PUT_ReceiveStock(jsondata);

            ////Update Receive Stock Detailed Cost(to branch)
            var table = $('#tbl-items').tableToJSON();
            table.forEach(function (tbl) {
                let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == tbl['Barcode'].toLowerCase().trim())

                jsonreceivestockdetailedcost = {
                    "receiveid": receivedata[0]['receiveid'],
                    "itemid": tbl['#'],
                    "acceptedqty": $('#tbl-items').find("tr:eq(" + tbl['#'] + ")").find("td:eq(9)").find("input").val(),
                    "rejectedqty": $('#tbl-items').find("tr:eq(" + tbl['#'] + ")").find("td:eq(10)").find("input").val(),
                    "reason": "",
                    "dbname": tobranch[0]['name']
                }

                PUT_ReceiveStockDetailedCost(jsonreceivestockdetailedcost)
            })

            //Update Transfer Stock
            let datatransferstock = {
                "transferid": receivedata[0]['transferid'],
                "senddatetime": receivedata[0]['senddatetime'],
                "confirmno": newconfirmno,
                "confirmdatetime": getDateTime(),
                "adjustdatetime": getDateTime(),
                "sinvoiceno": "",
                "subtotal": 0,
                "discount": 0,
                "gst": 0,
                "ttotal": 0,
                "tnotes": receivedata[0]['tnotes'],
                "employeename": receivedata[0]['employeename'],
                "sendflag": 1,
                "confirmflag": 1,
                "originalbranchid": receivedata[0]['frombranchid'],
                "originaltransferno": receivedata[0]['transferno'],
                "dbname": frombranch[0]['name']
            }
            PUT_TransferStock(datatransferstock)

            ////Update Transfer Stock Detailed Cost(to branch)
            var table = $('#tbl-items').tableToJSON();
            table.forEach(function (tbl) {
                let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == tbl['Barcode'].toLowerCase().trim())
                jsontransferstockdetailedcost = {
                    "transferid": receivedata[0]['transferid'],
                    "itemid": tbl['#'],
                    "batchid": tbl['Batch #'],
                    "qty": tbl['Send qty'],
                    "cost": tbl['Cost'],
                    "rejectedqty": $('#tbl-items').find("tr:eq(" + tbl['#'] + ")").find("td:eq(10)").find("input").val(),
                    "reason": "",
                    "dbname": frombranch[0]['name']
                }
                PUT_TransferStockDetailedCost(jsontransferstockdetailedcost)
            })

            //stock in to branch
            var table = $('#tbl-items').tableToJSON();
            table.forEach(function (tbl) {
                let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == tbl['Barcode'].toLowerCase().trim())
                let batchno = Generate_NewBatch(tobranch[0]['name'])
                detail = {
                    "inventoryid": inventory[0]['inventoryid'],
                    //"batchid": tbl['Batch #'],
                    "batchid": batchno,
                    "inqty": $('#tbl-items').find("tr:eq(" + tbl['#'] + ")").find("td:eq(9)").find("input").val(),
                    "outqty": 0,
                    "unitcost": tbl['Cost'],
                    "stockdate": getDateTime(),
                    "notes": "(Tr) Stock In(" + tbl['Batch #'] + ")",
                    "expirydate": getDateTime(),
                    "expiryalarm": 0

                }
                POST_InventoryCostAverageDetail(tobranch[0]['name'], detail)

                //stock in from branch
                let rejectqty = $('#tbl-items').find("tr:eq(" + tbl['#'] + ")").find("td:eq(10)").find("input").val();
                
                if (rejectqty > 0) {
                    let stockoutdetail = {
                        "inventoryid": inventory[0]['inventoryid'],
                        "batchid": tbl['Batch #'],
                        "inqty": rejectqty,
                        "outqty": 0,
                        "unitcost": tbl['Cost'],
                        "stockdate": getDateTime(),
                        "notes": "(TrR) Stock In",
                        "expirydate": getDateTime(),
                        "expiryalarm": 0
                    }
                    hasreturn = true
                    POST_InventoryCostAverageDetail(frombranch[0]['name'], stockoutdetail)
                }
            })

            //return stock
            //console.log(receivedata[0])
            //console.log(receivedata[0]['receiveid'])
            if(hasreturn == true){
                ReturnStockTransaction(frombranch[0]['name'], tobranch[0]['name'], receivedata[0]['receiveid'])
            }
           
            //stock out from branch
            var table = $('#tbl-items').tableToJSON();
            table.forEach(function (tbl) {
                let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == tbl['Barcode'].toLowerCase().trim())

                detail = {
                    "inventoryid": inventory[0]['inventoryid'],
                    "batchid": tbl['Batch #'],
                    "inqty": 0,
                    "outqty": tbl['Send qty'],
                    "unitcost": tbl['Cost'],
                    "stockdate": getDateTime(),
                    "notes": "(Tr) Stock Out",
                    "expirydate": getDateTime(),
                    "expiryalarm": 0

                }
                POST_InventoryCostAverageDetail(frombranch[0]['name'], detail)
            })

            Swal.fire({
                position: "center",
                icon: "success",
                text: "Stock successfully confirm",
                showConfirmButton: false,
                timer: 1500
            }).then((result) => {
                const urlParams = new URL(window.location.href).searchParams;
                const db = urlParams.get('ToBranch');
                receivedata = JSON.parse(GET_ReceiveStockList(db))
                receivedata = receivedata.filter((e) => e['transferno'].toLowerCase().trim() == $('#input-transfernumber').val().toLowerCase().trim())

                $('#input-confirmno').val(receivedata[0]['confirmno']);

                if (receivedata[0]['confirmflag'] == 1) {
                    $('#input-confirmstatus').val('Confirmed');
                    $('#btn-confirm').attr('disabled', 'disabled');
                    $('#table-body-transfer-item tr').css({
                        'pointer-events': 'none',
                    });

                }

            });
        }
    });
});

function ReturnStockTransaction(fromdb, todb, receivestockid) {
    let receivestock = JSON.parse(GET_ReceiveStock(todb, receivestockid));
    let frombranch = branches.filter((e) => e['name'] == fromdb);
    let tobranch = branches.filter((e) => e['name'] == todb);
    
    let returnstockdetaillist = JSON.parse(GET_ReturnStockList(fromdb))
    returnstockdetaillist = returnstockdetaillist.filter((e) => e['returnno'] != null);
    let returnno = 0;
    let returnnolength = '0000000';
    let prefixreturnno = 'RT'
    let newreturnno;
    let returndetail = [];

   
    if (returnstockdetaillist.length > 0) {        
        returnno = returnstockdetaillist.slice(-1)[0]['returnno'];
        
        returnno = returnno.split('-')
        returnno = parseInt(returnno[1]) + 1;
        
        newreturnno = returnnolength + returnno;
        
        newreturnno = newreturnno.substring(newreturnno.length - returnnolength.length);

        newreturnno = prefixreturnno + tobranch[0]['prefix'].toUpperCase().trim() + "-" + newreturnno;
    } else {
        returnno = parseInt(returnno) + 1;
        newreturnno = returnnolength + returnno;
        newreturnno = prefixreturnno + tobranch[0]['prefix'].toUpperCase().trim() + "-" + newreturnno.substring(newreturnno.length - returnnolength.length);
    }


    var table = $('#tbl-items').tableToJSON();
    table.forEach(function (tbl) {    
        let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == tbl['Barcode'].toLowerCase().trim())
        let rejectqty = $('#tbl-items').find("tr:eq(" + tbl['#'] + ")").find("td:eq(10)").find("input").val();

        //if (rejectqty > 0) {
        //    let stockoutdetail = {
        //        "inventoryid": tbl['ID'],
        //        "batchid": tbl['Batch #'],
        //        "inqty": fromdb,
        //        "outqty": 0,
        //        "unitcost": tbl['Cost'],
        //        "stockdate": getDateTime(),
        //        "notes": "Transfer Stock In",
        //        "expirydate": getDateTime(),
        //        "expiryalarm": 0
        //    }
        //    POST_InventoryCostAverageDetail(frombranch[0]['name'], stockoutdetail)
        //}
        if(rejectqty > 0){
            let detail = {           
                "returnid": returnno,
                "itemid": tbl['#'],
                "inventoryid": tbl['ID'],
                "batchid": tbl['Batch #'],
                "cost": tbl['Cost'],
                "returnqty": $('#tbl-items').find("tr:eq(" + tbl['#'] + ")").find("td:eq(10)").find("input").val(),
                "reason": '',
                "stockdate":getDateTime()

            }       
            returndetail.push(detail)
        }
    })
 
    let datareturnstock = {
        "returnStockDetailedCosts": returndetail,
        "returnid": returnno,
        "frombranchid": frombranch[0]['branchid'],
        "tobranchid": tobranch[0]['branchid'],
        "transdate": receivestock['confirmdatetime'], // confirm date
        "returnno": newreturnno,
        "returndate":getDateTime(),
        "transferid": receivestock['transferid'], 
        "transferno": receivestock['transferno'],
        "confirmid": receivestock['receiveid'],
        "confirmno": receivestock['confirmno'],
        "subtotal": 0,
        "discount": 0,
        "gst": 0,
        "ttotal": 0,
        "accepttotal": 0,
        "employeename": '',
        "returnflag": 1,
        "sinvoiceno": "",
        "tnotes": ""
    }

    //console.log(datareturnstock)
    POST_ReturnStock(fromdb, datareturnstock);

    //stock in to branch
    //var table = $('#tbl-items').tableToJSON();
    //table.forEach(function (tbl) {
    //    let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == tbl['Barcode'].toLowerCase().trim())
    //    let rejectqty = $('#tbl-items').find("tr:eq(" + tbl['#'] + ")").find("td:eq(10)").find("input").val();
      
    //    if (rejectqty > 0) {
    //        let stockoutdetail = {
    //            "inventoryid": inventory[0]['inventoryid'],
    //            "batchid": tbl['Batch #'],
    //            "inqty": 0,
    //            "outqty": rejectqty,
    //            "unitcost": tbl['Cost'],
    //            "stockdate": getDateTime(),
    //            "notes": "Transfer Stock In",
    //            "expirydate": getDateTime(),
    //            "expiryalarm": 0
    //        }
    //        POST_InventoryCostAverageDetail(frombranch[0]['name'], stockoutdetail)
    //    }
    //})
}


//get receivestocklist
function GET_ReceiveStockList(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "ReceivingStockTransfer.aspx/GET_ReceiveStockList",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

//get receivestock by receiveid
function GET_ReceiveStock(db,receiveid) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "ReceivingStockTransfer.aspx/GET_ReceiveStockByReceiveID",
        data: "{'db':'" + db + "','receiveid':'" + receiveid + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error GET_ReceiveStockList")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function loadReceiveStockDetail(frombranchname, data) {
    let itemarr = [];
    let itemdata = data[0]['receiveStockDetailedCosts']
    itemdata.forEach(function (item) {
        let inventory = inventorydetaildata.filter((e) => e['inventoryid'] == item['inventoryid'])
        let x = {
            "inventoryid": item['inventoryid'],
            "barcode": inventory[0]['barcode'],
            "name": inventory[0]['name'],
            "description": inventory[0]['description'],
            "unit": "PCS",
            "batch": item['batchid'],
            "cost": item['cost'].toFixed(2),
            "qty": item['qty'].toFixed(2),
        }
        itemarr.push(x);
    })

    loaditemlist(itemarr)

    if (data[0]['sendflag'] == 1) {
        status = 'Sent'
        $('#btn-save').attr('disabled', 'disabled');
        $('#btn-confirm').attr('disabled', 'disabled');
        $('#btn-branch').attr('disabled', 'disabled');
        $('#btn-additem').attr('disabled', 'disabled');
        $("#tbl-items :button").prop("disabled", true);        
    }
    $("#tbl-items :input").prop("disabled", true);

    //$('#input-branchfrom').val(currentbranch)
}

function GET_InventoryDetail(db) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/InventoryWithCostDetail",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error GET_InventoryDetail")
        },
        success: function (result) {
            returnvalue = result.d;
        }
    });
    return returnvalue;
}

//Confirm/Update stocktransfer
function PUT_ReceiveStock(json) {

    var returnvalue;
    $.ajax({
        type: "POST",
        url: "ReceivingStockTransfer.aspx/PUT_ReceiveStock",
        data: "{'jsondata':'" + JSON.stringify(json) + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            returnvalue = result.d;
        }
    });
    return returnvalue;
}

//Update Receive Stock Detailed Cost
function PUT_ReceiveStockDetailedCost(json) {

    var returnvalue;
    $.ajax({
        type: "POST",
        url: "ReceivingStockTransfer.aspx/PUT_ReceiveStockDetailedCost",
        data: "{'jsondata':'" + JSON.stringify(json) + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            returnvalue = result.d;
        }
    });
    return returnvalue;
}

//POST inventorycostaveragedetail
function POST_InventoryCostAverageDetail(db, json) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "ReceivingStockTransfer.aspx/POST_InventoryCostAverageDetail",
        data: "{'db':'" + db + "','jsondata':'" + JSON.stringify(json) + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error POST_InventoryCostAverageDetail")
        },
        success: function (result) {
            returnvalue = result.d;
        }
    });
    return returnvalue;
}

// Get Inventorycostaveragedetail
function GET_InventoryCostAverageDetail(todb) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "ReceivingStockTransfer.aspx/GET_InventoryCostAverageDetail",
        data: "{'db':'" + todb + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error POST_InventoryCostAverageDetail")
        },
        success: function (result) {
            returnvalue = result.d;
        }
    });
    return returnvalue;
}

//POST Returnstock
function POST_ReturnStock(db, json) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "ReceivingStockTransfer.aspx/POST_ReturnStock",
        data: "{'db':'" + db + "','jsondata':'" + JSON.stringify(json) + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error POST_ReturnStock")
        },
        success: function (result) {
            returnvalue = result.d;
        }
    });
    return returnvalue;
}

function GET_ReturnStockList(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "ReceivingStockTransfer.aspx/GET_ReturnStockDetailList",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error GET_ReturnStockList")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

//Update Transferstock 
function PUT_TransferStock(json) {

    var returnvalue;
    $.ajax({
        type: "POST",
        url: "ReceivingStockTransfer.aspx/PUT_TransferStock",
        data: "{'jsondata':'" + JSON.stringify(json) + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error PUT_TransferStock")
        },
        success: function (result) {
            returnvalue = result.d;
        }
    });
    return returnvalue;
}

//Update Transfer Stock Detailed Cost
function PUT_TransferStockDetailedCost(json) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "ReceivingStockTransfer.aspx/PUT_TransferStockDetailedCost",
        data: "{'jsondata':'" + JSON.stringify(json) + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error PUT_TransferStockDetailedCost")
        },
        success: function (result) {
            returnvalue = result.d;
        }
    });
    return returnvalue;
}

function Generate_NewBatch(todb) {
    let batchid;
    var newbatchid;
    let batchidlength = '000000';
    let icad = JSON.parse(GET_InventoryCostAverageDetail(todb))

    if (icad.length > 0) {
        let lastbatchid = icad.at(-1);
        let batchid = parseInt(lastbatchid['batchid']) + 1;

        newbatchid = batchidlength + batchid;
        newbatchid = newbatchid.substr(newbatchid.length - batchidlength.length);
    } else {
        newbatchid = batchidlength + 1;
        newbatchid = newbatchid.substr(newbatchid.length - batchidlength.length);
    }

    return newbatchid;
        
}

function loaditemlist(itemarr) {
    const tblbody = document.getElementById('table-body-transfer-item')
    tblbody.innerHTML = "";

    $.each(itemarr['0']['receiveStockDetailedCosts'], function (key, detail) {
        let x = key + 1;
        let inventorydata = inventorydetaildata.filter((e) => e['inventoryid'] == detail['inventoryid'])
        let tr = document.createElement('tr');

        let tdcount = document.createElement('td');
        tdcount.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let count = document.createTextNode(x);

        let tdinventoryid = document.createElement('td');
        tdinventoryid.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let inventoryid = document.createTextNode(detail['inventoryid']);

        let tdbarcode = document.createElement('td');
        tdbarcode.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let barcode = document.createTextNode(inventorydata[0]['barcode'].toString().trim());

        let tdname = document.createElement('td');
        tdname.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let name = document.createTextNode(inventorydata[0]['name'].toString().trim());

        let tddesc = document.createElement('td');
        tddesc.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let desc = document.createTextNode(inventorydata[0]['description'].toString().trim());

        let tdunit = document.createElement('td')
        tdunit.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let unit = document.createTextNode('PCS')

        let tdbatch = document.createElement('td');
        tdbatch.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let batch = document.createTextNode(detail['batchid'].toString().trim());

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

        let tdquantity = document.createElement('td');
        tdquantity.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
        let quantity = document.createTextNode(detail['qty'].toFixed(2))

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

        let inputacceptqty = document.createElement('input')
        inputacceptqty.type = 'number'
        inputacceptqty.className = 'form-control'
        inputacceptqty.min = '0'
        inputacceptqty.id = 'input-acceptqty'
        inputacceptqty.value = detail['qty'].toFixed(2)
        if (detail['acceptedqty'] > 0) {
            inputacceptqty.value = detail['acceptedqty'].toFixed(2)
        }

        inputacceptqty.max = detail['qty'].toFixed(2)


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

        let inputrejectqty = document.createElement('input')
        inputrejectqty.type = 'number'
        inputrejectqty.className = 'form-control'
        inputrejectqty.value = detail['rejectedqty'].toFixed(2)
        inputrejectqty.min = '0'
        inputrejectqty.id = 'input-rejectqty'
       

        tdcount.appendChild(count);
        tdinventoryid.appendChild(inventoryid);
        tdbarcode.appendChild(barcode);
        tdname.appendChild(name);
        tddesc.appendChild(desc);
        tdunit.appendChild(unit);
        tdbatch.appendChild(batch);
        tdcost.appendChild(cost);
        tdquantity.appendChild(quantity);
        tdacceptqty.appendChild(inputacceptqty);
        tdrejectqty.appendChild(inputrejectqty);


        tr.appendChild(tdcount)
        tr.appendChild(tdinventoryid);
        tr.appendChild(tdbarcode);
        tr.appendChild(tdname);
        tr.appendChild(tddesc);
        tr.appendChild(tdunit);
        tr.appendChild(tdbatch);
        tr.appendChild(tdcost)
        tr.appendChild(tdquantity);
        tr.appendChild(tdacceptqty);
        tr.appendChild(tdrejectqty);


        $('#input-rejectqty').attr('disabled', 'disabled');

        tblbody.appendChild(tr);
    });
}

function Get_Inventories(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/GET_InventoryList",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function GET_Categories(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/GET_Categories",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function GET_InventoryCostAverageDetail(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/GET_InventoryCostAverageDetail",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function GET_InventoryCostAverage(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/GET_InventoryCostAverage",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function InventoryWithCostDetail(db) {
  
    let sessioncategory = GET_Categories(db);
    let sessionitem = Get_Inventories(db);
    
    let sessionica = GET_InventoryCostAverage(db);
    let sessionicadetail =GET_InventoryCostAverageDetail(db);
  
    let ica = JSON.parse(sessionica);
    
    let inventory = JSON.parse(sessionitem).filter((e) => e['Active'] != 0 && e['Barcode'].toLowerCase() != 'round' && e['Class'] == '0');
    let category = JSON.parse(sessioncategory).filter((e) => e['Active'] != 0 && e['CategoryName'].toLowerCase() != 'round');
    let icadetail = JSON.parse(sessionicadetail);
    let arrinventory = [];
    let arricadetail = [];

    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);
                    }
                });
            }
        });
    });

    return arrinventory;
}



function getDateTime() {
    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var day = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    if (month.toString().length == 1) {
        month = '0' + month;
    }
    if (day.toString().length == 1) {
        day = '0' + day;
    }
    if (hour.toString().length == 1) {
        hour = '0' + hour;
    }
    if (minute.toString().length == 1) {
        minute = '0' + minute;
    }
    if (second.toString().length == 1) {
        second = '0' + second;
    }
    var dateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    return dateTime;

}