let returndetail;
let branches = [];
let inventorydetaildata;
$(document).ready(function () {
    const urlParams = new URL(window.location.href).searchParams;
    const returnno = urlParams.get('ReturnNo');
    const transferno = urlParams.get('TransferNo');
    const dbname = urlParams.get('FromBranch');
    const todbname = urlParams.get('ToBranch');

   

    branches = JSON.parse(sessionStorage.getItem('branchlist'))
    let branch = branches.filter((e)=>e['fullname'].toLowerCase().trim() == dbname.toLowerCase().trim())
    //inventorydetaildata = JSON.parse(GET_InventoryDetail(branch[0]['name']));

    inventorydetaildata = InventoryWithCostDetail(branch[0]['name'])
    returndetail = JSON.parse(GET_ReturnStockList(branch[0]['name']));
    returndetail = returndetail.filter((e)=>e['returnno'].toLowerCase().trim() == returnno.toLowerCase().trim())


    $('#input-returnnumber').val(returndetail[0]['returnno'])
    $('#input-transfernumber').val(returndetail[0]['transferno'])
    $('#input-confirmnumber').val(returndetail[0]['confirmno'])
    $('#input-branchfrom').val(dbname)
    $('#input-returndate').val(returndetail[0]['returndate'].substring(0, 10));
    $('#input-returnstatus').val('Confirmed')
    $('#input-branchto').val(todbname)
    $('#input-user').val(returndetail[0]['employee'])

    load_returned_item(returndetail[0])

})

function GET_ReturnStockList(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "ReturnStockTransfer.aspx/GET_ReturnStockDetailList",
        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_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")
        },
        success: function (result) {
            returnvalue = result.d;
        }
    });
    return returnvalue;
}


function load_returned_item(data) {
    console.log(data['returnStockDetailedCosts'])
    const tblbody = document.getElementById('table-body-return-item')
    tblbody.innerHTML = "";

    $.each(data['returnStockDetailedCosts'], 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['returnqty'].toFixed(2))

      



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


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



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