let returnstocklist;
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())    
    returnstocklist = JSON.parse(GET_ReturnStockList(db[0]['name']));
    load_returnstock_table(returnstocklist)*/
})


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

function ini_data(selecteddb,fromdate,todate){
    let currentbranchname = selecteddb;
    branches = JSON.parse(sessionStorage.getItem('branchlist'))

    let db = branches.filter((e) => e['fullname'].toLowerCase().trim() == currentbranchname.toLowerCase().trim())    
    returnstocklist = JSON.parse(GET_ReturnStockList(db[0]['name']));
    //console.log(returnstocklist)
    returnstocklist = returnstocklist.filter((e) => e['returndate'].substring(0, 10) >= fromdate && e['returndate'].substring(0, 10) <= todate);
    load_returnstock_table(returnstocklist)
}

function load_returnstock_table(data){        
    const tblbody = document.getElementById('table-body-returnstock')
    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['returnflag'] == 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 tdreturnno = document.createElement('td');
        tdreturnno.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let returnno = document.createTextNode(detail['returnno'].toString().trim());        

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

        //receiveno
        let tdreceiveno = document.createElement('td');
        tdreceiveno.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let receiveno = document.createTextNode(detail['confirmno'].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 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 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['returndate'].replace("T", " ").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('Confirmed');

        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);
        tdreturnno.appendChild(returnno)
        tdtransferno.appendChild(transferno);
        tdreceiveno.appendChild(receiveno)
        tdto.appendChild(to);
        tdfrom.appendChild(from);
        tddate.appendChild(date);              
        tdstatus.appendChild(status);
        tdaction.appendChild(action);

        tr.appendChild(tdnumber);
        tr.appendChild(tdreturnno)
        tr.appendChild(tdtransferno);        
        tr.appendChild(tdreceiveno)
        tr.appendChild(tdto);
        tr.appendChild(tdfrom);
        tr.appendChild(tddate);               
        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) {
    let branches = [];
    console.log(branchlist)
    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 GET_ReturnStockList(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "StockReturn.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;
}