<?php
$strModulo = 'refacciones';

$arrCT = array();
//$url = 'https://www.solerpalau.mx/plantasyp/datosPlanta.php';
$url = 'https://www.solerpalau.mx/plantasyp/datosPlanta.php';
$opciones = array('http' =>
    array(
        'method' => 'GET',
        'max_redirects' => '0',
        'ignore_errors' => '1'
    )
);

$contexto = stream_context_create($opciones);
$flujo = fopen($url, 'r', false, $contexto);
$arrResultadoPeticion = json_decode(stream_get_contents($flujo), true);

$arrCT[0]['idCT'] = 'todos';
$arrCT[0]['name'] = 'Todos';
$contadorCT = 1;
foreach ($arrResultadoPeticion['datosRespuesta'] as $clave => $valor){
    $arrCT[$contadorCT]['idCT'] = $clave;
    $arrCT[$contadorCT]['name'] = $clave;
    $contadorCT++;
}

$jsonCentrosT = json_encode($arrCT);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="imagetoolbar" content="no" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Poppins:400,500,700,300,600">
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Open+Sans">
    <link media="screen" rel="stylesheet" type="text/css" href="css/principal.css" />
    <!--<link media="screen" rel="stylesheet" type="text/css" href="css/pagination.css"  />--> <!--Paginador-->
    <link rel="shortcut icon" type="image/x-icon" href="css/layout/global/sp.ico" />

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.14.1/dijit/themes/claro/claro.css">
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.14.1/dojo/dojo.js" data-dojo-config="async: true, parseOnLoad:true"></script>

    <style type="text/css">
        /* Estilos para el DataGrid */
        @import "//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojox/grid/resources/claroGrid.css";
        @import "//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/resources/dojo.css";
        @import "//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dijit/themes/claro/claro.css";
        @import "//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dijit/themes/claro/document.css";
        @import "//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojox/grid/enhanced/resources/claro/EnhancedGrid.css";
        @import "//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojox/grid/enhanced/resources/EnhancedGrid_rtl.css";
        #Grid_Refacciones {
            height: 600px;
        }

    </style>

    <script type="application/javascript">
        // Cargamos los complementos de dojo
        require(["dojo/dom", "dojo/_base/fx", "dojo/_base/array", "dojo/query", "dojo/dom-construct", "dijit/registry", "dojo/dom-style", "dojo/ready", "dojo/on", "dojo/window",
                "dojo/store/Memory", "dijit/form/FilteringSelect", "dijit/form/Button", "dojo/dom-class", "dijit/Dialog",
                "dojo/_base/lang", "dojox/grid/DataGrid", "dojo/data/ItemFileWriteStore", "dojox/grid/enhanced/plugins/DnD", "dojox/grid/EnhancedGrid", "dojox/grid/enhanced/plugins/Selector", "dojox/grid/enhanced/plugins/IndirectSelection", "dojox/grid/enhanced/plugins/NestedSorting",
                "dijit/ProgressBar", "dijit/ConfirmDialog", "dojo/dom-style", "dijit/form/ComboButton", "dijit/Menu", "dijit/MenuItem", "dijit/MenuSeparator", "dijit/Tooltip", "dijit/form/Form", "dijit/form/TextBox",
                "dojox/grid/enhanced/plugins/Filter", "dijit/form/ValidationTextBox", "dijit/form/NumberSpinner", "dojo/request", "dojo/parser"],
            function(dom, fx, array, query, domConstruct, dijit, style, ready, on, win,
                     Memory, FilteringSelect, Button, domClass, Dialog,
                     lang, DataGrid, ItemFileWriteStore, DnDConfig, EnhancedGrid, Selector, indirectSelection, nestedSorting,
                     ProgressBar, ConfirmDialog, style, ComboButton, Menu, MenuItem, MenuSeparator, Tooltip, Form, TextBox, filter, ValidationTextBox, NumberSpinner, request) {

                const idModulo = "<?php echo($strModulo);?>";
                const arrCentrosT = <?php echo($jsonCentrosT); ?>;

                // Para Mostrar de Mensajes de "error o éxito"
                var dgEjecuta = new Dialog({title: 'Procesando...', style: 'width:300px'});
                var pbMarcar = new ProgressBar({value: Number.POSITIVE_INFINITY, layoutAlign: 'left'});
                dgEjecuta.setContent(pbMarcar);
                dgResultadoError = new ConfirmDialog({ title:"<b>Error</b>", style: "min-width:300px; heigth; auto" });
                style.set(dgResultadoError.cancelButton.domNode, 'display', 'none');
                dgResultadoExito = new ConfirmDialog({ title:"<b>Éxito</b>", style: "min-width:300px; heigth; auto" });
                style.set(dgResultadoExito.cancelButton.domNode, 'display', 'none');


                /****************************************************************** Inputs ******************************************************************/
                new FilteringSelect({
                    id: "select_CentroTrabajo",
                    store: new Memory({ idProperty: "idCT", data: arrCentrosT }),
                    autoComplete: true,
                    maxHeight: 300,
                    style: "width: 100%;",
                    placeHolder: "Seleccione una opción",
                    onChange: function(idCt){
                    }
                }, "select_CentroTrabajo");

                /****************************************************************** Botones ******************************************************************/
                new Button({
                    id: "btn_Buscar",
                    label: "Buscar",
                    iconClass: "dijitIconSearch",
                    showLabel: false,
                    onClick: function(){
                        let centroT = dijit.byId('select_CentroTrabajo').value;
                        if(centroT != ""){
                            cargarGrid("id_Grid_Refacciones", centroT, "");
                        }
                    }
                }, "btn_Buscar").startup();


                /****************************************************************** Acciones ******************************************************************/
                cargarGrid = function (idGrid, ct, maq){
                    dgEjecuta.set("title", "Consultando...");
                    dgEjecuta.show();

                    var accion = "";
                    var resdatosRecibidos = "datosRespuesta";
                    var posicionDom = "";

                    if(idGrid == "id_Grid_Refacciones"){
                        accion = "buscarMantoPreventivo";
                        posicionDom = "Grid_Refacciones";
                    }

                    request.post("datosPlanta.php", {
                        data: {
                            accion: accion,
                            idModulo: idModulo,
                            ct: ct,
                            maq: maq
                        }
                    }).then(
                        function (response) {
                            var objResponse = JSON.parse(response);
                            if (objResponse['estatus'] == "ERROR") {
                                dgEjecuta.hide();
                                dgResultadoError.setContent(objResponse['errorDescripcion']);
                                dgResultadoError.show();
                            } else {
                                let datosRecibidos = objResponse[resdatosRecibidos];

                                // Configuramos el data store
                                var data = {
                                    identifier: "id",
                                    items: []
                                };

                                // Creamos la lista de objetos
                                var data_list = JSON.parse(datosRecibidos);

                                for(var i = 0, l = data_list.length; i < data_list.length; i++){
                                    data.items.push(lang.mixin({ id: i+1 }, data_list[i%l]));
                                }
                                var store = new ItemFileWriteStore({data: data});

                                // Destruimos el dataGrid si ya existe
                                if (dijit.byId(idGrid)){
                                    dijit.byId(idGrid).destroy();
                                }

                                if(idGrid == "id_Grid_Refacciones"){
                                    var estructuralayout = [[
                                        {'name': 'No.', 'field': 'id', 'width': '30px', 'datatype':'number'},
                                        {'name': 'Centro de Trabajo', 'field': 'ct', 'width': '120px', 'datatype':'string'},
                                        {'name': 'Parte', 'field': 'parte', 'width': '250px', 'datatype':'string'},
                                        {'name': 'Actividad', 'field': 'actividad', 'width': '270px', 'datatype':'string'},
                                        {'name': 'Duración', 'field': 'duracion', 'width': '150px', 'datatype':'string'},
                                        {'name': 'Prioridad', 'field': 'prioridad', 'width': '150px', 'datatype':'string'},
                                        {'name': 'Tipo', 'field': 'tipo', 'width': '150px', 'datatype':'string'},
                                        {'name': 'Clasificación 1', 'field': 'clasificacion', 'width': '260px', 'datatype':'string'}
                                    ]];
                                }

                                var grid = new EnhancedGrid({
                                    id: idGrid,
                                    store: store,
                                    structure: estructuralayout,
                                    autoHeight: false,
                                    autoWidth: false,
                                    rowSelector: '20px',
                                    noDataMessage: 'No se encontraron datos',
                                    canSort: function () {
                                        return true;
                                    }, // Filtra
                                    plugins: {
                                        nestedSorting: true,
                                        filter: {
                                            // Show the closeFilterbarButton at the filter bar
                                            closeFilterbarButton: false,
                                            // Set the maximum rule count to 5
                                            ruleCount: 5,
                                            // Set the name of the items
                                            itemsName: "registros"
                                        }
                                    }
                                });


                                // Cargamos el dataGrid en el div
                                grid.placeAt(posicionDom);
                                // Inicializamos el dataGrid
                                grid.startup();

                                dgEjecuta.hide();
                            }
                        }
                    );

                };

                ready(function() {
                    // Actualizar el tamaño del TabContainer en función del tamaño de página
                    var ventana = win.getBox();
                    var strVentana = (ventana.h-130)+"px";
                    style.set(dijit.byId("djTab").id, { height:strVentana });
                    dijit.byId("djTab").resize();

                    // Actualizar el tamaño del TabContainer en función del tamaño de página
                    on(window, "resize", function() {
                        var ventana = win.getBox();
                        var strVentana = (ventana.h-130)+"px";
                        style.set(dijit.byId("djTab").id, { height:strVentana });
                        dijit.byId("djTab").resize();
                    });
                    // Eliminar la cortina de entrada
                    fx.fadeOut({node: dom.byId("loadingOverlay"), duration: 1}).play();
                    setTimeout(function () {
                        domConstruct.destroy("loadingOverlay");
                    }, 1);

                    cargarGrid("id_Grid_Refacciones", "todos", "");

                });
            });
    </script>

</head>

<body class="claro">
<div id="loadingOverlay" class="loadingOverlay pageOverlay">
    <div class="loadingMessage">Espere...</div>
</div>

<div id="wrapper_container_module">
    <div id="wrapper_table" style="position:relative;">
        <div data-dojo-type="dijit/form/Form" id="frm" data-dojo-id="frm" encType="multipart/form-data"
             action="<?php echo($_SERVER['PHP_SELF']); ?>" method="post" style="position:relative;">
            <script type="dojo/on" data-dojo-event="submit">return true;</script>
            <div id="wrapper_table_head">Mantenimiento Preventivo</div>
            <div id="wrapper_table_body_mod_app">

                <table width="100%" height="auto" border="0" style="border-spacing: 5px;">
                    <tr>
                        <td width="10%" colspan="2" class="etiquetaFormulario">
                            <label class="noTopPadding">Centro de Trabajo:</label>
                        </td>
                        <td width="20%" colspan="4">
                            <input id="select_CentroTrabajo"/>
                        </td>
                        <td width="70%" colspan="14">
                            <button id="btn_Buscar" type="button"></button>
                        </td>
                    </tr>
                </table>

                <div id="djTab" data-dojo-type="dijit/layout/LayoutContainer" style="overflow-y: auto;">
                    <div style="margin-top: 15px">
                        <div id="Grid_Refacciones"></div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

</body>

