const { getFontSize } = require("../../controller/documentacion/documentacion");
const { style } = require('./style');

const validaciones = [];

const pages_border = {
    border_left: 15,
    border_top: 0,
    border_right: 15,
    border_bottom: 0,
    header_height: 10,
    footer_height: 15
};

const pagare = async(parametros, imagen, fuente) => {
    const empresa = parametros['empresa'];
    const acreditado = parametros['acreditado'];
    const prestamo = parametros['prestamo'];
    const tabla_amortizacion = parametros['tabla_amortizacion'];
    const avales = parametros['avales'];
    const garantes = parametros['garantes'];
    const lista_acreditados = parametros['lista_acreditados'];
    const reca = prestamo.documentacion.reca;
    return `
        <!doctype html>
        <html>

        <head>
            <meta charset="utf-8">
            <title>Pagare</title>
            <style>
                ${await style(fuente)}

            </style>
        </head>
        
        <body>
          <!--  <div id="pageHeader">
                <div align='center' class="font-sucursal">
                    ${empresa.nombre}
                </div>
            </div> -->
            
            <div id="pageFooter">
                <table m-none>
                    <tr class="py-none m-none">
                       <!-- <td class="text-center noborder py-none font-sucursal m-none" style="width: 90%;">
                            Registro RECA: ${reca.split('/')[0]}
                        </td> -->
                        <td class="page_number text-right noborder py-none m-none fontsize9" style="width:10%">
                            {{page}}/{{pages}}
                        </td>
                    </tr>
                </table>
            </div>
            <div class="text-center">
                <b>PAGARÉ ${esValido(lista_acreditados)? 'GRUPAL':''}</b>
            </div>
            <div class="col-max my"></div>
            ${cuerpoPagare(empresa, prestamo, acreditado)}
            <div class="col-max my"></div>
            <p>El presente pagaré se suscribe en <b>${empresa.domicilio.entidad_descripcion}</b>  con fecha <b>${prestamo.fecha_impresion_letra}.</b></p>
            <div class="col-max my"></div>

            ${seccionFirmas(acreditado, avales, garantes, lista_acreditados, parametros['tipo_persona'])}
        </body>
    `;
}

const fechaImporte = (prestamo) => {
    return `
        <table>
            <tr class="">
                <td class="noborder row2"></td>
                <td class="noborder row4 py-chico text-left">
                    <b>Monto:</b>
                </td>
                <td class="noborder row4 py-chico text-right">
                    <b>${prestamo.importe}</b>
                </td>
            </tr>
            <tr class="">
                <td class="noborder row2"></td>
                <td class="noborder row4 py-chico text-left">
                    <b>Fecha de Vencimiento:</b>
                </td>
                <td class="noborder row4 py-chico text-right">
                    <b>${prestamo.fecha_vencimiento}</b>
                </td>
            </tr>
        </table>
    `;
}

const cuerpoPagare = (empresa, prestamo, acreditado) => {
    return `
        <div class="text-justify">
            <p>
                POR EL PRESENTE PAGARÉ YO, <b>${acreditado.nombre_completo}</b>,(en lo sucesivo suscriptor) PROMETO PAGAR INCONDICIONALMENTE A LA ORDEN DE <b>${empresa.nombre}</b>, EN SU DOMICILIO UBICADO EN <b>${empresa.domicilio.domicilio_completo}</b> O EN CUALQUIERA DE SUS SUCURSALES, LA CANTIDA TOTAL DE <b>${prestamo.importe} (${prestamo.importe_letra})</b> COMO SUMA PRINCIPAL, MEDIANTE <b>${prestamo.pagares} ${prestamo.descripcion_pago_plural}</b> IGUALES Y CONSECUTIVOS, LOS CUALES CONTEMPLAN INTERESES, Y CAPITAL, EN RAZÓN DE LA FECHA DE PRESENTACIÓN PARA EL PAGO TOTAL DEL MISMO, ESTABLECIENDO COMO FECHA DE PRIMER
                PAGO EL DÍA <b>${prestamo.fecha_primer_pago_letra}</b>  Y DÍA DE PAGOS SUBSECUENTES EL DÍA <b>${prestamo.dia_pago !== undefined ? prestamo.dia_pago : "--"}</b> DE CADA MES, HASTA LA FECHA DEL PAGO TOTAL DEL PRESENTE PAGARÉ LA CUAL SERÁ EL DÍA <b>${prestamo.fecha_vencimiento_letra}</b>, SALVO QUE SE INCUMPLA EN UNO O MÁS PAGOS, SUCESIVOS O ALTERNOS, EN CUYO CASO LA PRESENTACIÓN PODRÁ EFECTUARSE EN CUANTO OCURRA TAL SUPUESTO
            </p>
            <p>
                A PARTIR DE LA SUSCRIPCIÓN DEL PRESENTE PAGARÉ, LA SUMA PRINCIPAL GENRARÁ INTERESES ORDINARIOS SOBRE SALDOS INSOLUTOS EN FORMA MENSUAL CONTADOS A PARTIR DE LA FECHA DE DISPOSICIÓN A LA TASA DE INTERÉS ANUAL QUE RESULTE DEL <b>${prestamo.intn}</b>.
            </p>
            <p>
                PARA EL CASO DE QUE NO SE REALICE EL PAGO DE UNA CUOTA MENSUAL EN LA FECHA QUE SEA PAGADERA, SE ESTARÁ INCURRIENDO EN MORA Y POR TANTO "EL SUSCRIPTOR" Y/O SU AVAL, ESTARÁ OBLIGADO A PAGAR 1.5% DE INTERÉS DEL CAPITAL VENCIDO POR DÍA, CONTADO A PARTIR DESDE EL PRIMER DÍA DE ATRASO Y HASTA QUE EFECTIVAMENTE SE CUBRAN DICHOS MONTOS.
            </p>
            <p>
                TODOS LOS PAGOS DE PRINCIPAL E INTERESES RELATIVOS AL PRESENTE PAGARÉ, SE HARÁN SIN QUE PROCEDA COMPENSACIÓN ALGUNA Y NO PODRÁN SUJETARSE A CUALQUIER DEDUCCIÓN O A CUALQUIER RETENCIÓN PARA, O A CUENTA DE CUALQUIER IMPUESTO, CARGO, DERECHO, MULTA O CUALESQUIERA OTROS CONCEPTOS SIMILARES, PRESENTES O FUTUROS, DE CUALQUIER NATURALEZA, IMPUESTOS O ESTABLECIDOS POR LOS ESTADOS UNIDOS MEXICANOS Y/O CUALQUIERA DE SUS SUBDIVISIONES POLÍTICAS, CON LA SALVEDAD DE QUE LA CANTIDAD PAGADERA CONFORME AL PRESENTE PAGARÉ, SE INCREMENTARÁ EN UNA SUMA EQUIVALENTE AL DIECISÉS POR CIENTO DEL IMPORTE DE LOS INTERESES QUE SE DEVENGUEN, POR CONCEPTO DEL IMPUESTO AL VALOR AGREGADO (EL <b>"IVA"</b>), OBLIGÁNDOSE EL(LOS) SUSCRIPTOR(ES) Y EL(LOS) OBLIGADO(S) SOLIDARIO(S), A CUBRIR TAL CANTIDAD AL TENEDOR DEL PRESENTE PAGARÉ AL MOMENTO DE EFECTUAR PAGOS DE INERESES. EN CASO DE PAGO PARCIAL DE LA SUMA PRINCIPAL, DICHO PAGO SE APLICARÁ EN PRIMER ORDEN, A INTERESES DEVENGADOS, NO PAGADOS Y AL CORRESPONDENTE IVA, POR LO QUE UNA VEZ SATISFECHOS LOS INTERESES E IVA, SE APLICARÁ A LA SUMA PRINCIPAL.
            </p>
            <p>
                PARA LA INTERPRENTACIÓN, CUMPLIMIENTO Y EJEUCIÓN DEL PRESENTE PAGARÉ, EL(LOS) SUSCRIPTOR(ES) Y EL(LOS) OBLIGADO(S),SE SOMETEN IRREVOCABLEMENTE A LA JURISDICCIÓN Y COMPETENCIA DE LOS TRIBUNALES DE LA CIUDAD DE MÉXICO, ASÍ COMO A LAS LEYES VIGENTES EN LOS ESTADOS UNIDOS MEXICANOS, RENUNCIANDO EXPRESAMENTE A CUALQUIER OTRO FUERO QUE PUDIERA CORRESPONDERLES EN RAZÓN DE SUS DOMICILIOS PRESENTES O FUTUROS.
            </p>
        </div>
    `;
}

const tablaAmortizacion = (tabla_amortizacion) => {
    let amortizaciones = `
        <table>
            <tr>
                <td class="noborder py-chico  text-center">
                    <b>N° Pago</b>
                </td>
                <td class="noborder py-chico  text-center">
                    <b>Fecha de Pago</b>
                </td>
                <td class="noborder py-chico  text-center">
                    <b>Capital</b>
                </td>
                <td class="noborder py-chico  text-center">
                    <b>Interes</b>
                </td>
                <td class="noborder py-chico  text-center">
                    <b>IVA
                </td>
                <td class="noborder py-chico  text-center">
                    <b>Total a Pagar</b>
                </td>
                <td class="noborder py-chico  text-center">
                    <b>Saldo Insoluto</b>
                </td>
            </tr>
    `;
    tabla_amortizacion.forEach(amortizacion => {
        amortizaciones += `
                <tr>
                    <td class="noborder py-chico text-center border-top border-bottom">
                        ${amortizacion.pagare}
                    </td>
                    <td class="noborder py-chico text-center border-top border-bottom">
                        ${amortizacion.fecha_pago}
                    </td>
                    <td class="noborder py-chico text-right border-top border-bottom">
                        ${amortizacion.capital}
                    </td>
                    <td class="noborder py-chico text-right border-top border-bottom">
                        ${amortizacion.interes}
                    </td>
                    <td class="noborder py-chico text-right border-top border-bottom">
                        ${amortizacion.iva}
                    </td>
                    <td class="noborder py-chico text-right border-top border-bottom">
                        ${amortizacion.total}
                    </td>
                    <td class="noborder py-chico text-right border-top border-bottom">
                        ${amortizacion.saldo}
                    </td>
                </tr>
            `;
    });
    amortizaciones += `</table>`;
    return amortizaciones;
}

const seccionFirmas = (acreditado, avales, garantes, lista_acreditados, tipo_persona) => {
        let encabezado_grupal = `
        <tr>
            <td class="row3 noborder text-center">
                <b>INTEGRANTES DEL GRUPO</b>
            </td>
            <td class="noborder" style="width:10%">
            </td>
            <td class="noborder text-center" style="width:15%">
                <b>Firma</b>
            </td>
        </tr>
        </table>
    `;
        let encabezado_individual = `
        <tr>
            <td class="row3 noborder text-center">
                <b>SUSCRIPTOR</b>
            </td>
            <td class="noborder" style="width:10%">
            </td>
            <td class="row4 noborder text-center" style="width:15%">
                <b>Firma</b>
            </td>
        </tr>
        </table>
    `;
        let firmas = `<table>`;
        if (esValido(lista_acreditados)) {
            firmas += encabezado_grupal;
            lista_acreditados.forEach((acreditado, index) => {
                firmas += `
                <table class="saltodePag">
                    <tr class="">
                        <td class="row3 noborder saltodePag fontsize8 px-none">
                            <b>${index+1}.- C.</b> <u> ${acreditado.nombre_completo !== undefined ? acreditado.nombre_completo:''}.</u>
                            <br>
                            <b>Domicilio:</b> ${acreditado.domicilio_completo !== undefined ? acreditado.domicilio_completo: ''}
                            <hr class="hrBajo">
                        </td>
                        <td class="noborder px-none" style="width:10%">
                        </td>
                        <td class="noborder saltodePag fontsize8 px-none" valign="bottom" style="width:15%">
                            <hr class="hrBajo">
                        </td>
                    </tr>
                </table>
            `;
            })
        } else {
            firmas += encabezado_individual;
            firmas += `
        <table>
            <tr>
                <td class="row3 noborder fontsize8 px-none">
                    <b>C.</b><u> ${tipo_persona == 'F'? acreditado.nombre_completo: acreditado.acreditado_representante}.</u>
                    <br>
                    <b>RFC:</b><u>${acreditado.rfc}</u>
                    
                    <span>${tipo_persona == 'M'? `<br>Por propio derecho o en representación legal del “CLIENTE”`: ''}</span>
                    <br>
                    <b>Domicilio:</b> ${acreditado.domicilio_personal.domicilio_completo}
                    <hr class="hrBajo">
                </td>
                <td class="noborder" style="width:10%">
                </td>
                <td class="noborder fontsize8 px-none" valign="bottom" style="15%">
                    <hr class="hrBajo">
                </td>
            </tr>
        </table>
        `;
        if (esValido(avales)) {
            firmas += `<table>${firmasAvales(avales)}</table>`;
        }
    }
    // firmas += `</table>`;
    return firmas;
}

const firmasAvales = (avales) => {
    let firmas_avales = `
        <tr>
            <td class="row3 noborder text-center">
                <b>AVALES</b>
            </td>
            <td class="noborder" style="width:10%">
            </td>
            <td class="noborder text-center " style="width:15%">
                <b>Firma</b>
            </td>
        </tr>
    `;
    avales.forEach((aval, index) => {
        firmas_avales += `
            <tr>
                <td class="row3 noborder fontsize8">
                    <b>${index+1}.- C.</b> <u>${aval.nombre_completo}</u>
                    <br>
                    <b>Clave Elector: </b><u>${aval.clave_elector !== undefined ? aval.clave_elector : "------"}</u>
                    <br>
                    <b>CURP: </b><u>${aval.curp !== undefined ? aval.curp : "--------"}</u>
                    <br>
                    <b>Domicilio:</b> ${aval.domicilio_completo}
                    <hr class="hrBajo">
                </td>
                <td class="noborder" style="width:10%">
                </td>
                <td class="noborder fontsize8 px-none" valign="bottom" style="width:15%">
                    <hr class="hrBajo">
                </td>
            </tr>
        `;
    })
    return firmas_avales;
}

const firmasGarantes = (garantes) => {
    let firmas_garantes = `
        <tr>
            <td class="row3 noborder text-center">
                <b>GARANTES HIPOTECARIOS</b>
            </td>
            <td class="noborder" style="width:10%">
            </td>
            <td class="noborder text-center" style="width:15%">
                <b>Firma</b>
            </td>
        </tr>
    `;
    garantes.forEach((garante, index) => {
        firmas_garantes += `
            <tr>
                <td class="row3 noborder fontsize8">
                    <b>${index+1}.- C.</b> <u>_${garante.nombre_completo}.</u>
                    <br>
                    <b>Domicilio:</b> ${garante.domicilio_completo}
                    <hr class="hrBajo">
                </td>
                <td class="noborder" style="width:10%">
                </td>
                <td class=" noborder  px-none" valign="bottom" style="width:15%">
                    <hr class="hrBajo">
                </td>
            </tr>
        `;
    })
    return firmas_garantes;
}

const esValido = (array_objetos) => {
    if (array_objetos == undefined || array_objetos.length === 0 || (array_objetos.length === 1 && Object.entries(array_objetos[0]).length === 0)) {
        return false;
    }
    return true;
}

module.exports = {
    pagare,
    validaciones,
    pages_border
}