//-------------------------------------------------------//
// Author:Rodolfo Machon
// Company:WebSoft, SA de CV 
// Nombre del archivo: recibo.p.js
// Created: 2022-09-23
// Updates: 2022-09-23
// Copyright - All Rights Reserved
//-------------------------------------------------------//
//-------------------------------------------------------//
var numbers		= new makeArray0('','un','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez','once','doce','trece','catorce','quince','dieciseis','diecisiete','dieciocho','diecinueve','veinte');
var numbers10	= new makeArray0('','diez','veinte','treinta','cuarenta','cincuenta','sesenta','setenta','ochenta','noventa');
var numbers20	= new makeArray0('','diez','veinti','treinta','cuarenta','cincuenta','sesenta','setenta','ochenta','noventa');
var numbers100	= new makeArray0('','cien','doscientos','trescientos','cuatrocientos','quinientos','seiscientos','setecientos','ochocientos','novecientos');
var Numbers100	= new makeArray0('','ciento','doscientos','trescientos','cuatrocientos','quinientos','seiscientos','setecientos','ochocientos','novecientos');
//-------------------------------------------------------//
( async function() {
	user = await fetchData('user.data','');
	//console.log(user);
	let data = {"mid":document.getElementById('mid').value};
	let mandamiento =  await fetchData('mandamiento.data',data);
	//console.log(mandamiento);
	let mandamientoD =  await fetchData('mandamientoDetalle.data',data);
	let table= construcTable(mandamientoD);
	let total= getTotal(mandamientoD);
	constructPage(mandamiento,table,total);
})();
//-------------------------------------------------------//
//LEVEL 1
function constructPage(m,table,total){
	//console.log(m);
	document.querySelector(".expediente").innerHTML = m.i8_expediente_id;	
	document.querySelector(".contribuyente").innerHTML = m.v128_contribuyente;
	document.querySelector(".ubicacion").innerHTML = m.txt_expediente_direccion;	
	document.querySelector(".emision").innerHTML = m.dt_emision;
	document.querySelector(".concepto").innerHTML = m.txt_concepto;	
	document.querySelector(".total").innerHTML = total;
	document.querySelector(".son").innerHTML = chequeAmount(total);
	
	document.querySelector(".tabla").innerHTML = table;
	const html = document.getElementById("recibo").innerHTML;
    var clone = document.createElement('span');
    clone.innerHTML = html;	
	document.getElementById("reciboCopia").appendChild(clone);
	
}
function construcTable(man){
	let header = `<tr><td>Codigo</td><td>Rubros</td><td>Desde</td><td>Hasta</td><td>Cant</td><td>Unitario</td><td>Sub-Total</td></tr>`;
	let body = constructBody(man);
	let table = `<table class='grid'><thead>${header}</thead><tbody>${body}</tbody></table>`;
	return table;
}
function getTotal(man){
	let total = 0;
	Object.keys(man).forEach(function(key) {
		let subtotal = (man[key][0]*1)*(man[key][4]*1);
		total += subtotal;
	});	
	return total.toFixed(2);
}
async function processRecibo(){
    document.getElementById('process').style.display = 'none';
	window.print();
	let recibo = await fetchData("recibo.actual.data",{"i2_cajero_id":user.cajaID,"i8_user_id":user.id});
	if(recibo!=""){
		document.getElementById('recibo_libro').value = recibo.c16_recibo_actual;
		document.getElementById('save').style.display = 'inline';
	}
}
async function saveRecibo(){
	let mid = document.getElementById('mid').value;
	let reciboLibro = document.getElementById('recibo_libro').value;
	let reciboActual = await fetchData("recibo.data",{"id":reciboLibro});
	if(reciboActual.c16_recibo_id!=reciboLibro){
		let data = {"mandamientoID":mid,"reciboID":reciboLibro,"cajaID":user.cajaID,"cajeroID":user.id};
		//console.log(data);
		let reciboNuevo =  await fetchData("recibo.s",data);
		window.close();
	}else{
		alert("El numero de Recibo ya existe, favor introducir el numero de recibo en el documento impreso");
	}
}
//-------------------------------------------------------//
//LEVEL 2
function constructBody(man){
	let body = "";
	Object.keys(man).forEach(function(key) {
		let row = "";
		let ini = "";
		let fin = "";		
		if(man[key][5]!==""){
			let periodos = man[key][5].split("~");
			let periodo_ini = periodos[0].split(",");
			let periodo_fin = periodos[periodos.length-1].split(",");
			ini = periodo_ini[0];
			fin = periodo_fin[0];
		}
		let qty = (man[key][0]*1).toFixed(2);
		let unitario = (man[key][4]*1).toFixed(2);
		let subTotal = (qty*unitario).toFixed(2);
		row = `<tr><td>${man[key][2]}</td><td>${man[key][3]}</td><td>${ini}</td><td>${fin}</td><td>${qty}</td><td>${unitario}</td><td>${subTotal}</td></tr>`;
		body += row;
	});	
	return body;
}
//-------------------------------------------------------//
//AUXILIAR
function fetchData(endPoint,data){
    return new Promise(resolve => {
		var r = new XMLHttpRequest();
		r.open("POST",'../pl/'+endPoint+".pl", true);
		r.setRequestHeader("Content-Type", "application/json");
		r.send(JSON.stringify(data));	
		r.onreadystatechange = function () {
			if (r.readyState != 4 || r.status != 200) return;
			//console.log(endPoint);			
			//console.log(r.responseText);
			resolve(JSON.parse(r.responseText));
		};		
    }); 
}
function chequeAmount(input){
    var re=/^((\d*)|(\d*(\.\d{1,2})))$/;
    if (!re.test(input)){
        alert("Datos incorrectos en monto, no usar ','\n Ej: 1564.93");
    }else{
        var dollars     = Math.floor(input);
        var cents       = Math.round((input*100 - dollars*100));
        
		var thousands   = (dollars - dollars % 1000) / 1000;
        dollars        -= thousands * 1000;
        var hundreds    = (dollars - dollars % 100) / 100;
        dollars        -= hundreds * 100;
        var output      = '';
        output 			+= (thousands > 0 ? fN(thousands) + ' mil ' : '') + (hundreds > 0 ?  FN(hundreds,dollars) + ' ' : '') + (dollars > 0 ? fN(dollars) + ' ' : '') + 'con '+cents + '/100 dolares';
        output          = output.toUpperCase();
        return output.substring(0,1).toUpperCase() + output.substring(1);
    }
}
function FN(i,b){
    if ((i == 1)&&(b > 0)){		
	return Numbers100[i];
    }else{
        if (i<20) return numbers100[i];
    }
    var tens = (i - i % 10) / 10, units = i - (i - i % 10);
    return numbers10[tens] + ((tens > 0 && units > 0) ? '-' : '') + numbers[units];
}
function fN(i) {
    if (i<=20) return numbers[i];
    var tens = (i - i % 10) / 10, units = i - (i - i % 10);
    if ( (i > 20)&&(i <= 30) ){
            return numbers20[tens] + ((tens > 0 && units > 0) ? '' : '') + numbers[units];
    }
    if ((i>30)&&(i<100)){
            return numbers10[tens] + ((tens > 0 && units > 0) ? ' y ' : '') + numbers[units];
    }
    if (i>=100 && i<110){
            let str   = i+"";
            let hunds  = str.substr(0,1);
            tens   = str.substr(1,1);
            units  = str.substr(2,1);
            return Numbers100[hunds] + ((hunds > 0 && tens > 0) ? ' ' : ' ') + numbers100[tens] + ((tens > 0 && units > 0) ? ' y ' : '') + numbers[units];    
    }
    if (i>=110 && i<120){
            let str   = i+"";
            let hunds  = str.substr(0,1);
            tens   = 0;	    
            units  = str.substr(1,2);
            return Numbers100[hunds] + ((hunds > 0 && tens > 0) ? ' ' : ' ') + numbers100[tens] + ((tens > 0 && units > 0) ? ' y ' : '') + numbers[units];    
    }   
    if ((i>=120 && i<130)||(i>=220 && i<230)||(i>=320 && i<330)||(i>=420 && i<430)||(i>=520 && i<530)||(i>=620 && i<630)||(i>=720 && i<730)||(i>=820 && i<830)||(i>=920 && i<930)){
            let str   = i+"";
            let hunds = str.substr(0,1);
            tens   = str.substr(1,1);	    
            units  = str.substr(2,1);
            return Numbers100[hunds] + ((hunds > 0 && tens > 0) ? ' ' : ' ') + numbers20[tens] + ((tens > 0 && units > 0) ? '' : '') + numbers[units];    
    }
    if (i>=130 && i<=999){
		let str   = i+"";
		let hunds = str.substr(0,1);
		tens   = str.substr(1,1);
		units  = str.substr(2,1);
		return Numbers100[hunds] + ((hunds > 0 && tens > 0) ? ' ' : ' ') + numbers10[tens] + ((tens > 0 && units > 0) ? ' y ' : '') + numbers[units];    
    }
}
function fN1(i) {
    if (i<10) return Numbers100[i];
}
function makeArray0() {
    for (i = 0; i<makeArray0.arguments.length; i++)
    this[i] = makeArray0.arguments[i];
}
/*
function printDiv() {
	var divContents = document.getElementById("GFG").innerHTML;
	var a = window.open('', '', 'height=500, width=500');
	a.document.write('<html>');
	a.document.write('<body > <h1>Div contents are <br>');
	a.document.write(divContents);
	a.document.write('</body></html>');
	a.document.close();
	a.print();
}
*/
