let receivedata;
let branches = [];
$(document).ready(function () {          
    /*let currentbranchname = getSelectedBranch();
    branches = JSON.parse(sessionStorage.getItem('branchlist'))

    let db = branches.filter((e) => e['fullname'].toLowerCase().trim() == currentbranchname.toLowerCase().trim())    
    receivedata = JSON.parse(get_ReceiveStockList(db[0]['name']));
    load_receivestock_table(receivedata)*/
})

$(document).on('click', 'button', function () {
    if ($(this)[0].innerHTML.toLowerCase().trim() == 'view detail') {  
    
        let tobranch = $(this).closest('tr').find('td:eq(1)').text();    
        let transferno = $(this).closest('tr').find('td:eq(1)').text();
        let branch = branches.filter((e)=>e['fullname'].toLowerCase().trim() == getSelectedBranch().toLowerCase().trim())
    
        window.location.href = '/ReceivingStockTransfer.aspx?ToBranch=' + branch[0]['name'] + '&TransferNo=' + transferno;
        //ReceivingStockTransfer.aspx?ToBranch=da1&TransferNo=AMK-0000002
    }
   
});

//initialize
function ini_data(currentbranch,fromdate,todate){
    
    let currentbranchname = currentbranch;
  
    branches = JSON.parse(sessionStorage.getItem('branchlist'))
    let db = branches.filter((e) => e['fullname'].toLowerCase().trim() == currentbranchname.toLowerCase().trim())    

    receivedata = JSON.parse(get_ReceiveStockList(db[0]['name']));
    //console.log(receivedata)
    receivedata = receivedata.filter((e) => e['senddatetime'].substring(0, 10) >= fromdate && e['senddatetime'].substring(0, 10) <= todate);
    //console.log(receivedata)
    load_receivestock_table(receivedata)
}

//get receivestocklist
function get_ReceiveStockList(db) {    
    var RetValue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.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;
}


function load_receivestock_table(data){    
    const tblbody = document.getElementById('table-body-receivestock')
    if (tblbody == null) {
        return
    }
    
    tblbody.innerHTML = "";
    $.each(data, function (key, detail) {      
        let frombranch = branches.filter((e) => e['branchid'] == detail['frombranchid'])
        let tobranch = branches.filter((e) => e['branchid'] == detail['tobranchid'])

        let tr = document.createElement('tr');
        //send status
        let sendstatus;
        if (detail['confirmflag'] == 0) {
            sendstatus = 'Pending'
        } else {
            sendstatus = 'Confirmed'
        }


        let tdnumber = document.createElement('td');
        tdnumber.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let number = document.createTextNode(parseInt(key) + 1);

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

        let tddate = document.createElement('td');
        tddate.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let date = document.createTextNode(detail['transferdate'].replace("T", " ").toString().trim());

        let tdfrom = document.createElement('td');
        tdfrom.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center text-capitalize';
        let from = document.createTextNode(frombranch[0]['fullname'].toString().trim());

        let tdto = document.createElement('td');
        tdto.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center text-capitalize';
        let to = document.createTextNode(tobranch[0]['fullname'].toString().trim());

        let tdstatus = document.createElement('td');
        tdstatus.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let status = document.createTextNode(sendstatus.toString().trim());

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

        //let action = document.createTextNode(sendstatus.toString().trim());
        //action.id = 'btn-' + detail['transferno'].toString().trim();
        var action = document.createElement('div')
        action.id = Math.random().toString(16).substring(2, 16);


        tdnumber.appendChild(number);
        tdtransferno.appendChild(transferno);
        tddate.appendChild(date);
        tdfrom.appendChild(from);
        tdto.appendChild(to);
        tdstatus.appendChild(status);
        tdaction.appendChild(action);

        tr.appendChild(tdnumber);
        tr.appendChild(tdtransferno);
        tr.appendChild(tddate);
        tr.appendChild(tdfrom);
        tr.appendChild(tdto);
        tr.appendChild(tdstatus);
        tr.appendChild(tdaction);

        tblbody.appendChild(tr);


        var viewdetail = document.createElement('button')
        viewdetail.type = 'button'
        viewdetail.className = 'btn btn-outline-primary btn-xs m-1'
        viewdetail.innerText = 'View Detail'
        document.getElementById(action.id).appendChild(viewdetail);
    });
}

function loadbranches(branchlist) {
    console.log(branchlist)
    let branches = [];
    for (const item of branchlist) {
        var branch = {
            'branchid': item[0],
            'name': item[1].toLowerCase().trim(),
            'fullname': item[2].toLowerCase().trim(),
            'prefix': item[4].toLowerCase().trim(),
        }
        branches.push(branch)
    }
    sessionStorage.setItem('branchlist', JSON.stringify(branches))
}

function getBatchID() {
    let token = bearertoken();
    let db = loadDB();
    let batchid;
    var newbatchid;
    let batchidlength = '000000';
    var settings = {
        "url": url + "/api/" + db + "/InventoryCostAverageDetail/GetInventoryCostAverageDetail",
        "method": "GET",
        "async": false,
        "timeout": 0,
        "headers": {
            "Authorization": token
        },
    };

    $.ajax(settings).done(function (response) {
        let data = JSON.parse(response);
        data.sort(function (a, b) {
            return a['batchid'].localeCompare(b['batchid'])
        });

        //console.log(data)

        if (data.length > 0) {
            let lastbatchid = data.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);
        }

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

    return newbatchid;
}


