<script class='controller'>
    setTimeout(function() {

        /*           ACTUALIZAR CONTADORES               */
        $(document).off('click', "#updateCharts");
        $(document).on('click', '#updateCharts', function(e) {
            var userIntel = JSON.parse(window.localStorage.getItem("userIntel")),
                panelToShow = userIntel.panelUsuario,
                userId = $('#sidebarLoaded').attr('userIdPanel');
            $("#loading").fadeIn("fast", function() {
                showPanel(panelToShow, userId);
            });
        });

        $(document).find('.anim1').velocity("transition.slideUpBigIn", {
            stagger: 250
        });
        enterSubm();

        $(document).off('click', "#addNewLecturaPistola");
        $(document).on('click', '#addNewLecturaPistola', function(e) {
            newProductRead();
        });

        $(document).off('click', ".deleteThisLectura");
        $(document).on('click', '.deleteThisLectura', function(e) {
            var currentTotal = $('.totalRead').html();
            var cant = $(this).parent().parent().find('.cant').html();
            currentTotal = +currentTotal - +cant;
            $('.totalRead').html(currentTotal);

            $(this).parent().parent().remove();
            var cajasLeidasCont = cajasRead();
            $('.totalReadBox').html(cajasLeidasCont.length);
        });

        $(document).off('click', ".restarunidadLectura");
        $(document).on('click', '.restarunidadLectura', function(e) {
            var currentTotal = $('.totalRead').html();
            var cant = $(this).parent().parent().find('.cant').html();
            cant--;
            $(this).parent().parent().find('.cant').html(cant);
            $('.totalRead').html(+currentTotal - 1);

            if (cant == 0) {
                $(this).parent().parent().remove();
            }
            var cajasLeidasCont = cajasRead();
            $('.totalReadBox').html(cajasLeidasCont.length);
        });
		  /** CONSULTAMOS LA GONDOLA SI EXISTE*/
  /**      $(document).off('click', "#saveTomaLecturas");
        $(document).on('click', '#saveTomaLecturas', function(e) {
            var formData = new FormData(),
                gon = $(document).find('#gondolaBox').val();
				bod = $(document).find('#selectBodegaPls').val();
            formData.append('gon', gon);
			formData.append('bod', bod);
            formData.append('meth', 'consultargonrev');
            apiCall(formData, function(data) {
			//		alert(JSON.stringify(data));
				//	alert ("Hola Mundo");
				//	alert (bod);
                console.log(data);
                if (data.status == "gotProd") {
                    $(document).find('#saveNewDevol').removeAttr('disabled');
                } else {
                    $.growl.error({
                        message: " Esta gondola ya ha sido registrada ",
                        duration: 6000
                    });
					return;
                    $(document).find('#gondolaBox').val('');
                    $(document).find('#gondolaBox').focus();
                }
            });
        });	 */
		
///// se guarda si no esta vacio
        $(document).off('click', "#saveTomaLecturas");
        $(document).on('click', '#saveTomaLecturas', function(e) {
			var formData = new FormData(),
                gon = $(document).find('#gondolaBox').val();
				bod = $(document).find('#selectBodegaPls').val();
            formData.append('gon', gon);
			formData.append('bod', bod);
            formData.append('meth', 'consultargonrev');
			
			apiCall(formData, function(data) {
			  //  console.log(data);
                if (data.status == "gotProd") {
					   $.growl.error({
                        message: " Gondola registrada "
              //      $(document).find('#saveNewDevol').removeAttr('disabled');
               // } else {
                 
                       //duration: 6000
                    });
					//return;
                //    $(document).find('#gondolaBox').val('');
                  //  $(document).find('#gondolaBox').focus();
                }
            });	

            var rowsCount = 1,
                inventariodetail = [],
                userId = $('#sidebarLoaded').attr('userIdPanel'),
                gondolaVal = $('#gondolaBox').val();

            if (gondolaVal == '') {
                $.growl.error({
                    message: "Debe ingresar el codigo de Góndola"
                });
                return;
            } 
				
				
					

            var idtransaccion = userId + gondolaVal + new Date();
            idtransaccion = Math.abs(idtransaccion.hashCode());
            $(document).find('.listadoTomaFisica tbody tr').each(function(i, n) {

                var inventarioRow = {};
                inventarioRow.bodega = $(n).find('.bode').html();
                inventarioRow.ubicacion = $(n).find('.locat').html();
                inventarioRow.cajamaster = $(n).find('.cajam').html();
                inventarioRow.codbarras = $(n).find('.prod').html();
                inventarioRow.unidades = $(n).find('.cant').html();
                inventarioRow.usuario = userId;
                inventarioRow.gondola = gondolaVal;
                inventarioRow.idtransaccion = idtransaccion;
                inventarioRow.idlineat = rowsCount;
				inventarioRow.idestado = 0;
				inventarioRow.rev = $(n).find('.rev').html();
                inventariodetail.push(inventarioRow);

                rowsCount++;
            });

          

		  if (rowsCount > 0) {
			  
			  

                $(this).velocity("transition.slideUpOut", {
                    duration: 200,
                    complete: function() {
                        $('#saveTomaLecturasFake').velocity("transition.slideUpIn", {
                            duration: 200,
                            complete: function() {

                                var currentTotal = $('.totalRead').html();
                                var invent = {};
                                invent.inventario = {};
                                invent.inventario.inventariodetail = inventariodetail;
                                invent.inventario.filas = currentTotal;
                                var formData = new FormData(),
                                    userId = $('#sidebarLoaded').attr('userIdPanel');
                                formData.append('userToma', userId);
                                formData.append('inventario', JSON.stringify(invent));
                                formData.append('meth', 'saveVerToma');
								//alert(JSON.stringify(invent));
                                apiCall(formData, function(data) {
                                    //console.log(data);
									alert(JSON.stringify(data));
                                    if (data.status == "saved") {
                                        $(document).find('.listadoTomaFisica tbody').html('');
                                        $('#saveTomaLecturasFake').velocity("transition.slideUpOut", {
                                            duration: 200,
                                            complete: function() {
                                                $('#gondolaBox').val('');
                                                $('.totalRead').html('0');
                                                swal({
                                                    title: "Felicitaciones",
                                                    text: "Su toma ha sido registrada exitosamente.",
                                                    type: "success",
                                                    showCancelButton: false,
                                                    confirmButtonText: 'Entendido',
                                                    cancelButtonText: 'salir'
                                                }, function(isConfirm) {
                                                    $(document).find('#updateCharts').click();
                                                });
                                                $('#saveTomaLecturas').velocity("transition.slideUpIn", {
                                                    duration: 200
                                                })
                                            }
                                        });
                                    } else {
                                        //$(document).find('.listadoTomaFisica tbody').html('');
                                        $('#saveTomaLecturasFake').velocity("transition.slideUpOut", {
                                            duration: 200,
                                            complete: function() {
                                                swal({
                                                    title: "Lo Sentimos",
                                                    text: "Hubo un problema para guardar sus datos, intente de nuevo",
                                                    type: "error",
                                                    showCancelButton: false,
                                                    confirmButtonText: 'Entendido',
                                                    cancelButtonText: 'salir'
                                                });
                                                $('#saveTomaLecturas').velocity("transition.slideUpIn", {
                                                    duration: 200
                                                })
                                            }
                                        });
                                    }
                                });

                            }
                        });
                    }
                });
            } else {
                $.growl.error({
                    message: "No hay filas para enviar"
                });
            }

        });

        $(document).off('change', "input[type=radio][name=caja-radios]");
        $(document).on('change', "input[type=radio][name=caja-radios]", function(e) {
            console.log(this.value);
            if (this.value == 'sincajamaster') {
                $(document).find('.cajamasterBoxInpG').slideUp('slow');
                $(document).find('#cajamasterBox').val('0000');
            } else if (this.value == 'cajamaster') {
                $(document).find('#cajamasterBox').val('');
                $(document).find('.cajamasterBoxInpG').slideDown('slow');
            }
        });

        /** CONSULTAMOS LA UBICAION SI EXISTE*/
        $(document).off('change', "#locationBox");
        $(document).on('change', "#locationBox", function(e) {
            var formData = new FormData(),
                tiporigdest = $(document).find("input[type=radio][name=caja-radios]:checked").val(),
                codUbi = $(document).find('#locationBox').val();
				bod = $(document).find('#selectBodegaPls').val();
            formData.append('codUbi', codUbi);
            formData.append('meth', 'consultarUbic');
			formData.append('bod', bod);
            apiCall(formData, function(data) {
                console.log(data);
                if (data.status == "gotProd") {
                    $(document).find('#saveNewDevol').removeAttr('disabled');
                } else {
                    $.growl.error({
                        message: "Codigo de Ubicacion no existe en el sistema ",
                        duration: 6000
                    });
                    $(document).find('#locationBox').val('');
                    $(document).find('#locationBox').focus();
                }
            });
        });
		
    }, 1000);

    // CREAR ARREGLO DE FECHAS DIA POR DIA
    function getDateArray(type = 'normal') {
        // CREAMOS EL RANGO DE FECHAS QUE SE MOSTRARA EN EL GRAFICO
        var startDate = new Date("2019-11-11");
        var today = new Date(),
            dd = today.getDate() + 1,
            mm = today.getMonth() + 1,
            yyyy = today.getFullYear();
        if (dd < 10) {
            dd = '0' + dd;
        }
        if (mm < 10) {
            mm = '0' + mm;
        }
        today = yyyy + '-' + mm + '-' + dd;
        var endDate = new Date(today);

        var arr = new Array();
        var dt = new Date(startDate);
        while (dt <= endDate) {
            var thisday = new Date(dt),
                d = thisday.getDate() + 1,
                m = thisday.getMonth() + 1,
                y = thisday.getFullYear();
            if (d < 10) {
                d = '0' + d;
            }
            if (m < 10) {
                m = '0' + m;
            }
            if (m == 11) {
                if (d == 31) {
                    d = '01';
                    m = '12';
                }
            }
            if (m == 12) {
                if (d == 32) {
                    d = '01';
                    m = '01';
                }
            }
            if (type == 'normal') {
                thisday = m + '-' + d;
            } else {
                thisday = y + '-' + m + '-' + d;
            }
            arr.push(thisday);
            dt.setDate(dt.getDate() + 1);
        }

        return arr;
    }

    /** FUNCIONALIDAD DE LOS INPUT */
    function enterSubm() {
        $('.locationBoxInp').on('keypress', function(e) {
            if (e.which == 13) {
                if ($('input[name=caja-radios]:checked').val() == 'cajamaster') {
                    $('.cajamasterBoxInp').val('');
                    $('.cajamasterBoxInp').focus();
                } else {
                    $('.productoBoxInp').val('');
                    $('.productoBoxInp').focus();
                }
            }
        });
        $('.cajamasterBoxInp').keypress(function(e) {
            if (e.which == 13) {
                $('.productoBoxInp').val('');
                $('.productoBoxInp').focus();
            }
        });
        $('.productoBoxInp').keypress(function(e) {
            if (e.which == 13) {
                newProductRead();
            }
        });

        /*           ACTUALIZAR CAJA O INDIVIDUAL               */
        $(document).off('click', ".leerCajaCompleta");
        $(document).on('click', '.leerCajaCompleta', function(e) {
            $('.readerPistolBox').velocity("transition.slideLeftBigOut", {
                duration: 200,
                complete: function() {
                    $('.readerPistolUnitBox').velocity("transition.slideLeftBigIn", {
                        duration: 200
                    });
                }
            });
        });
        $(document).off('click', ".leerProductosIndividuales");
        $(document).on('click', '.leerProductosIndividuales', function(e) {
            $('.readerPistolUnitBox').velocity("transition.slideLeftBigOut", {
                duration: 200,
                complete: function() {
                    $('.readerPistolBox').velocity("transition.slideLeftBigIn", {
                        duration: 200
                    });
                }
            });
        });

        /** LEER CAJA COMPLETA */
        $(document).off('click', ".readerPistolUnitBox button.enviUnit");
        $(document).on('click', '.readerPistolUnitBox button.enviUnit', function(e) {

            var cajaVal = $(document).find('#productoBoxUnit').val();
            if (cajaVal == '') {
                $.growl.error({
                    message: "Debe llenar todos los campos"
                });
                return;
            }
            getThisCaja();
        });
        $('.productoBoxUnitInp').keypress(function(e) {
            if (e.which == 13) {
                var cajaVal = $(document).find('#productoBoxUnit').val();
                if (cajaVal == '') {
                    $.growl.error({
                        message: "Debe llenar todos los campos"
                    });
                    return;
                }
                getThisCaja();
            }
        });

        /*           ACTUALIZAR CODIGO UBICACION             */
        $(document).off('click', 'td[data-valtype="locat"]');
        $(document).on('click', 'td[data-valtype="locat"]', function(e) {
            var lineRead = this;
            $('.updateLocationBox').velocity("transition.slideDownBigOut", {
                duration: 200,
                complete: function() {
                    $(document).find('#cajaToUpdate').val($(lineRead).parent().find('td[data-valtype="cajam"]').html());
                    $('.updateLocationBox').velocity("transition.slideDownBigIn", {
                        duration: 200
                    });
                }
            });
        });
        $(document).off('click', "button.updateLocatBtn");
        $(document).on('click', 'button.updateLocatBtn', function(e) {

            var cajaVal = $(document).find('#cajaToUpdate').val();
            var locatVal = $(document).find('#newLocatInp').val();
            if (locatVal == '') {
                $.growl.error({
                    message: "Debe llenar todos los campos"
                });
                return;
            }
            updateAllLocats(cajaVal, locatVal);
        });
        $('button.updateLocatBtn').keypress(function(e) {
            if (e.which == 13) {
                var cajaVal = $(document).find('#cajaToUpdate').val();
                var locatVal = $(document).find('#newLocatInp').val();
                if (locatVal == '') {
                    $.growl.error({
                        message: "Debe llenar todos los campos"
                    });
                    return;
                }
                updateAllLocats(cajaVal, locatVal);
            }
        });
    }

    /** NUEVA LECTURA DE PRODUCTO */
    function newProductRead() {

        var bode = $(document).find('#selectBodegaPls').val(),
			rev = $(document).find('#selectRevisionPls').val(),
            locat = $(document).find('#locationBox').val(),
            cajam = $(document).find('#cajamasterBox').val(),
            prod = $(document).find('#productoBox').val(),
            isPresent = 0;

        if (bode == '' || locat == '' || cajam == '' || prod == '') {
            $.growl.error({
                message: "Debes capturar todos los campos"
            });
            return false;
        }


        var formData = new FormData();
        formData.append('codbar', prod);
        formData.append('meth', 'consultarPNL');
        apiCall(formData, function(data) {
			
            if (data.status != "gotProd") {
                $(document).find('#productoBox').val('');
                $(document).find('#productoBox').focus();
                $.growl.error({
                    message: "Codigo de barras no existe en el sistema ",
                    duration: 6000
                });
            } else {
                console.log(data);
                $(document).find('.listadoTomaFisica tbody tr').each(function(i, n) {
                    var bodeRow = $(n).find('.bode').html(),
                        locatRow = $(n).find('.locat').html(),
                        cajamRow = $(n).find('.cajam').html(),
                        prodRow = $(n).find('.prod').html(),
                        cantRow = $(n).find('.cant').html();
						revRow = $(n).find('.rev').html();
                    if (rev == revRow && bode == bodeRow && locat == locatRow && cajam == cajamRow && prod == prodRow) {
                        cantRow = +cantRow + 1;
                        $(n).find('.cant').html(cantRow);
                        isPresent = 1;
                        $.growl.notice({
                            message: "Registrado exitosamente Item: " + prod
                        });
                    }
                });

                if (isPresent == 0) {

                    var proveedor = '';
                    if (data.provs) {
                        proveedor = data.provs[0][0];
                    }
                    $('.listadoTomaFisica tbody')
                        .append(' <tr>' +
                            '<th scope="row" class="bode" data-valtype="bode">' + bode + '</th>' +
							'<th scope="row" class="rev" data-valtype="rev">' + rev + '</th>' +
                            '<td class="locat" data-valtype="locat">' + locat + '</td> ' +
                            '<td class="cajam" data-valtype="cajam">' + cajam + '</td> ' +
                            '<td class="prod" data-valtype="prod">' + prod + '</td> ' +
                            '<td class="prov" data-valtype="prov">' + proveedor + '</td> ' +
                            '<td class="cant" data-valtype="cant">1</td> ' +
                            '<td> <button class="btn btn-danger deleteThisLectura " ><i class="fa fa-trash-o"></i></button><button class="btn btn-primary restarunidadLectura " ><i class="fa fa-minus"></i></button></td> ' +
                            ' </tr>');
                    $.growl.notice({
                        message: "Registrado exitosamente Item: " + prod
                    });
                }
                $(document).find('#productoBox').val('');
                $(document).find('#productoBox').focus();

                var currentTotal = $('.totalRead').html();
                currentTotal = +currentTotal + 1;
                $('.totalRead').html(currentTotal);
                return true;
            }
        });

    }

    /** OBTENEMOS LOS DATOS DE LA CAJA MASTER Y TODOS SUS PRODUCTOS */
    function getThisCaja() {
        $('.refreshPageIcon').addClass('fa-spin');
        //var suPedido = $(document).find('.thisDevolProd .suPedido').html();
        var suPedido = $(document).find('#selectBodegaPlsCaja').val();
        var cajaVal = $(document).find('#productoBoxUnit').val(),
            formData = new FormData();

        var cajasLeidas = cajasRead();
        if (cajasLeidas.includes(cajaVal)) {
            $.growl.error({
                message: "Esta caja ya fue capturada, no puede repetir la caja en el mismo pedido"
            });
            $(document).find('#productoBoxUnit').val('');
            $(document).find('#productoBoxUnit').focus();
            return;
        }

        formData.append('suPedido', suPedido);
        formData.append('cajaVal', cajaVal);
        formData.append('meth', 'consultarCajaMasterIF');
        apiCall(formData, function(data) {
            console.log(data);
            $('.refreshPageIcon').removeClass('fa-spin');
            if (data.rows.length > 0) {
                $(data.rows).each(function(i, n) {
                    var bode = $(document).find('#selectBodegaPlsCaja').val(),
                        isPresent = 0;

                    $(document).find('.listadoTomaFisica tbody tr').each(function(ii, nn) {
                        var bodeRow = $(nn).find('.bode').html(),
                            locatRow = $(nn).find('.locat').html(),
                            cajamRow = $(nn).find('.cajam').html(),
                            prodRow = $(nn).find('.prod').html(),
                            cantRow = $(nn).find('.cant').html();
                        if (bode == bodeRow && n[5] == locatRow && cajaVal == cajamRow && n[4] == prodRow) {
                            cantRow = +cantRow + n[5];
                            $(nn).find('.cant').html(cantRow);
                            isPresent = 1;
                            $.growl.notice({
                                message: "Registrado exitosamente Item: " + n[4]
                            });
                        }
                    });

                    if (isPresent == 0) {

                        var proveedor = '';
                        if (data.provs) {
                            proveedor = data.provs[0][0];
                        }
                        $('.listadoTomaFisica tbody')
                            .append(' <tr>' +
                                '<th scope="row" class="bode" data-valtype="bode">' + bode + '</th>' +
                                '<td class="locat" data-valtype="locat">' + n[6] + '</td> ' +
                                '<td class="cajam" data-valtype="cajam">' + cajaVal + '</td> ' +
                                '<td class="prod" data-valtype="prod">' + n[4] + '</td> ' +
                                '<td class="prov" data-valtype="prod">' + proveedor + '</td> ' +
                                '<td class="cant" data-valtype="cant">' + n[5] + '</td> ' +
                                '<td> <button class="btn btn-danger deleteThisLectura " ><i class="fa fa-trash-o"></i></button><button class="btn btn-primary restarunidadLectura " ><i class="fa fa-minus"></i></button></td> ' +
                                ' </tr>');
                        $.growl.notice({
                            message: "Registrado exitosamente Item: " + n[4]
                        });
                    }

                    var currentTotal = $('.totalRead').html();
                    currentTotal = +currentTotal + +n[5];
                    $('.totalRead').html(currentTotal);
                });
                var cajasLeidasCont = cajasRead();
                $('.totalReadBox').html(cajasLeidasCont.length);

                $(document).find('#productoBoxUnit').val('');
                $(document).find('#productoBoxUnit').focus();

            } else {
                $.growl.error({
                    message: "Esta caja no contiene productos registrados"
                });
                return;
            }
        });
    }

    /* LEEMOS LAS CAJAS QUE HAN SIDO PITADAS */
    function cajasRead() {
        var cajasLeidas = [];
        $(document).find('.listadoTomaFisica tbody tr').each(function(ii, nn) {
            var codCaja = $(nn).find('.cajam').html();
            if (!cajasLeidas.includes(codCaja)) {
                cajasLeidas.push(codCaja);
            }
        });
        return cajasLeidas;
    }

    /* ACTUALZIAMOS EL CODIGO DE UBICACION PARA TODAS LAS CAJAS */
    function updateAllLocats(caja, locat) {
        var i = 0;
        $(document).find('.listadoTomaFisica tbody tr').each(function(ii, nn) {
            var cajamRow = $(nn).find('.cajam').html();
            if (cajamRow == caja) {
                $(nn).find('.locat').html(locat);
                i++;
            }
        });
        $.growl.notice({
            message: "Se actualizaron " + i + " lineas con codigo de caja master " + caja
        });
        $('.updateLocationBox').velocity("transition.slideDownBigOut", {
            duration: 200
        });
        $(document).find('#cajaToUpdate').val('');
        $(document).find('#newLocatInp').val('');
    }
</script>