@extends('layouts.app')
@section('styles')

@section('content')

    <div class="container">
        <div class="row" style="width:100%;">
            <div class="col-md-10 col-md-offset-1">
                <div class="panel panel-default">


                    {{--<div class="panel-heading">Panel de {{ $user->name }} {{ $user->surname }}</div>--}}
                    <div style="padding:16px;">
                        @if(session()->has('message'))
                            <div class="alert alert-success alert-dismissable">
                                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                {{ session()->get('message') }}
                            </div>
                        @endif
                        @if ($errors->any())
                            <div class="alert alert-danger">
                                <ul>
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        @endif

                        <h3>Crear Tarea</h3>
                        <br>
                        <form method="POST" action="{{ URL::to('/')}}/tasks/teamLeader/form" accept-charset="UTF-8">
                            <input type="hidden" name="_token" value="{{ csrf_token() }}">

                            <input type="hidden" name="type" value="email">

                            @if($taskId != null)

                                <input type="hidden" name="related_task" value="{{$taskId}}">
                                <input type="hidden" name="related_unit" value="{{$unitId}}">
                            @endif

                            <h4><i class="fa fa-pencil-square-o" aria-hidden="true"></i> &nbsp;Seleccionar Perfil</h4>

                            <hr>
                            {{------------------------------------select profile ---------------------------------------}}
                            <div class="col-md-12">

                                <div class="form-group">
                                    <select name="profile_id" id="perfil" style="width:100% !important">
                                        <option value="">Seleccionar Perfil</option>

                                        @foreach($profiles as $key=>$value)


                                            @if($value->status == 1)    {{--**--}}
                                            <option   value="{{ $value->id }}"


                                                      @if ($value->id == old('profile_id', ($profile != null) ? $profile->id : null) )

                                                      @endif

                                                      @if($profile != null)
                                                      @if($profile->id  == $value->id)
                                                      selected="selected"

                                                      @else
                                                      disabled="true"
                                                    @endif
                                                    @endif

                                            > {{ $value->area }}

                                            </option>
                                            @endif
                                        @endforeach
                                    </select>
                                    <p id="" style="font-size:12px;color:#969696;" class="help-block">Perfil relacionado a la tarea.</p>

                                </div>

                                {{--------------------------------fin select profile ----------------------------------}}

                                <p id="" style="font-size:12px;color:#969696;" class="help-block">Perfil relacionado
                                a la tarea.</p>

                                <br>

                                <div class="form-group" style="display: none" id="datosTL">


                                        <label>Datos de Tarea</label><br>
                                        <div class="s2-example" style="">
                                            <p>

                                                <select name="taskdataid" id="tasksTL" class="  form-control" >

                                                    <option value="{{  ($taskdata == null) ? old('taskdataid') :$taskdata->id  }}"

                                                    >Seleccione</option>
                                                </select>
                                            </p>
                                        </div>

                                </div>
                                <br>

                                <hr>


                            </div>
                            <hr>
                            <br>
                            <br>
                            <h4><i class="fa fa-pencil-square-o" aria-hidden="true"></i> &nbsp;Datos de la consulta</h4>
                            <hr>

                            <div class="col-md-12"><h4></h4>

                                <div class="form-group">
                                    <label for="">Título</label><br>
                                    <input  onkeypress="return anular(event)" type="text" name="title" value="{{ old('title') }}" class="form-control">
                                </div>
                                <div class="form-group">
                                    <label for="description" class="control-label">Descripción</label>
                                    <p id="" style="font-size:12px;color:#969696;" class="help-block">Campo de texto
                                        para asiento de cambios y opción de carga de archivos.</p>

                                    <textarea class="form-control summer_create_teaml" name="description" cols="50" rows="10"
                                              id="description">{{ old('description') }}</textarea>

                                </div>

                                <!--tr data-category-id="" class="unity-list"-->
                                <div class="form-group" >
                                    <label for="">Línea de producción</label><br>
                                    <div style="display: flex" div class="s2-example" style="">
                                        <select name="pipeline" data-category="" style=""  class="  form-control" >
                                            <option value="">-</option>
                                            @foreach($pipelines as $p)
                                                @if ($p->deprecated != 1)
                                                    <option @if(Auth::user()->hasRole('supervisor') != 1 && $p->id == 13) hidden @endif value="{{ $p->id }}">{{ $p->name }}</option>
                                                @endif
                                            @endforeach
                                        </select>
                                        <br>
                                    </div>
                                </div>
                                <br>
                                <div class="form-group">

                                    <label for="email_deadline" class="control-label">Deadline:</label>
                                    <input class="form-control" name="deadline" type="text" id="deadline" class="deadline" value="{{ old('deadline') }}">
                                </div>
<br>

                            <div class="form-group">
                                <label for="adjuntos" class="control-label">Adjuntos:</label>
                                <div class="task_text_borrador"></div>
                                <div class="task_temporal_progress">
                                <progress class="barProgress_task" max="100" value="0" style="display: none;"><span id="textProgress_task">22</span></progress>
                                <ul id="file-upload-progress_task" class="list-unstyled">
                                </ul>
                                <ul id="file-upload-list" class="list-unstyled file-upload-list_task" data-type="task">
                                </ul>
                                </div>
                                <span class="btn btn-success fileinput-button">
                                    <i class="icon-plus icon-white"></i>
                                    <span>Subir Archivos</span>
                                    <input id="fileupload" class="fileupload" multiple type="file" data-type="task" name="file" data-url="{{ url('upload') }}" style="display: inline;">
                                </span>

                                <input type="hidden" name="jsonIdAttachments" id="jsonIdAttachments_task" value="">
                            </div>



                            </div>
                            <br>
                            <br>

                            <input type="button" class="form-control"  value="Enviar" onclick="form.submit()">

                        </form>
                    </div><?php /* Fin del Formulario  */ ?>
                </div>
            </div>
        </div>
    </div>

    <div id="demo"></div>
@endsection
<style>/*
    .subattach:last-child{

        margin-bottom: 20px;
        
    }*/
    .bdn{
        color: #979797;
        height: 20px;
        font-size: 14px;
    /*  margin-bottom: 10px */
    }
    .stack_deleted{

        position: absolute !important;
        margin-left: 20px;
        line-height: 8px !important;
        height: 14px;
        font-size: 11px !important;
        width: 14px;
        padding-left: 3px !important;

    }
    .sub_enseptiembre{
        margin-bottom: 2px;
    }

    .subattachtask_element:first-child {
    margin-top: 6px;
    }

    .datin{
            margin-left: 6px;
            font-size: 14px;
            font-style: inherit;
            color: #979797;
            opacity: 0.7;
    }

</style>

@section('scripts')
    <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
    <script>


        var disableddates = ["12-25-2018","1-1-2019","5-1-2018","5-25-2018","7-9-2018"];//mes,dia,año ,acà se agrega días feriados inamovibles
        function DisableSpecificDates(date) {
            var m = date.getMonth();
            var d = date.getDate();
            var y = date.getFullYear();
            var currentdate = (m + 1) + '-' + d + '-' + y ;
            for (var i = 0; i < disableddates.length; i++) {
                if ($.inArray(currentdate, disableddates) != -1 ) {
                    return [false];
                }
            }
            var weekenddate = $.datepicker.noWeekends(date);
            return weekenddate;
        }

        $.datepicker.regional['es'] = {
            closeText: 'Cerrar',
            prevText: '<Ant',
            nextText: 'Sig>',
            currentText: 'Hoy',
            monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
            monthNamesShort: ['Ene','Feb','Mar','Abr', 'May','Jun','Jul','Ago','Sep', 'Oct','Nov','Dic'],
            dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
            dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
            dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sá'],
            weekHeader: 'Sm',
            dateFormat: 'dd/mm/yy',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: '',
            beforeShowDay: DisableSpecificDates,
            minDate: 1
        };
        $.datepicker.setDefaults($.datepicker.regional['es']);
        $('#deadline').datepicker();


    </script>
    <script>

//        console.log('asdf');

        @if(old('profile_id'))

//                    console.log('asdf');

                perfilTL = "<?php echo !empty(old('profile_id'))?'true':''; ?>";

                if(perfilTL=="true"){
            
                  $("#datosTL").show();
                  $("#perfil").select2().select2('val','<?php echo old('profile_id');?>');

                  {{--$("#perfil").select2().select2('val','<?php echo old('profile_id',($profile != null) ? $profile->id : null);?>');--}}


<?php if(empty(old('taskdataid'))){?>


                            selectTaskdata = $('#tasksTL');
        //                    console.log('aca');
                            selectTaskdata.select2({
                                // Activamos la opcion "Tags" del plugin
                                tags: true,
                                tokenSeparators: [','],
                                ajax: {
                                    dataType: 'json',
                                    url: '{{ url("taskdata") }}',
                                    delay: 250,
                                    data: function (params) {

                                        return {
                                            term: params.term,
                                            profile_id:<?php echo old('profile_id');?>,
                                        }
                                    },
                                    processResults: function (data, page) {

                    

                                    //    console.log(data);
                                        return {
                                            results: data

                                        };
                                    },
                                }
                            });


<?php  }  ?>

                        // taskdataid

                        @if(old('taskdataid'))


                            tareaTL = "<?php echo !empty(old('taskdataid'))?'true':''; ?>";

                            if(tareaTL=="true"){

                                    $("#tasksTL").html();
                                    $("#tasksTL").html("<option value=''>Searching...</option>");
                                        



                                    var request = $.ajax({
                                      url: '{{ url("taskdata") }}',
                                      method: "GET",
                                      data: { profile_id :<?php echo old('profile_id');?>},
                                      dataType: "json"
                                    });
                                     
                                    request.done(function( obj ) {


                                        //Add returned options
                                        $.each(obj, function (index) {   

                                        valor = obj[index].id;
                                        texto = obj[index].text;

                                        $("#tasksTL").append('<option value=' + valor + '>' + texto + '</option>');
                                        
                                        // $("#tasksTL").prop("readonly", false);
                                        
                                        });


                                        //  reinicializar a select2

          
                                            //  myFunction();
                                            var eventselect = $('#perfil');
                                            eventselect.select2();
                                 
                                            var selectTaskdata = null;
                                 
                                            eventselect.on('select2:select', function (e) {
                                //                console.log(eventselect.select2('val'));
                                 
                                                if (selectTaskdata) {
                                                    selectTaskdata.select2('destroy');
                                 
                                                }
                                                //    $('#datosTL').css({'display':'block'});
                                                    selectTaskdata = $('#tasksTL');
                                //                    console.log('aca');
                                                    selectTaskdata.select2({
                                                        // Activamos la opcion "Tags" del plugin
                                                        tags: true,
                                                        tokenSeparators: [','],
                                                        ajax: {
                                                            dataType: 'json',
                                                            url: '{{ url("taskdata") }}',
                                                            delay: 250,
                                                            data: function (params) {
                                                                return {
                                                                    term: params.term,
                                                                    profile_id:eventselect.select2('val'),
                                                                }
                                                            },
                                                            processResults: function (data, page) {
                                                                console.log(data);
                                                                return {
                                                                    results: data
                                 
                                                                };
                                                            },
                                                        }
                                                    });

                                 
                                        });
         
               
                                        $("#tasksTL").select2().select2("val","{{ old('taskdataid') }}");

                                        $("#perfil").addClass("perfil_init");


                                    });

                            }

                        @endif


                    //  $("#tasksTL").select2().select2('val','2');

                }


        @endif




        $('.summer_create_teaml').summernote({ height: 200 });    

        function anular(e) {

            tecla = (document.all) ? e.keyCode : e.which;
            return (tecla != 13);
        }

        function myFunction() {
            var x = document.getElementsByTagName("input");

        //    console.log("x: " + x);
        //    console.log("Number of inputs: " + x.length);

            var arrayOfInputNames = [];

            for (var i = 0; i < x.length; i++) {
                //for(key in x) {
            //    console.log("i: " + i);
            //    console.log("value: " + x[i].name);

                arrayOfInputNames.push(x[i].name);
            }
        //    console.log(arrayOfInputNames);
            document.getElementById("demo").innerHTML = arrayOfInputNames;
        }

        $(document).ready(function () {


            @if(!old('taskdataid'))

                $("#perfil").addClass("perfil_init");

            @endif



            $('.perfil_init').on('change', function() {

                $("#tasksTL").html("<option>Seleccione</option>");

            })


            //  myFunction();
            var eventselect = $('#perfil');
            eventselect.select2();

            var selectTaskdata = null;
                                                                           

            eventselect.on('select2:select', function (e) {
            //    console.log(eventselect.select2('val'));

            if (selectTaskdata) {
                selectTaskdata.select2('destroy');

            }
                $('#datosTL').css({'display':'block'});


            //   console.log("delilah "+eventselect.select2('val'));

            <?php if(empty(old('taskdataid'))){?>


                      selectTaskdata = $('#tasksTL');
                    //    console.log('aca');
                    selectTaskdata.select2({
                        // Activamos la opcion "Tags" del plugin
                        tags: true,
                        tokenSeparators: [','],
                        ajax: {
                            dataType: 'json',
                            url: '{{ url("taskdata") }}',
                            delay: 250,
                            data: function (params) {

                                return {
                                    term: params.term,
                                    profile_id:eventselect.select2('val'),
                                }
                            },
                            processResults: function (data, page) {

            

                        //        console.log(data);
                                return {
                                    results: data

                                };
                            },
                        }
                    });

            <?php } ?>

            });


        });

   function deleteAttach(id_item){

        

        swal({
          title: 'Confirmar',
          text: "Estas seguro de eliminar el archivo?",
          type: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#d33',
          cancelButtonColor: '#3085d6',
          confirmButtonText: 'Eliminar'
        }).then((result) => {
          if (result.value) {


                tt = JSON.parse($("#jsonIdAttachments_task").val());


                tt.forEach( function(valor, indice, array) {

                    if(valor.id==id_item){

                        tt.splice(indice, 1);

                    }
                 });

                $("#jsonIdAttachments_task").val(JSON.stringify(tt));


                $(".subattachtask_"+id_item).remove();

                if($(".elementTheTask").length==0){

                    $(".nuevo_div").css("height","38px");
                    $("#buttonDownload").hide();

                }




          }
        })


        $(".swal2-confirm").attr("class","btn btn-danger swal2-confirm");
    //  $("swal2-popup").css("width","400px");
        $(".swal2-cancel").css("margin-left","6px");
        $(".swal2-cancel").attr("class","btn btn-primary swal2-cancel");
        $(".swal2-warning").css("width","66px");
        $(".swal2-warning").css("height","66px");
        $(".swal2-icon.swal2-warning").css("line-height","70px");

    }

    </script>


@endsection

