@extends('template.layout')

@section('styles')
@endsection

@section('content')
    <h1 class="page-title">
        Consulta de Trámites TUPA
    </h1>
    <div class="portlet light bordered">
        <div class="portlet-title">
            <div class="caption">
                <span class="caption-subject bold uppercase"> Lista de Trámites TUPA </span>
                <span class="caption-helper"></span>
            </div>
        </div>
        <div class="portlet-body">
            <table id="dataTable" class="table table-hover nowrap dataTable dtr-inline">
                <thead>
                <tr>
                    <th>Nombre</th>
                    <th>Categoría</th>
                    <th>Calificación</th>
                    <th>Duración del Trámite</th>
                    <th>Opciones</th>
                </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
    <div id="modalIniciar" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modalIniciar">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title caption-subject font-blue-secondary sbold uppercase">Sustento</h4>
                </div>
                <div class="modal-body">
                    {{ Form::open(array('id' => 'form-validation', 'class' => 'form-horizontal', 'name' => 'formIniciar', 'onsubmit' => 'IniciarResult(this, event)')) }}
                    <div class="form-body">
                        {!! Form::hidden('id_tramite_procedimiento', null, ['id' => 'iniciarIdTramiteProcedimiento', 'class' => 'form-control']) !!}
                        {!! Form::hidden('id_dependencia', null, ['id' => 'iniciarIdDependencia', 'class' => 'form-control']) !!}
                        {!! Form::hidden('nombre', null, ['id' => 'iniciarNombre', 'class' => 'form-control']) !!}
                        <div class="form-group">
                            <div class="col-xs-12">
                                {!! Form::textarea('sustento', null, ['class' => 'form-control', 'style' => 'resize: none']) !!}
                            </div>
                        </div>
                        <div class="form-actions">
                            <div class="row">
                                <div class="col-md-offset-0 col-xs-12">
                                    <a class="btn btn-default" href="#" data-dismiss="modal">Cancelar</a>
                                    {!! Form::submit('Guardar', ['class' => 'btn btn-primary', 'name' => 'submit']) !!}
                                </div>
                            </div>
                        </div>
                    </div>
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        var tramiteCalificacion = JSON.parse('{!! json_encode(config('constants.TRAMITE_CALIFICACION')) !!}');

        var dataTableLanguage = {
            "sProcessing":     "Procesando...",
            "sLengthMenu":     "Mostrar _MENU_ registros",
            "sZeroRecords":    "No se encontraron resultados",
            "sEmptyTable":     "Ningún dato disponible en esta tabla",
            "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
            "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
            "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
            "sInfoPostFix":    "",
            "sSearch":         "Buscar:",
            "sUrl":            "",
            "sInfoThousands":  ",",
            "sLoadingRecords": "Cargando...",
            "oPaginate": {
                "sFirst":    "Primero",
                "sLast":     "Último",
                "sNext":     "Siguiente",
                "sPrevious": "Anterior"
            },
            "oAria": {
                "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
                "sSortDescending": ": Activar para ordenar la columna de manera descendente"
            }
        };
        var dataTable = [
            function (args) {
                $("#dataTable").DataTable({
                    language: dataTableLanguage,
                    processing: true,
                    serverSide: true,
                    destroy: true,
                    responsive: true,
                    ajax: {
                        data: null,
                        type: "POST",
                        url: "{{ route('tramite.index.post') }}",
                        error: function (jqXHR, textStatus, errorThrown) {
                            /*console.log(jqXHR);
                             console.log(textStatus);
                             console.log(errorThrown);*/
                        }
                    },
                    columns: [
                        {
                            data: "nombre",
                            name: "nombre"
                        },
                        {
                            data: "tramite_categoria_nombre",
                            name: "tramite_categoria_nombre",
                            render: function(data, type, row) {
                                var render = "";

                                if (data != "") {
                                    render = "<td>" + data + "</td>";
                                } else {
                                    render = "<td>---</td>";
                                }

                                return render;
                            }
                        },
                        {
                            data: "id_tramite_calificacion",
                            name: "id_tramite_calificacion",
                            render: function(data, type, row) {
                                var render = "";

                                if (data != "") {
                                    render = "<td>" + tramiteCalificacion[data] + "</td>";
                                } else {
                                    render = "<td>---</td>";
                                }

                                return render;
                            }
                        },
                        {
                            data: "plazo_resolucion",
                            name: "plazo_resolucion",
                            render: function(data, type, row) {
                                var render = "";

                                if (data != "") {
                                    render = "<td>" + data + (data != "1" ? " días" : " día") + "</td>";
                                } else {
                                    render = "<td>---</td>";
                                }

                                return render;
                            }
                        },
                        {
                            data: "id",
                            name: "id",
                            render: function(data, type, row) {
                                var render = "";
                                render += "<td class=\"td_center\">";
                                render += " <a onclick=\"Detalle(" + data + ")\" title=\"Detalle\" class=\"btn btn-outline btn-circle btn-sm green\">";
                                render += "     <i class=\"fa fa-eye\"></i> Detalle";
                                render += " </a>";
                                render += " <a onclick=\"Iniciar(" + data + ", " + row.id_area_inicio + ", '" + row.nombre + "')\" title=\"Iniciar\" class=\"btn btn-outline btn-circle dark btn-sm purple\">";
                                render += "     <i class=\"fa fa-file-text\"></i> Iniciar";
                                render += " </a>";
                                render += "</td>";

                                return render;
                            }
                        }
                    ],
                    order: [
                        [0, "asc"]
                    ],
                    dom: 'Bfrtip',
                    buttons: [
                        {
                            extend: 'excel',
                            exportOptions: {
                                columns: [ 0, 1, 2,3]
                            },
                            title: 'Listado de tramites'
                        },{
                            extend: 'pdf',
                            exportOptions: {
                                columns: [ 0, 1, 2,3]
                            },
                            pageSize: 'LEGAL',
                            customize: function(doc) {
                                //pageMargins [left, top, right, bottom]
                                doc.pageMargins = [ 120, 20, 20, 20 ];
                            },
                            title: 'Listado de tramites'
                        }

                    ]
                });
            }
        ];

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        function CargarDataTables(index, args) {
            index = index || -1;
            args = args || null;

            if (index < 0) {
                var dataTableLength = dataTable.length;
                for (var i = 0; i < dataTableLength; i++) {
                    dataTable[i](args);
                }
            } else {
                dataTable[index](args);
            }
        }

        function Detalle(id) {
            window.location.href = "{{ url('tramite/detalle/') }}" + "/" + id;
        }
        
        function Iniciar(id_tramite_procedimiento, id_dependencia, nombre) {
            document.getElementById("iniciarIdTramiteProcedimiento").value = id_tramite_procedimiento;
            document.getElementById("iniciarIdDependencia").value = id_dependencia;
            document.getElementById("iniciarNombre").value = nombre;

            $("#modalIniciar").modal("show");
        }
        
        function IniciarResult(element, event) {
            event.preventDefault();

            var formName = element.name;
            var form = document.forms[formName];

            $("#modalIniciar").modal("hide");

            swal({
                cancelButtonColor: "#dd3333",
                cancelButtonText: "No",
                confirmButtonColor: "#3085d6",
                confirmButtonText: "Sí",
                showCancelButton: true,
                showConfirmButton: true,
                text: form["nombre"].value,
                title: "¿Desea solicitar el trámite?",
                type: "warning"
            }, function (isConfirm) {
                $.ajax({
                    data: {
                        id_tramite_procedimiento: form["id_tramite_procedimiento"].value,
                        id_dependencia: form["id_dependencia"].value,
                        sustento: form["sustento"].value
                    },
                    type: "POST",
                    url: "{{ route('tramite.usuario.agregar.post') }}",
                    success: function(data) {
                        //console.log(data);

                        swal({
                            text: "Trámite agregado",
                            title: "Éxito",
                            type: "success"
                        }, function (isConfirm) {
                            //window.location.href = "{ url('tramite') }}";
                            form["sustento"].value = "";
                        });
                    },
                    error: function(error) {
                        //console.log(error);

                        swal({
                            text: "No se pudo agregar el trámite",
                            title: "Error",
                            type: "error"
                        }, function (isConfirm) {
                            //window.location.href = "{ url('/tramite/') }}";
                            form["sustento"].value = "";
                        });
                    }
                });
            });
        }

        window.onload = function() {
            CargarDataTables();
        };
    </script>
@endsection
