<section class="invoice">
    <form id="cotizacion" onsubmit="return false;" method="post" name="cotizacion">
        {% include 'ventas/vistas/cotizaciones/cotizacion/cabecera.html.php' %}
        {% include 'ventas/vistas/cotizaciones/cotizacion/servicios.html.php' %}
        {% include 'ventas/vistas/cotizaciones/cotizacion/tabla.html.php' %}
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-12">
                        <label for="valorServicio">Observaciones/Detalles:</label>
                        <textarea class="form-control" rows="5" id="Observaciones" name="Observaciones" placeholder="Observaciones/Detalles"></textarea>
                    </div>
                </div>
            </div>
        </div>
        {% include 'ventas/vistas/cotizaciones/cotizacion/pie.html.php' %}
    </form>
</section>

<script type="text/javascript" src="componentes/ventas/recursos/js/ventas.js" ></script>                
<script type="text/javascript">
    
    var valorBruto = "0";
    var IVA = "0";
    var valorNeto = "0";
    var jason = "";
    var item_ID = "0";
    var tablaCotizacion = $('#tablaItems').DataTable();
    
    $(document).ready(function(){
        $("#valorBruto").val("0");
        $("#IVA").val("0");
        $("#valorNeto").val("0");
        
        {% if CotizacionEditar is defined %}
            {% for CotizacionEditar in CotizacionEditar %}
                console.log({{CotizacionEditar.itemServicioID}});
                var bruto = parseInt({{CotizacionEditar.itemCANTIDAD}})*parseInt({{CotizacionEditar.itemVLRUNITARIO}});
                var total = parseInt(bruto) + parseInt({{CotizacionEditar.itemVLRIMPUESTOS}});
                tablaCotizacion.row.add( [
                "<p class='hidden'>" + {{CotizacionEditar.itemID}} +"-</p><p class='hidden'>"+{{CotizacionEditar.itemServicioID}}+"</p><button type='button' class='btn btn-danger borrarServicio' onclick='eliminar(this);'><i class='fa fa-trash-o' aria-hidden='true'></i></button>&nbsp;<button type='button' class='btn btn-warning editarServicio' onclick='editar(this,"+{{CotizacionEditar.itemID}}+","+{{CotizacionEditar.itemCategoriaID}}+","+{{CotizacionEditar.itemServicioID}}+");'><i class='fa fa-pencil-square-o' aria-hidden='true'></i></button>",
                "{{CotizacionEditar.itemDESCRIPCION}}",
                {{CotizacionEditar.itemCANTIDAD}},
                {{CotizacionEditar.itemVLRUNITARIO}},
                {{CotizacionEditar.itemIMPUESTO}}+"%",
                {{CotizacionEditar.itemVLRIMPUESTOS}},
                total
                ] ).draw( false );
                
                valorBruto = (parseInt(valorBruto) + parseInt(bruto));
                IVA = (parseFloat(IVA) + parseFloat({{CotizacionEditar.itemVLRIMPUESTOS}}));
                valorNeto = (parseFloat(valorBruto) + parseFloat(IVA));
                valorNeto = Math.round(valorNeto);
                
                document.getElementById("valorBruto").value = valorBruto;
                document.getElementById("IVA").value = IVA;
                document.getElementById("valorNeto").value = valorNeto;
                $("#Observaciones").val("{{CotizacionEditar.cotizacionOBSERVACIONES}}");
            {% endfor %}   
        {% endif %}   
    });
    
    function activarBoton() {
        $("#btnCedulaCliente").removeAttr("disabled");
    }
    
    $("#btnCedulaCliente").click(function () {
        verificarIdentificacionCliente($('#cedulaCliente').val(), $('#tipoDocumento').val(), actualizarDatosCliente);
    });

    
    function actualizarDatosCliente(datos) {
        console.log(datos);
        if(datos.RESPUESTA == "EXITO"){
                    var Persona = datos.Persona;
                    $("#cedulaCliente").val(Persona.personaIDENTIFICACION);
                    $("#nombreCliente").val(Persona.personaNOMBRES + " " + Persona.personaAPELLIDOS);
                    $("#direccionCliente").val(Persona.direccionDOMICILIO);
                    $("#telefonoCliente").val(Persona.telefonoFIJO);
                    $("#correoCliente").val(Persona.personasCorreoPRINCIPAL);
                }else{
                   $("#nombreCliente").attr("placeholder","NO SE ENCONTRÓ PERSONA CON LA IDENTIFICACIÓN DIGITADA."); 
                    $("#nombreCliente").val("");
                    $("#direccionCliente").val("");
                    $("#telefonoCliente").val("");
                    $("#correoCliente").val("");
                }
    }
                
    
    
    function cargarServicios() {
        ejecutarOperacion("ventas","cotizaciones", "servicios", "categoria=" + $('#categoriaServicio').val(),
        function (datos){
            if(datos.RESPUESTA == "EXITO"){
            var Servicios = datos.Servicios;
            var num_servicios = Servicios.length;
            document.getElementById('ServiciosCargados').length = num_servicios;
            for (i = 0; i < num_servicios; i++) {
                document.getElementById('ServiciosCargados').options[i].value = Servicios[i].servicioID;
                document.getElementById('ServiciosCargados').options[i].text = Servicios[i].servicioTITULO;
            }
            }else {
                document.getElementById('ServiciosCargados').options[0].value = "0";
                document.getElementById('ServiciosCargados').options[0].text = "Seleccione...";  
            }
        });
    }
    
    function mostrarServicio(servicio) {
        document.getElementById('descripcionServicio').value = servicio;
    }
    
    function agregarServicio () {
        
        var Categoria = $("#categoriaServicio").val();
        var Servicio = $("#ServiciosCargados").val();
        var descripcionServicio = $("#descripcionServicio").val();
        var Cantidad = $("#Cantidad").val();
        var Valor = $("#valorServicio").val();
        var vlrservicio = (parseInt(Cantidad) * parseInt(Valor));
        var iva = 0.19;
        var vlriva = (parseInt(vlrservicio) * parseFloat(iva));
        iva = "19%";
        var total = (parseInt(vlrservicio) + parseInt(vlriva));
        
        if (descripcionServicio !== "" && Cantidad !== "" && Valor !== "") {
            valorBruto = (parseInt(valorBruto) + parseInt(vlrservicio));
            IVA = (parseFloat(IVA) + parseFloat(vlriva));
            valorNeto = (parseFloat(valorBruto) + parseFloat(IVA));
            valorNeto = Math.round(valorNeto);
            document.getElementById("valorBruto").value = valorBruto;
            document.getElementById("IVA").value = IVA;
            document.getElementById("valorNeto").value = valorNeto;

           tablaCotizacion.row.add( [
                "<p class='hidden'>"+item_ID+"-</p><p class='hidden'>"+Servicio+"</p><button type='button' class='btn btn-danger borrarServicio' onclick='eliminar(this);'><i class='fa fa-trash-o' aria-hidden='true'></i></button>&nbsp;<button type='button' class='btn btn-warning editarServicio' onclick='editar(this," + item_ID + "," + Categoria + "," + Servicio + ")'><i class='fa fa-pencil-square-o' aria-hidden='true'></i></button>",
                descripcionServicio,
                Cantidad,
                Valor,
                iva,
                vlriva,
                total
                ] ).draw( false );
           // swal('Exito!','SE AGREGÓ EL ITEM A LA LISTA',"success");   
            reset_campos();
            item_ID = "0";
        }else{
            swal("Error!", 'INGRESA TODOS LOS DATOS OBLIGATORIOS', "error"); 
        }
    }

    function reset_campos() {
        
        $("#descripcionServicio").val("");
        $("#Cantidad").val("");
        $("#valorServicio").val("");
    }
    
    function eliminar(servicio) {
        var valores = new Array();
        $(servicio).parents("tr").find("td").each(function () {
            valores.push($(this).html() + "\n");
        });
        valorBruto = (parseInt(valorBruto) - (parseInt(valores[2]) * parseFloat(valores[3])));
        IVA = (parseFloat(IVA) - parseFloat(valores[5]));
        valorNeto = (parseFloat(valorBruto) + parseFloat(IVA));
        valorNeto = Math.round(valorNeto);
        document.getElementById("valorBruto").value = valorBruto;
        document.getElementById("IVA").value = IVA;
        document.getElementById("valorNeto").value = valorNeto;
        tablaCotizacion.row( $(servicio).parents('tr') ).remove().draw();
    }
    
    function editar(datos,itemID,categoria,servicio) {
        item_ID = itemID;
        var valores = new Array();
        $(datos).parents("tr").find("td").each(function () {
            valores.push($(this).html()); 
        });
        $("#categoriaServicio").val(categoria);
        cargarServicios();
        setTimeout(MostrarServicio,1000);
        function MostrarServicio() {
            $("#ServiciosCargados").val(servicio);
            tablaCotizacion.row( $(datos).parents('tr') ).remove().draw();
        }
            
        $("#descripcionServicio").val(valores[1]);
        $("#Cantidad").val( parseInt(valores[2]));
        $("#valorServicio").val( parseInt(valores[3]));
        valorBruto = (parseInt(valorBruto) - (parseInt(valores[2]) * parseFloat(valores[3])));
        IVA = (parseFloat(IVA) - parseFloat(valores[5]));
        valorNeto = (parseFloat(valorBruto) + parseFloat(IVA));
        valorNeto = Math.round(valorNeto);
        document.getElementById("valorBruto").value = valorBruto;
        document.getElementById("IVA").value = IVA;
        document.getElementById("valorNeto").value = valorNeto;
    }
    
    $("#cotizacion").submit(function (evt) {
        jason = JSON.stringify(tableToJSON('#tablaItems'));
        if ( tablaCotizacion.data().count() ) {
             ejecutarOperacion("ventas","Cotizaciones","registrarCotizacion","usuarioID="+{{ session.usuarioID }}+"&"+$('#cotizacion').serialize()+"&servicio="+jason,function (datos) {
                    if(datos.RESPUESTA == 'EXITO'){
                        swal('Exito!','SE HAN GUARDADO LOS CAMBIOS EN TU COTIZACIÓN',"success");
                        cargarVista(
                            "ventas","Cotizaciones","vistaPrevia","cotizacionCONSECUTIVO="+datos.Cotizacion,
                            "Vista Previa Cotización "+ datos.DATOS.Cotizacion, "vistaPrevia");
                        removeTab("mostrarNuevaCotizacion");
                        removeTab("nuevaCotizacion");
                    }
                });
        }else{
            swal("Error!", ' NO PUEDES GENERAR UNA COTIZACIÓN SIN ITEMS', "error");
        }
        evt.preventDefault();
    });
    
</script>
