<script type="text/javascript" src="<?php echo Constantes::ROOT_DIR_APP ?>web/js/jquery/jquery.contextmenu.js"></script>

<style type="text/css">
.ui-jqgrid .ui-jqgrid-pager .ui-pg-div span.ui-icon {
    background-color: #ffffff;
    float: left;
    margin: 0 2px;
}
</style>

<table id="jqGrid"></table>
<div id="jqGridPager"></div>

<div class="contextMenu" id="contextMenu" style="display:none; width:400px;">
    <ul style="width: 400px; font-size: 65%;">
        <li id="add">
            <span class="ui-icon ui-icon-plus" style="float:left"></span>
            <span style="font-size:130%; font-family:Verdana">Add Row</span>
        </li>
        <li id="edit">
            <span class="ui-icon ui-icon-pencil" style="float:left"></span>
            <span style="font-size:130%; font-family:Verdana">Edit Row</span>
        </li>                
        <li id="del">
            <span class="ui-icon ui-icon-trash" style="float:left"></span>
            <span style="font-size:130%; font-family:Verdana">Delete Row</span>
        </li>                
    </ul>
</div>


<script>
    findControl = function ()
    {
        //pr( JSON.stringify( $( 'form' ).serializeArray() ) );
        strFormSerialize = $( 'form' ).serialize();
        relaodGrid( strFormSerialize );

        //$.cookie.raw = true;
        //$.cookie.json = true;

        $.cookie( 'form_item', JSON.stringify( $( 'form' ).serializeArray() ), { expires: 1 } );
        //pr( $.cookie( 'form_item' ) );
        //pr( JSON.parse( $.cookie( 'form_item' ) ) );
        
        
    }
    
    relaodGrid = function( s_url_param )
    {
        jQuery( '#jqGrid' ).jqGrid( 'clearGridData' );
        jQuery( '#jqGrid' ).jqGrid( 'setGridParam', { url: '<?=buildUrl('item/grid','')?>?' + s_url_param } );
        jQuery( '#jqGrid' ).trigger( 'reloadGrid' );
    }
    
    showView = function( i_Id )
    {
        $( '#myIframe' ).attr( 'src', '<?=buildUrl( 'item/viewdel', 's_TipoProc=shw&i_Id=' )?>' + i_Id );
        $( '#dialog' ).dialog( 'open' );
    }
    
    deleteRow = function( i_Id )
    {
        $( '#myIframe' ).attr( 'src', '<?=buildUrl( 'item/viewdel', 's_TipoProc=dlt&i_Id=' )?>' + i_Id );
        $( '#dialog' ).dialog( 'open' );
    }
    
    resumenKardex = function( id_item )
    {
        //parent.openDialorParent( '' + id_item );
        $( '#myIframe4' ).attr( 'src', '<?=buildUrlComplet( 'rep.php/rep/listMovRes', 'IdIem=' )?>' + id_item );
        $( '#dialog4' ).dialog( 'open' );
    }
    
    closeWindow = function( s_NameWin )
    {
        $( '#' + s_NameWin ).dialog( 'close' );
    }

    buscarResumenReserevas = function( i_Id )
    {
        $( '#myIframe3' ).attr( 'src', '<?=buildUrl( 'item/listRes', 'id_item=' )?>' + i_Id );
        $( '#dialog3' ).dialog( 'open' );
    }

    editarPrecioItem = function( i_Id )
    {
        $( '#myIframe5' ).attr( 'src', '<?=buildUrl( 'item/editPrice', 'id_item=' )?>' + i_Id );
        $( '#dialog5' ).dialog( 'open' );
    }
</script>

<script>
    var s_Estado_Valores = { value: "A:Activo;I:Inactivo" };

    var jqGridContent = $( "#jqGrid" );
    jqGridContent.jqGrid
    (
        {
            url         : '<?=buildUrl( 'item/nothing', 'id_item=' )?>',
            mtype       : "POST",
            datatype    : "json",
            editurl     : 'edicionData.php',                        
            colNames    : [ 'IdItem', 'C&oacute;digo', 'Descripci&oacute;n', 'Tipo', 'Linea', 'Familia', 'SubFamilia', 'Marca', 'Unidad', 'Cod Sunat', 'Peso', 'Stock Fisico', /*'Stock Dispo',*/ /*'Precio',*/ /*'Pre.Fra',*/ 'Estado', '', '', '', '', '' ],
            colModel    : 
                          [
                            { name: 'IdItem',               width: 0, align: 'center', hidden: true, hidedlg: false, editrules : { required: true }, key: true },
                            {
                                name: 'IdItem',
                                width: 70, 
                                align: 'center', 
                                editable: true, 
                                sortable: true, 
                                formatter: function( cellvalue, options, rowObject )
                                {
                                	return  '<span style="color:blue;text-decoration: underline;cursor:pointer;" originalValue="' + cellvalue + '" onclick="buscarResumenStock( \'' + cellvalue + '\' );">' + cellvalue + '</span>';
                                } 
                            },
                            { name: 'DescripcionCompleta',      width: 250,  align: 'left',   editable: true, sortable: true },
                            { name: 'DescripcionTipoItem',      width: 90, align: 'center', editable: true, sortable: false },
                            { name: 'DescripcionLinea',         width: 100, align: 'center', editable: true, sortable: false },
                            { name: 'DescripcionFamilia',       width: 100, align: 'center', editable: true, sortable: false },
                            { name: 'DescripcionSubFamilia',    width: 100, align: 'center', editable: true, sortable: false },
                            { name: 'DescripcionMarca',         width: 100, align: 'center', editable: true, sortable: false },
                            { name: 'UnidadVentaDesc',          width: 80, align: 'center', editable: true, sortable: false },

                            { name: 'CodigoSunat',          width: 70, align: 'center', editable: true, sortable: false },
                            { name: 'PesoGramos',          width: 50, align: 'center', editable: true, sortable: false },
                            
                            { name: 'StockDisponibleTotal',        width: 60, align: 'center', editable: false, sortable: false },
                            /*{ 
                                name: 'StockDisponibleTotal',   width: 60, align: 'center', editable: false, sortable: false,
                                formatter: function( cellvalue, options, rowObject )
                                {
                                    if( rowObject.StockFisicoTotal != rowObject.StockDisponibleTotal )
                                    {
                                        return  '<span style="color:blue;text-decoration:underline;cursor:pointer;" originalValue="' + cellvalue + '" onclick="buscarResumenReserevas( \'' + rowObject.IdItem + '\' );">' + cellvalue + '</span>'; //buscarResumenReserevas( rowid );
                                    }
                                    else
                                    {
                                        return  "<span style='' originalValue='" + cellvalue + "'>" + cellvalue + "</span>";
                                    }
                                } 
                            },*/
                            /*{
                                name: 'PrecioConIGV',         width: 60, align: 'center', editable: false, sortable: false,
                                formatter: function( cellvalue, options, rowObject )
                                {
                                    return '<span style="color:blue;text-decoration:underline;cursor:pointer;background-color: #F8DA50; display: inline-block; width: 100%; height: 22px; line-height: 22px;" onclick="editarPrecioItem( \'' + rowObject.IdItem + '\' );">' + cellvalue + '</span>'; //editarPrecioItem( rowid );
                                }
                            },*/
                            /*{ name: 'PrecioConIGVFra',   width: 70, align: 'center', editable: true, sortable: false },*/
                            
                            { name: 'Estado',            width: 70, align: 'center', editable: true, sortable: false },
                            
                            { name: 'edit', width: 25, align: 'center', sortable: false, search: false,
                            	cellattr: function () { return ' title="Editar"'; },
                                formatter:function( param1, param2, param3 )
                                {
                                    var s_url = '<?=buildUrl('item/addedit','s_TipoProc=upd&i_Id=')?>' + param3.IdItem;
                                    
                                    return "<span style='cursor:pointer; margin: 0 auto;' class='ui-icon ui-icon-pencil' onclick=location.href=\'"+s_url+"\'></span>"
                                }
                                <?php //if( myUser::getUser()->getRoleId() != "sys.adm" ){ ?> /*,hidden: true*/ <?php //} ?>
                            },
                            
                            { name: 'details', width: 25, align: 'center', sortable: false, search: false,
                            	cellattr: function () { return ' title="Mostrar"'; },
                                formatter:function()
                                {
                                    return "<span style='cursor:pointer; margin: 0 auto;' class='ui-icon ui-icon-document' onclick='showView( $(this).parent().parent()[0].id );'></span>"
                                }
                            },
                            {
                                name: 'kardex', width: 25, align: 'center', sortable: false, search: false,
                            	cellattr: function () { return ' title="Kardex"'; },
                                formatter:function()
                                {
                                    return "<span style='cursor:pointer; margin: 0 auto;' class='ui-icon ui-icon-calculator' onclick='resumenKardex( $(this).parent().parent()[0].id );'></span>"
                                }
                            },
                            { name: 'prices', width: 25, align: 'center', sortable: false, search: false,
                            	cellattr: function () { return ' title="Mostrar Precios"'; },
                                formatter:function( cellvalue, options, rowObject )
                                {
                                    return "<span style='cursor:pointer; margin: 0 auto;' class='' onclick='editarPrecioItem( \"" + rowObject.IdItem + "\" );'><i class='fas fa-dollar-sign' style='color: #0078ae;'></i></span>"
                                }
                            },
                            { 
                                name: 'delete', width: 25, align: 'center', sortable: false, search: false,
                                cellattr: function () { return ' title="Eliminar"'; },
                                formatter:function( cellvalue, options, rowObject )
                                {
                                    return '<span style="cursor:pointer; margin: 0 auto;" class="ui-icon ui-icon-trash" onclick="deleteRow(\''+rowObject.IdItem+'\');"></span>';
                                }
                            }
                          ],
			viewrecords : true,
			height      : $(window).height() - 209, 
			width       : $(window).width() - 5,
            //width       : 600,
            //autowidth   : true,
            sortable    : true,
            multiSort   : true,
            autoencode: true,
            ignoreCase: true,

            shrinkToFit : false,

            //width: null,
            emptyrecords: "Nothing to display",
            //height      : 480,
            rowNum      : 100,
            rownumbers  : true, // show row numbers
            //multiselect : true,//SELECCION MULTIPLE
            pager       : "#jqGridPager",
            //caption     : "Products / Category Primary Grid View"
            onCellSelect: function( rowid, iCol, cellcontent )
            {
                if( iCol == 2 ) //Codigo del Item
                {
                	//buscarResumenStock( rowid );
                }
                if( iCol == 8 ) //se vizualiza la reserva
                {
                    //buscarResumenReserevas( rowid );
                }
                if( iCol == 9 ) //se edita el precio
                {
                    //editarPrecioItem( rowid );
                }

            },
            beforeSelectRow: function ( rowid, e ) 
            {
            },
            gridComplete: initGrid
        }
    );

    function initGrid() {
        $(".jqgrow", "#jqGrid").contextMenu('contextMenu', {
            bindings: {
                'edit': function (t) {
                    editRow();
                },
                'add': function (t) {
                    addRow();
                },
                'del': function (t) {
                    delRow();
                }
            },
            onContextMenu: function (event, menu) {
                var rowId = $(event.target).parent("tr").attr("id")
                var grid = $("#jqGrid");
                grid.setSelection(rowId);

                return true;
            }
        });

        function addRow() {
            var grid = $("#jqGrid");
            grid.editGridRow("new", { closeAfterAdd: true});
        }

        function editRow() {
            var grid = $("#jqGrid");
            var rowKey = grid.getGridParam("selrow");
            if (rowKey) {
                grid.editGridRow(rowKey, {closeAfterEdit: true});
            }
            else {
                alert("No rows are selected");
            }
        }

        function delRow() {
            var grid = $("#jqGrid");
            var rowKey = grid.getGridParam("selrow");
            if (rowKey) {
                grid.delGridRow(rowKey);
            }
            else {
                alert("No rows are selected");
            }
        }
    }

    $( "#jqGrid" ).jqGrid( 'bindKeys' ); // esto habilita bajar las celdas con las tecla de arriba y abajo

    //un ejemplo para ver mas opciones al metodo bindKeys
    /* jQuery("#keynav").jqGrid('bindKeys', { "onEnter" : function( rowid ) { alert("You enter a row with id:"+rowid) } }); */
    
    jQuery( "#jqGrid" ).jqGrid( 'navGrid', "#jqGridPager", { edit:false, add:false, del:false, view: false, search: false, refresh: false } )
    .jqGrid( 'navButtonAdd', "#jqGridPager", 
        {
            caption:"STOCK-MIN",
            buttonicon:"ui-icon-circle-plus",
            onClickButton:function()
            { 
                /*
                var dataFromTheRow = jQuery('#list').jqGrid ('getRowData', rowId);
                var dataFromCellByColumnIndex = jQuery('#list').jqGrid ('getCell', rowId, 7);
                var dataFromCellByColumnName = jQuery('#list').jqGrid ('getCell', rowId, 'Tax');
                */

                var myGrid = $( '#jqGrid' );

                var rowId  = myGrid.jqGrid( 'getGridParam', 'selrow' );
                
                if( empty( rowId ) )
                {
                    alert( "Seleccione el Item para registrar el Stock Minimo" );
                    return false;
                }
                //var objData = myGrid.jqGrid ('getRowData', rowId ); 
                var elm_stock = myGrid.jqGrid ( 'getCell', rowId, 9 ); //stock en unidades
                pr( elm_stock );
                var stock = $( elm_stock ).html();
                var desc  = myGrid.jqGrid ( 'getCell', rowId, 3 ); //

                //pr( $( stock ).html() );
                //pr( "Stock -> "+stock );
                //pr( desc );

                x = confirm( "Esta seguro de activar el Stock Minimo del Item [" + desc + "] ? " );
                if( x )
                {
                    $.ajax
                    (
                        {
                            url: "<?=buildUrlComplet( 'mst.php/item/addStockMin', 'id_item=' )?>" + rowId + "/stock/" + stock + "/value/Y",
                            async: false, 
                            //very important: else php_data will be returned even before we get Json from the url
                            dataType: 'json',
                            success: function ( json ) 
                            {
                                //pr( json );
                                if( json.error )
                                {
                                    alert( json.mensaje_error );
                                    return false;
                                }
                                //$( '#myIframe2' ).attr( 'src', '<?=buildUrlComplet( 'mst.php/item/listStkMin', '' )?>' );
                                //$( '#dialog2' ).dialog( 'open' );
                            }
                        }
                    );
                }
            },
            position: "last",
            title:"",
            id : "",
            cursor: "pointer"
        }
    );

    $(window).on
    ( 
        "resize", 
        function () 
        {
            var newWidth = $( "#jqGrid" ).closest( ".ui-jqgrid" ).parent().width() - 5;
            if( newWidth <= 705 )
            {
                jqGridContent.jqGrid( "setGridWidth", newWidth, false );
            }
            else
            {
                jqGridContent.jqGrid( "setGridWidth", newWidth, true);
            }
        }
    );

    if( $( "#jqGrid" ).closest( ".ui-jqgrid" ).parent().width() <= 705 )
    {
        jqGridContent.jqGrid( "setGridWidth", $( "#jqGrid" ).closest( ".ui-jqgrid" ).parent().width() - 5, false );
    }
    else
    {
        jqGridContent.jqGrid( "setGridWidth", $( "#jqGrid" ).closest( ".ui-jqgrid" ).parent().width() - 5, true);
    }
    
    setTimeout
    (
        function()
        {
            findControl();
        },
        300
    );
</script>

<?=crearPopupResumenStock( array( "name_function"=>"buscarResumenStock" ) )?>

<?=crearFuentePopupIframe( array( "div_id"=>"dialog",  "iframe_id"=>"myIframe",  "popup_title"=>"Buscar Producto", "modal"=>true ) )?>
<?=crearFuentePopupIframe( array( "div_id"=>"dialog2", "iframe_id"=>"myIframe2", "popup_title"=>"Eliminar", "modal"=>true ) )?>
<?=crearFuentePopupIframe( array( "div_id"=>"dialog3", "iframe_id"=>"myIframe3", "popup_title"=>"Reservas", "modal"=>true ) )?>
<?=crearFuentePopupIframe( array( "div_id"=>"dialog4", "iframe_id"=>"myIframe4", "popup_title"=>"Kardex Resumen", "modal"=>true ) )?>
<?=crearFuentePopupIframe( array( "div_id"=>"dialog5", "iframe_id"=>"myIframe5", "popup_title"=>"Edicion de Precio", "modal"=>true ) )?>