@extends('layouts.app')

@section('styles')
    <style xmlns="http://www.w3.org/1999/html">


        .panel-footer.text-right .btn {
            display: none;
        }

        .dropdown-menu form {

            margin: 0;
            display: block;
            padding: 3px 20px;
            clear: both;
            font-weight: 400;
            line-height: 1.42857143;
            color: #333;
            white-space: nowrap;

        }

        .dropdown-menu form:hover {
            background: #f5f5f5;

        }

        .dropdown-menu form input {
            color: #333;
            padding: 0;
            margin: 0;
            text-align: left;
            width: 100%;

        }

        .dropdown-menu form input:hover {
            text-decoration: none;
            background: #f5f5f5;
            color: #333;
        }

        {{--@if()--}}
        @if ($task->userCanEditTask() == false && $task->userTagCanViewTask($task->id,$task->unit_id) == false && $user->id != $task->user_id)
        .comments-container form{
            display: none;
        }
        @endif
    </style>

@section('content')
    {{--<div class="crumbs">--}}


    @if(Session::has('modal')))
    <script> console.log('modal');</script>
    @endif

    <div class="alert alert-success" role="alert" style="display: none">...</div>


    <div class="alert alert-danger alert-dismissible" hidden ="none" id="alerPipeline">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
        <p>Debe cambiar el estado de la tarea para cambiar la línea de producción.</p>

    </div>


    <div class="alert alert-warning alert-dismissible" hidden ="none" id="alerPipeline2">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
        <p>¿Esta seguro/a que desea crear una nueva tarea?.</p>

    </div>

    <div class="breads">

        <div class="panel" style="padding: 1%;display: table; float: right ; margin-bottom: 0px; list-style: none;width: 20%">
            <li style="font-size: 14px"><i>Línea de producción:</i><b style="color: #27a9f0"> {{$task->pipeline->first()->name }}</b> </li>

            @if($user->hasRole('supervisor') )


                <div class="input-group" id="pipeline-form" hidden= "none"  data-statu="{{ $task->status_id }}" style="margin-top: 8%;width: 80%">

                    <form id="pipeline-select"  style="width: 30%" action="{{ URL::to('/') }}/tasks/update-pipeline" method="post">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                        <input type="hidden" name="id" value="{{ $task->id }}">
                        <input type="hidden" name="status" value="{{ $task->status_id }}">
                        <select class="custom-select"  name="pipeline_id" >

                            {{--<option value="">Seleccione...</option>--}}

                            @if(isset($pipeline_unit))

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

                                    @if ($value != $task->pipeline->first()->name )
                                    <option  value="{{ $key}}"

                                             selected="selected"


                                    >{{$value}}</option>
                                    @endif
                                @endforeach
                            @endif

                        </select>
                        <button class="btn btn-default active" id="savePipeline" style="margin-top: 5%" >Guardar</button>
                    </form>

                </div>


                <li style="padding-top: 1%"><a class="btn btn-default active" id="setPipeline"  >Cambiar línea de producción</a></li>

            @endif


        </div>

        <div class="panel" style="padding: 16px;display: table;"><i style="font-size: 13px;"> Actividad de la
                unidad:
                @if($active_unit->slug != 'aprobacion')
                <a href="{{ URL::to('/') }}/tasks/unit/{{ $active_unit->id }}/show">{{ $active_unit->name }}</a>
                ({{ $active_unit->id }})
                @endif

            </i>
        </div>


        <?php $pipeline_length = count($pipeline->unitsByRevision($task->pipelineRevision)); ?>
        <?php  $opacity = '1';


//        var_dump($task->pipelineRevision);


        ?>

        @if($task->type=='other' || $task->type=='otros' || $task->type=='otro')



            <em> Esta tarea no tiene una línea de producción asignada </em>
            <button style="margin-left:10px;"type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#recategorize">Asignar Línea de Producción
            </button>
            </em><br>

    @else


            @foreach($pipeline->unitsByRevision($task->pipelineRevision) as $index=>$unit)

                <?php

                    if ($active_unit->id != $task->unit_id) {


                    $opacity = '0.5';

                        if ($active_unit->id == $unit->id) {
                            $opacity = '1';
                        }
                    }

                ?>
                @if($unit->id == $task->unit_id  && $unit->slug != 'aprobacion' ){{----}}


                    <?php

                    if ($active_unit->id == $task->unit_id) {
                        $link = '';
                    } else {
                        $link = URL::to('/') . '/tasks/' . $task->id . '/show/' . $unit->id;
                    }
                    ?>
                    <div style="position: relative;display: inline">

                        <button type="button" class="btn btn-lg btn-default btn-arrow-right active-unit  dropdown-toggle"
                                data-toggle="dropdown"
                                style="z-index:{{$pipeline_length-$index}} ;background: {{ $unit->color }};color:#fff;opacity:{{$opacity}}"
                                aria-haspopup="true" aria-expanded="false">{{ $unit->name }} </button>

                        @if ($active_unit->id != $task->unit_id)
                            <ul class="dropdown-menu" style="top:180%">

                                <li>
                                    <a href="{{ URL::to('/') }}/tasks/{{ $task->id }}/unit/{{ $unit->id }}/show/">Ver
                                        actividad
                                        de la tarea en {{ $unit->name }}</a>
                                </li>

                            </ul>
                        @endif

                    </div>
                @else


                    <div style="position: relative;display: inline">
                        @if($unit->name != 'Aprobación')
                        <button type="button" class="btn btn-default btn-arrow-right dropdown-toggle" data-toggle="dropdown"
                                aria-haspopup="true" aria-expanded="false" data-thisunit="{{$task->unit_id}}"
                                data-tounit="{{ $unit->id }}"
                                style="z-index:{{$pipeline_length-$index}} ;background: {{ $unit->color }};color:#fff;opacity:{{$opacity}}">{{ $unit->name }}                           </button>
                        <ul class="dropdown-menu" style="top:180%;">
                            @if ($active_unit->id == $task->unit_id)
                                @if($task->userCanPassTask())
                                    <li>
                                        <a href="#" class="js-move-unit" data-slug="{{ $unit->slug }}"
                                           data-name="{{ $unit->name }}" data-unit="{{ $unit->id }}" data-toggle="modal"
                                           data-target="#movemodal" data-backdrop="static" data-keyboard="false" >Enviar tarea </a>
                                    </li>
                                @endif
                            @endif
                            <li><a href="{{ URL::to('/') }}/tasks/{{ $task->id }}/unit/{{ $unit->id }}/show/">Ver actividad
                                    de la tarea en {{ $unit->name }}</a></li>

                        </ul>
                            @endif
                    </div>
                @endif

            @endforeach
    @endif





    </div>

    {{--</ul>--}}
    <br>
    @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(\Session()->has('perfilCambiado'))
        <div class="alert alert-success">
            {{ \Session()->get('perfilCambiado', 'Perfil cambiado correctamente') }}
        </div>
    @endif

    <br>
    <br>
    <div class="task-single">
        <div class="task-header">
            <div class="task-panel ">
                <div class="task-panel-main panel">
                    <div id="taskTL" style="display:block;">

                        @if($task->title)
                            <h4>{{ $task->title }}</h4>

                        @else
                            <h4>{{ $task->taskdata->title }}</h4>

                        @endif
                        @if ($task->taskdata->email_name)
                                <h5 style="font-weight: 600">Nombre:</h5>
                                {{ $task->taskdata->email_name }}
                            @endif

                            @if ($task->taskdata->email_surname)
                                <h5 style="font-weight: 600">Apellido:</h5>
                                {{ $task->taskdata->email_surname }}
                            @endif
                            @if ($task->taskdata->email_personalemail)
                                <h5 style="font-weight: 600">Email Personal:</h5>
                                {{ $task->taskdata->email_personalemail }}
                            @endif
                            @if ($task->taskdata->email_observation)
                                <h5 style="font-weight: 600">Observaciones:</h5>
                                {{ $task->taskdata->email_observation }}
                            @endif
                            @if ($task->taskdata->email_name_clean)
                                <h5 style="font-weight: 600">Nombre de la Cuenta a Blanquear:</h5>
                                {{ $task->taskdata->email_name_clean }}
                            @endif
                            @if ($task->taskdata->email_deleteemail)
                                <h5 style="font-weight: 600">Email a eliminar:</h5>
                                {{ $task->taskdata->email_deleteemail }}
                            @endif
                            @if ($task->taskdata->email_description)
                                <h5 style="font-weight: 600">Observaciones:</h5>
                                {{ $task->taskdata->email_description }}
                            @endif
                        <h5 style="font-weight: 600;max-height: none;height: auto; ">Descripción:</h5>
                        <div class="descriptionTaskTL">
                            @if($task->description)
                                {!!  $task->description !!}
                            @else
                                {!!  $task->taskdata->description !!}
                            @endif


                        </div>

                    </div>

                    <div id="form_edit" style="display: none">
                        <form action="{{ URL::to('/') }}/tasks/form_edit_Task" method="post">
                            <input type="hidden" name="_token" value="{{ csrf_token() }}">
                            <input type="hidden" name="id" value="{{ $task->id }}">

                            <label for="">Título</label><br>
                            @if($task->title)
                                <input name="title" style="width: 100% " type="text" value="{{$task->title }}"/>
                            @else
                                <input name="title" style="width: 100% " type="text"
                                       value="{{$task->taskdata->title }}"/>
                            @endif

                            <h5 style="font-weight: 600">Descripción:</h5>
                            <div>
                                @if($task->description)
                                    <textarea name="description" class="summer_description_show_task"   style="width: 100%;" rows="30"  value="">{!!  $task->description !!}

                                    </textarea>
                                @else
                                    <textarea name="description"  class="summer_description_show_task" style="width: 100%;" rows="30" value="">{!!  $task->taskdata->description !!}

                                        </textarea>
                                @endif
                            </div>

                            @if($task->type != 'email'){{--si la tarea es tipo 'email' no muestra deadline --}}
                                <div >
                                    <label for="edit_deadline" class="control-label">Deadline:</label>

                                    @if($task->deadline){{--si exite deadline en task entonces muestra fecha de esa columna  ,sino muestra el deadline de taskdata--}}
                                        <input class="form-control deadline2" name="edit_deadline" type="text" value="{{ date('d-m-Y', strtotime(str_replace('/', '-', $task->deadline))) }}">
                                    @elseif ($task->taskdata->deadline)
                                        <input class="form-control deadline2" name="edit_deadline" type="text" value="{{ date('d-m-Y', strtotime(str_replace('/', '-', $task->taskdata->deadline))) }}">
                                    @else
                                        <input class="form-control deadline2" name="edit_deadline" type="text" value="Sin Deadline asignado">
                                    @endif
                                </div>
                            @endif
                            <br>
                            <button class="btn btn-xs btn-raised btn-success" type="submit">Enviar</button>
                        </form>

                    </div>
                    <br>
                    <div class=" text-right">
                        @if($task->userCanEditTask())

                            <button class="btn btn-xs btn-default" id="editar" data-unico="taskdata" style="float: right;padding-right: 2%">
                                Editar
                            </button>
                        @endif
                        <button class="btn btn-xs btn-default" style="display: none" id="cancelar">Cancelar</button>
                            <br>
                    </div>
                    {{------- Botón Ver pedido completo--------}}
                    <button type="button" class="btn btn-primary btn-md" data-toggle="modal"
                            data-target="#taskdata" data-backdrop="static" data-keyboard="false" style="" >Ver pedido completo
                    </button>

                </div>

                <div class="task-panel-secondary" style="">
                    <div class="task-panel-secondary-inside panel">
                        <div class="task-creator">

                            <h5>Responsable de área: <a
                                        href="mailto:{{$task->profile->email}}"> {{ $task->profile->name }} {{ $task->profile->surname }}</a>
                            </h5>
                            <h5>Área: {{ $task->profile->area }}</h5>
                            <h5>Contacto:
                                {{--@if($active_unit->slug != 'pre-ingreso')--}}
                                    {{--<a href="mailto:{{ $task->taskdata->tasksRel->first()->createdBy->email }}">{{ $task->taskdata->tasksRel->first()->createdBy->name }} {{ $task->taskdata->tasksRel->first()->createdBy->surname }}</a>--}}
                                {{--@else--}}
                                    {{--<a href="mailto:{{ $task->createdBy->email }}">{{ $task->createdBy->name }} {{ $task->createdBy->surname }}</a>--}}
                                {{--@endif--}}

                                <a href="mailto:{{ $task->taskdata->tasksRel->first()->createdBy->email }}">{{ $task->taskdata->tasksRel->first()->createdBy->name }} {{ $task->taskdata->tasksRel->first()->createdBy->surname }}</a>

                            </h5>
                        </div>
                        <div class="task-date">
                            <h5>Fecha de creación: {{ date('d-m-Y H:i', strtotime(str_replace('/', '-', $task->created_at))) }}</h5>
                        </div>

                        @if($task->type != 'email')

                            <div class="task-deadline">
                                @if($task->deadline) {{--si la tarea es tipo 'email' no muestra deadline --}}
                                    <h5>Deadline: {{ date('d-m-Y', strtotime(str_replace('/', '-', $task->deadline))) }} &nbsp&nbsp</h5>
                                @elseif ($task->taskdata->deadline)
                                    <h5>Deadline: {{ date('d-m-Y', strtotime(str_replace('/', '-', $task->taskdata->deadline))) }} &nbsp&nbsp</h5>
                                @else
                                    <h5>Deadline: Sin Deadline asignado &nbsp&nbsp</h5>
                                @endif

                            </div>
                        @endif
                        <div >
                           Tiempo en esta unidad: <i style="color: #019d95">{{$difftime}}</i>
                        </div>
                        <br>
                        @if(\Auth::user()->hasRole('supervisor') || \Auth::user()->hasRole('administrator'))
                            <form method="post" action="{{\Url::to('/')}}/tasks/change-profile-task">
                                <input type="hidden" name="_token" value="{!! csrf_token() !!}">

                                <input type="hidden" name="tarea" id="tarea" value="{{ $task->id }}">

                                <select name="cambiarPerfilTarea" id="cambiarPerfilTarea" style="margin-bottom: 5px;width: 59%">
                                    <option value="{{$task->profile->id}}" selected>{{$task->profile->area}}</option>

                                    @foreach($profiles as $cadaPerfil)
                                        <option value="{{$cadaPerfil->id}}">{{$cadaPerfil->area}}</option>
                                    @endforeach
                                </select>

                                <input type="submit" value="Cambiar perfil de tarea" class="btn btn-primary">
                            </form>
                        @endif

                            {{--<form id="form-deadline" action="" style="display:none">--}}
                                {{--<input id="deadline3"  type="text" class="deadline1" name="dateDeadline" /> <br><br>--}}
                                {{--<input type="submit" value="enviar"/>--}}
                            {{--</form>--}}

                        @if($task->userCanChangeStatu() )

                            <select id="status-select" name="status" style="width: 40%">

                                <option value="">Seleccione estado...</option>

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

                                    <option value="{{ $value->id }}"
                                            @if ($value->id == $task->status_id)
                                            selected="selected"
                                            @endif
                                    >{{$value->name}}</option>
                                @endforeach

                            </select>
                            <button  id="changeStatus" type="button" data-backdrop="static" data-keyboard="false" class="btn btn-primary btn-md" data-toggle="modal"
                                    >Cambiar estado
                            </button>
                        @else
                            {{ $task->status->name}} <br>
                        @endif
                        <br>
                        @if($user->can('create-task') || $user->hasRole('administrator') || $user->hasRole('supervisor') || $user->hasRole('teamleader'))
                            <a class="btn btn-primary" href="{{URL::to('/') }}/tasks/teamLeader/{{$task->profile->id}}/{{$task->taskdata->id}}/{{$task->id}}/{{$task->unit_id}}">Crear tarea relacionada</a>

                        @endif

                        <br><br>
                        @if ($task->type == 'evento')
                        <a class="btn btn-primary" target="_blank" href="{{URL::to('/') }}/tasks/{{$task->id}}/download/pdf">Descargar PDF</a>
                        @endif
                    </div>

                </div>
            </div>

        </div>
        <br>

{{---------------------------Etiquetar------------------------------------------}}

        <div class="panel panel-default"  id="#takstags">
            <div class="panel-heading">

                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                <input type="hidden" name="type" value="task">
                <input type="hidden" name="relation_id" value="{{ $task->id }}">

                {{--<input type="hidden" name="user_id" value="obtener usuarios"  >--}}
                @if($user->canTagOthers())

                    <div class="form-group" style="font-weight: normal;">
                        <h4>Etiquetar usuarios</h4>
                        <div class="s2-example col-sm-6" style="">
                            <select class="js-example-data-array" multiple="multiple" data-placeholder="" id="userTL" name="selectUser[]"  style="width:80%">
                                <option value="" >Seleccione usuario</option>

                                     @foreach($users as $u)

{{--                                    @if (in_array('autotag',$user->getRoleInUnit($user->id,$task->unit_id)))--}}
{{--                                        @if (in_array('autotag',$user->getRoleInUnit($u->id,$task->unit_id)) || $u->id == 31)--}}
{{--                                            <option value="{{$u->id}}">{{$u->name}}{{$u->surname}}</option>--}}
{{--                                        @endif--}}
{{--                                    @else--}}
                                        <option value="{{$u->userID}}">{{$u->name}} {{$u->surname}}</option>
{{--                                    @endif--}}

                                    @endforeach

                            </select>
                            <button class="btn btn-primary" id="etiquetar">Etiquetar</button>

                        </div>
                    </div>
                @endif
            </div>
            {{-----------etiquetados ---------}}
            <div   id="tabla_tasktags_ajax"  class="panel-body" style="font-size: small"  >
                <h4>Etiquetados :<br></h4>

                    @foreach($usersEtiq as $index=>$u)

{{--                         @if($u['unit']== $active_unit->id )--}}

                            <button id="user-{{$index}}">
                                <span class="glyphicon-class"></span><label>{{$u['name']}}&nbsp&nbsp</label>

                                @if($user->canTagOthers())

                                    <span onClick=untag({{$index}})  class="glyphicon glyphicon-remove" aria-hidden="true"> </span>
                                @endif

                            </button>

                        {{--@endif--}}

                    @endforeach

            </div>
            {{-------fin de etiquetados---------------}}
        </div>

{{-- fin de etiquetar --}}
        <br>
        <div class="task-bottom">
            <div class="comments-container">
                @include('comments::comments-react', [
                    'content_type' => App\Task::class,
                    'content_id' => $task->id
                ])
            </div>
            <div class="task-sidebar">

                @if($user->hasPermission('approve-task') && $task->unit->approve_unit == 1)
                <div class="sidebar-container panel">
                    <form method="POST" action="{{ URL::to('/') }}/store/coverage" accept-charset="UTF-8" id="" >
                        <input type="hidden" name="id" value="{{ $task->id }}">
                        <input type="hidden" name="profile_id" value="{{ $task->profile_id }}">
                        <input type="hidden" name="title" value="{{ $task->title }}">

                        <input type="hidden" name="deadline" value="{{ $task->deadline }}">

                        <input type="hidden" name="taskdata_id" value="{{ $task->taskdata_id }}">
                        <input type="hidden" name="description" value="{{ $task->taskdata->description }}">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                        <h4>Tareas a Generar</h4>
                        <ul class="task-subtask-list">
                            @foreach($pipelines as $index=>$pipeline)

                                @if($pipeline->public == 1)
                                    <li style="border-bottom: none;" >
                                        <input type="checkbox" value="{{ $pipeline->id }}" name="event_coverage[]"
                                               @if(in_array(  $pipeline->id , $generatedPipelines)) disabled @endif
                                               @if(in_array(  $pipeline->id , $generatedPipelines))  checked @endif>
                                        {{ $pipeline->public_name ? $pipeline->public_name : $pipeline->name }}

                                        @foreach($relatedTasks as $rTask)

                                            @if($rTask->pipeline->first()->id == $pipeline->id  )

                                                <a style="font-size:10px"href="{{ URL::to('/')}}/tasks/{{ $rTask->id}}/unit/{{ $rTask->unit->id }}/show "> Enlace</a> <br>
                                                @else


                                                @endif
                                            @endforeach
                                    </li>
                                @endif
                            @endforeach
                        </ul>


                        <div class="coverage-action" style="opacity: 1;">
                            <button data-backdrop="static" data-keyboard="false" type="submit" class="btn btn-primary btn-md " data-toggle="modal">
                                Generar Tarea
                            </button>
                            <br><br>

                        </div>
                    </form>
                </div>
                
                @endif



































                   {{--@if(count($relatedTasks) > 0)--}}
                    {{--<div class="sidebar-container panel relatedTask">--}}
                        {{--<h5>Tareas Generadas</h5>--}}
                        {{--@foreach($relatedTasks as $rTask)--}}

                                {{--<a style="" href="{{ URL::to('/')}}/tasks/{{ $rTask->id}}/unit/{{ $rTask->unit->id }}/show "> {{ $rTask->pipeline->first()->name }}</a> <br>--}}


                        {{--@endforeach--}}

                    {{--</div>--}}

                    {{--@endif--}}




                    <?php $exist_entregados = false;  ?>

                @if($user->canViewAttach())
                <div class="sidebar-container panel entregados" style="display:none">
                    <div class="no-content task_element">



                            @if (is_countable($attachments))

                            <h5 style="font-weight: 600">Archivos Entregados:</h5>

                            @foreach($task->attachments as $attach)

                                <?php

                                  if(($attach->pivot->active == "1")&&($attach->delivered == "1")){

                                      $exist_entregados = true;
                                   ?>

                                     <div style='color:#777 !important' class="bdn subattachtask_element deliveredSub delsub_{{$attach->id}}">{{ $attach->original_name}}<span class='minidatetask_{{$attach->id}} minifecha' style='margin-left: 6px;font-size: 14px;font-style: inherit;'>{{ date('d/m/Y', strtotime($attach->created_at))}}</span></div>

                                <?php
                                }
                                ?>


                            @endforeach
                        @endif
                    </div>
                </div>
<?php

/*
echo "<pre>";
var_dump($task->attachments->toArray());
echo "</pre>";
exit;
*/

?>









                <div class="sidebar-container panel ajduntados">

                    <div class="no-content task_element desde_ajax">


















                    </div>

                    <div class="form-group flex center box_supArchivo" style="text-align:-webkit-center" >

                    <div class="task_temporal_progress">
                        <progress class="barProgress_task" max="100" value="0" style="display: none;margin-bottom: 6px;margin-left: 12%;margin-right: 12%"><span id="textProgress_task">22</span></progress>
                        <ul id="file-upload-list" class="list-unstyled file-upload-list_task" data-type="task">
                        </ul>
                        <ul id="file-upload-progress_task" class="list-unstyled"></ul>
                    </div>

                        <input type="hidden" name="jsonIdAttachments" id="jsonIdAttachments_task" value="">
                        <input type ="hidden" name ="_token" value ="{{ csrf_token() }}" />
                        <input type="hidden" id="task_id" name="task_id" value="{{ $task->id }}">

                    </div>


                    <div class="nuevo_div">

                            <div>

                            <button type="button" id="buttonDownload" style="width: 90px;display:none" class="btn btn-primary">Descargar</button>
                            @if ($task->status_id != 3 && $task->status_id != 6)
                            <span class="btn btn-success fileinput-button box_elegirArchivo" style="visibility: hidden" >
                                <i class="icon-plus icon-white"></i>
                                <span>Subir Archivos</span>
                                <input id="fileupload" class="fileupload" data-type="task" multiple type="file" name="file" data-url="{{ url('upload') }}" style="display: inline;">

                            </span>
                            @endif
                            </div>

                    </div>


            </div>













                <div class="sidebar-container panel nuevo_divCompatido">

                    <div class="no-content">

                           @if (is_countable($unicos))

                            <h5 style="font-weight: 600">Archivos Compartidos:</h5>

                            @foreach($unicos as $attach3)

                                <?php


                                        /* Archivo activo  */

                                        $attaoriginal_name = "'".$attach3['original_name']."'";

                                   ?>

                                    <div class="bdn subattachtask_element subattachtask_{{$attach3['id']}} item_compartido compartido_{{$attach3['id']}}" data-fileatta="{{$attach3['filename']}}" data-dateatta="{{ date('d/m/Y', strtotime($attach3['created_at']))}}" data-nameatta='{{ $attach3['original_name'] }}' ><a href='{{URL::to('/')}}/download/{{$attach3['id']}}' target='_blank'>{{ $attach3['original_name']}}<span class='minidatetask_{{$attach3['id']}} minifecha' style='margin-left: 6px;font-size: 14px;font-style: inherit;'>{{ date('d/m/Y', strtotime($attach3['created_at']))}}</span></a><button type='button' title="Compartir Archivo" onclick='combinateAttach({{ $attach3['id']}},false,{{ $attaoriginal_name}})' class='btn btn-success btn-xs stack_deleted elementTheTask'>+</button></div>


                            @endforeach
                        @else
                          <div class="task_text_borrador">No se encontraron archivos Compartidos</div>
                        @endif
                    </div>

                    <div class="form-group flex center box_supArchivo" style="text-align:-webkit-center" >



                        <input type="hidden" name="jsonIdAttachments" id="jsonIdAttachments_task" value="">
                        <input type ="hidden" name ="_token" value ="{{ csrf_token() }}" />
                        <input type="hidden" id="task_id" name="task_id" value="{{ $task->id }}">

                    </div>


                    <div >

                            <div>

       



                            </div>

                    </div>


            </div>

















                        <?php $user= Auth::user(); ?>

                        @if ($user->canViewListSubtask() == true && $user->isTeamLeaderInUnit($task->unit_id))


                    <div class="sidebar-container panel">

                            @if($task->subtasks->count() != 0)

                                <h4>Subtareas</h4>
                                <ul class="task-subtask-list">

                                    @foreach($task->subtasks as $index=>$subtask)

                                        <li>
                                            <a href="{{ URL::to('/') }}/subtasks/{{$subtask->id}}/show"> {{$subtask->title}} </a>
                                            <h6>creada
                                                por: {{ $subtask->createdBy->name }} {{ $subtask->createdBy->surname }} </h6>
                                            <h6>Asignada
                                                a: {{ $subtask->assignedTo->name }} {{ $subtask->assignedTo->surname }} </h6>
                                            <h6>Status: {{ $subtask->status->name }}  </h6>
                                        </li>

                                    @endforeach
                                </ul>

                            @else
                                <div class="no-content">
                                    No se encontraron Subtareas

                                </div>

                            @endif

                            <div class="subtask-action" style="opacity: 1;">
                                {{--<button class="btn btn-primary btn-large"  data-toggle="modal" data-target="#subtarea-modal"> Crear subtarea</button>--}}
                                <button data-backdrop="static" data-keyboard="false" type="button" class="btn btn-primary btn-md createSubtarea" data-toggle="modal" data-target="#create-subtarea">
                                    Crear subtarea
                                </button>
                                <br><br>

                            </div>

                        </div>
                        @endif
                @endif

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


        <!-- Button trigger modal -->


        <!-- Modal -->

    @endsection


    @section('modals')
        <div class="modal fade" id="create-subtarea" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <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" id="myModalLabel">Crear Subtarea</h4>
                    </div>
                    <div class="modal-body">
                        @include('shared.alertError')

                        <form action="{{ URL::to('/') }}/subtasks/store" method="post" class="form_createsub" enctype="multipart/form-data"
                              id="mensaje">

                            <input type="hidden" name="_token" value="{{ csrf_token() }}">

                            <div class="form-group">
                                <label for="">Título</label><br>
                                <input type="text" name="title" value="{{ $task->taskdata->title }}">
                            </div>
                            <div class="form-group">

                                <input type="hidden" name="task_id" value="{{ $task->id }}">
                            </div>
                            <div class="form-group">

                                <input type="hidden" name="user_id" value="{{ $user->id }}">
                            </div>
                            <div class="form-group">
                                <textarea class="summer" style="width:100%;"
                                          name="description">------------------------<br>{!! $task->taskdata->description !!}</textarea>
                            </div>



                               @if (is_countable($attachments))

                                    <div class="form-group filesforTask">
                                        <label for="">Archivos de la tarea</label><br>


                                          <select multiple="" id="taskAttach_multiple" class="form-control" style="width:100%;margin-bottom:10px">
                                            {{--
                                            @foreach($task->attachments as $attach)

                                            @if($attach->pivot->active=="1")

                                            <option class="attachtask_{{ $attach->id }}" data-filename="{{ $attach->filename }}" value="{{ $attach->id }}" >{{ $attach->original_name }}</option>

                                            @endif

                                            @endforeach
                                            --}}
                                          </select>
                                         <div class="alltach" style="display:none;text-align:center;margin-top: 16px;margin-bottom: 20px;">Todos los archivos de la tarea fueron asignados a la subtarea.</div>

                                        <button type="button" style="font-size: 14px;width: 154px;text-align: center;padding-left: 9px;" class="btn  btn-info btn-sm addsubtask" style="display:none">Agregar a la subtarea</button>

                                    </div>

                            @endif

                            <div class="form-group" style="margin-top: 18px;">
                            <label  for="">Archivos de la subtarea</label>
                            <div class="subAttach"></div>
    <div class="subtask_text_borrador"></div>

    {{-- text_borrador  --}}
    <div class="subtask_temporal_progress">
                            <ul id="file-upload-progress_subtask" class="list-unstyled sub_enseptiembre"></ul>
                            <progress class="barProgress_subtask" max="100" value="0" style="display: none;margin-bottom: 10px"><span
                            id="textProgress_subtask">22</span></progress>
                            <ul id="file-upload-list" class="list-unstyled file-upload-list_subtask sub_enseptiembre" data-type="subtask" style="margin-bottom: 10px"></ul>
    </div>

                            <span class="btn btn-success fileinput-button" style="display: table-cell;">
                                <i class="icon-plus icon-white"></i>
                                <span>Subir Archivos</span>
                                <input id="fileupload" class="fileupload" data-type="subtask" multiple type="file" name="file" data-url="{{ url('upload') }}"
                                       style="display: inline;">
                            </span>

                        <input type="hidden" name="jsonIdAttachments" id="jsonIdAttachments_subtask" value='<?php echo !empty(old("jsonIdAttachments"))?old("jsonIdAttachments"):""; ?>'>
                        <input type="hidden" id="jsonIdAttachments_subtask_aux" value="">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}"/>

                            </div>
                            <div class="form-group">
                                <label for="">Deadline</label><br>
                                <div class='input-group date' id='datetimepicker2'>
                                    <input type='text' name="deadline" class="form-control"/>
                                    <span class="input-group-addon">
                                        <span class="glyphicon glyphicon-calendar"></span>
                                    </span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="">Usuario Asignado</label>
                                <select name="assigned_id" id="">
                                    <option value="">Seleccionar Usuario...</option>

                                    @foreach($task->unit->teamMemberByUnit as $tm)

                                            <option value="{{ $tm->id }}">{{ $tm->name }} {{ $tm->surname }} -- Rol
                                                : {{ $teamroles[$tm->pivot->teamrole_id ] }} </option>

                                    @endforeach

                                </select>
                            </div>
                            <input class="btn btn-primary" type="button" id="create_sub" value="Crear Subtarea">
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
                    </div>
                </div>
            </div>
        </div>

        <div id="movemodal" class="modal fade" role="dialog">
            <div class="modal-dialog">

                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Enviar tarea a la unidad <b class="js-unit-name"></b></h4>
                    </div>
                    <div class="modal-body">
                        <div>
                            <form id="" style="" action="{{ URL::to('/') }}/tasks/move-to-task" method="post">
                                <input type="hidden" name="_token" value="{{ csrf_token() }}">

                                <input type="hidden" name="task_id" value="{{ $task->id }}">
                                <input type="hidden" name="from_unit" value="{{ $task->unit_id }}">
                                <input type="hidden" name="to_unit" value="">
                                <input type="hidden" name="unit_id" value="{{ $task->unit_id }}">
                                <div class="form-group">

                                    <label for="">Agrega un comentario</label>
                                    <p class="help">Este comentario será agregado a la tarea destino</p>
                                    <textarea style="width: 100%;" name="add_content" id="" cols="30" rows="10"></textarea>
                                </div>
                                <hr>
                                <div style="height:15px !important">
                                <input style=""  class="btn btn-primary change_level" type="submit"
                                       value="Enviar tarea">
                                </div>
                            </form>

                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
                    </div>
                </div>

            </div>
        </div>

        <div id="taskdata" class="modal fade " role="dialog">
            <div class="modal-dialog modal-lg">

                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Detalles</h4>
                    </div>
                    <div class="modal-body">
                        @include('task.taskdata')
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
                    </div>
                </div>

            </div>
        </div>
        <div id="recategorize" class="modal fade " role="dialog">
            <div class="modal-dialog modal-md">

                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Asignar línea de producción a esta tarea</h4>
                    </div>
                    <div class="modal-body">
                        <form action="{{ URL::to('/') }}/tasks/assign-pipeline" method="post">
                            <input type="hidden" name="_token" value="{{ csrf_token() }}">

                            <input type="hidden" name="taskId" value="{{$task->id}}">
                            <select name="pipeline_assign" id="pileline_assign">
                                <option value="">Elegir una línea de producción</option>
                                @foreach($pipelines_query as $pipeline)
                                    @if ($pipeline->deprecated != 1)
                                        <option @if(Auth::user()->hasRole('supervisor') != 1 && $pipeline->id == 13) hidden @endif value="{{ $pipeline->id }}">{{ $pipeline->name }}</option>
                                    @endif
                                @endforeach


                            </select>
                            <input type="submit" value="Asignar">
                        </form>


                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
                    </div>
                </div>

            </div>
        </div>


    <style>

    /*
        .subattach:last-child{

            margin-bottom: 20px;

        }*/

    /*
        .bdn{
            width:300px;
             word-break:break-all;
            color: red;
            height: 20px;
            font-size: 14px;
        }
    */

        /*   new   */

        .ajduntados{

            padding: 30px 70px !important;

        }

        .minifecha{

            font-size: 11px !important;
        }

        .bdn {
            /* width: 360px; */
            word-break: break-all;
            color: red;
            margin-top: 7px;
            margin-bottom: 7px;
            /* height: 20px; */
            font-size: 11px;
        }


        .stack_deleted{

            position: absolute !important;
            margin-left: 20px;
            margin-top: -4px !important;
            line-height: 0px;
            height: 12px;
            font-size: 11px;
            width: 12px;
            padding-left: 2px;
        }


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

        /* NEW*/


        .stack_newed{
            color: white;
            float: none;
            height: 16px;
    /*      background-color: orange;  */
            left: 40px;
            line-height: 2px;
            padding-left: 2.5px;
            top: -1.5px;
    /*      font-weight: bold;  */
            height: 14px;
            margin-left: -2px;
            width: 14px;
            position: relative;
        }


        .not_deliver{
            background-color: #FF8000;
            border-color: #FF8000;
            color:white;
        }

        .delivered{
    /*      background-color: #549E54;
            border-color: #549E54;  */
            color:#549E54;
        }


        .not_deliver:hover{
            background-color: #FF8000;
            border-color: #FF8000;
            color:white;
        }


        .delivered:hover{
    /*      background-color: #549E54;
            border-color: #549E54;  */
            color:#549E54;
        }
        .opt_delivered{
            color: #BCBCBC;
            background-color: #FFFFD2;
        }

        .stack_newed:focus{
        color:white;
        }

    </style>

    @endsection


    @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']);
            $('.deadline1').datepicker();
            $('.deadline2').datepicker();


        </script>
        <script>
        //----------------editar deadline --------------------------
// -*- se comenta el botón editar deadline ya que también se puede editar al editar la tarea  -*- 

//            function editardlbtn(e){
//
//                $("#form-deadline").show();
//                $(e).hide();
//
//            }

            {{--$("#form-deadline").submit(function(event) {--}}
                {{--event.preventDefault();//hace que no se recarge la página--}}

                {{--$.ajax({--}}
                    {{--data:{deadline:$("#deadline3").val(),taskid:{{$task->id}} },--}}
                    {{--url:"{{ URL::to('/') }}/deadline",--}}
                    {{--type: "post",--}}
                    {{--headers: {--}}
                        {{--'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')--}}
                    {{--},--}}
                    {{--success: function(result) {--}}
                        {{--// console.log(result.deadline);--}}

                        {{--$(".task-deadline").html("");--}}
                        {{--$(".task-deadline").append("<h5>Deadline: "+result.deadline+"&nbsp&nbsp<button onclick='editardlbtn(this)' class='editar-dl-btn'>Editar</button></h5>");--}}
                        {{--$("#form-deadline").hide();--}}
                        {{--$(".editar-dl-btn").show();--}}
                    {{--}--}}
                {{--});--}}
            {{--});--}}


    //---------------------fin deadline----------------------------------------------

            $(document).ready(function () {

                //  Llamo por Ajax a la vista que me devuelve los archivos de cada tarea

                getAttachByTask();


                $(".change_level").on("click",function(){

                    $(this).hide();

                });

                //  Verifica los attach segun el task

                <?php echo ($exist_entregados)?'$(".entregados").show();':'$(".entregados").hide();'; ?>


                verifyAttachinTask();


                $("#jsonIdAttachments_subtask").val("");
                $("#jsonIdAttachments_subtask_aux").val("");


                // Al abrir un modal se visualizan los archivos nuevos

                $(".createSubtarea").on("click",function(){

                    $("#taskAttach_multiple option:selected").removeAttr("selected");
                    verifyAttachinTask();

                });




            $(".addsubtask").on("click",function(){


                if($('#taskAttach_multiple').val()){

                    $(".addsubtask").prop("disabled",true);


                    objetJson = "";
                    multiple  = "";


                    if($('#taskAttach_multiple').val()){

                            var multiple = []

                            multiple      = $('#taskAttach_multiple').val();

                            $("#taskAttach_multiple option:selected").removeAttr("selected");

                            if($("#jsonIdAttachments_subtask_aux").val()!= ""){

                                var objetJson = JSON.parse($("#jsonIdAttachments_subtask_aux").val());

                            }else{

                                var objetJson = $("#jsonIdAttachments_subtask_aux").val();

                            }

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


                            if(!objetJson){

                                objetJson = [];
                            }

                                e = parseInt(valor);

                                objetJson.push({id: e});


                                ee       = $(".attachtask_"+valor).html();
                                fn       = $(".attachtask_"+valor).data("filename");
                                var date = new Date($(".attachtask_"+valor).data("createdat"));
                                createdt = date.getDate()+'/'+(date.getMonth()+ 1)+'/'+date.getFullYear();

                              //   console.log(dd,valor);


                                linkAttach = '<div class="bdn subattachtask_element suboption_subattachtask_'+valor+'"><a href="http://guntref.dev/uploads/'+fn+'" target="_blank">'+ee+' '+createdt+'</a><button onclick="subdeleteAttach('+valor+')" type="button" class="btn btn-danger btn-xs stack_deleted">x</button></div>';


                                $(".subtask_text_borrador").before(linkAttach);

                                $(".attachtask_"+valor).hide();
                                $(".attachtask_"+valor).removeClass("miniAttach");  // nuevo


                        });

                         $(".subAttach").children().css( "margin-bottom", "0px" );

                         $(".subAttach").children().last().css( "margin-bottom", "6px" );


                    if(($("#jsonIdAttachments_subtask_aux").val()!="")&&($('#taskAttach_multiple').val()!="")){

                            objetJson=JSON.stringify(objetJson);
                    }


                    if(($("#jsonIdAttachments_subtask_aux").val()=="")&&($('#taskAttach_multiple').val()!="")){

                            objetJson=JSON.stringify(objetJson);
                    }

                       $("#jsonIdAttachments_subtask_aux").val(objetJson);  //  al enviar

                    }


                    $(".addsubtask").prop("disabled",false);


                    /*  HTML  */


                    if($(".miniAttach").length == 0){  // otra clase

                        $(".alltach").show();
                        $(".addsubtask").hide();
                        $("#taskAttach_multiple").hide();

                    }



                    }

                });


                // quitar , esto se hace con subtarea boton azul

                $("#create_sub").on("click",function(){


                    if(($("#jsonIdAttachments_subtask").val()!="")&&($("#jsonIdAttachments_subtask_aux").val()!="")){


                        a = JSON.parse($("#jsonIdAttachments_subtask").val());
                        b = JSON.parse($("#jsonIdAttachments_subtask_aux").val());


                        if((a!="")&&(b!="")){

                            c = a.concat(b);

                        }else if((a!="")&&(b=="")){

                            c = a;

                        }else{

                            c = b;
                        }


                        $("#jsonIdAttachments_subtask").val(JSON.stringify(c));

                    }else if(($("#jsonIdAttachments_subtask").val()=="")&&($("#jsonIdAttachments_subtask_aux").val()!="")){


                       $("#jsonIdAttachments_subtask").val($("#jsonIdAttachments_subtask_aux").val());

                    }

                    $("#taskAttach_multiple option:selected").removeAttr("selected");
                    $("#jsonIdAttachments_subtask_aux").val("");


                    $(".form_createsub").submit();

                });


            // new
            jsonOldAttach = $("#jsonIdAttachments_subtask").val();

                $("#buttonDownload").on("click",function(){

                    var d = new Date();
                    var n = d.getTime();

                    location.href = "{{ URL::to('/') }}/tasks/{{ $task->id }}/download?"+n;


                });




                countAtachFiles = parseInt($(".elementTheTask").length); {{--   parseInt("{{ count($task->attachments) }}");  --}}

                if(countAtachFiles>0){

                        seeDownload();

                }else{

                    $(".nuevo_div").css("text-align","center");
                    $(".box_elegirArchivo").css("visibility","visible");

                    $(".box_supArchivo").css("margin-top","12px");
                    $(".box_supArchivo").css("text-align","center");

                }


                @if($errors->any())

                    $('#create-subtarea').modal('show');

                @endif


                $('.js-move-unit').click(function (ev) {
                    ev.preventDefault();
                    $('#movemodal').find('input[name="to_unit"]').val($(this).attr('data-unit'));
                    $('#movemodal').find('.js-unit-name').html($(this).attr('data-name')).addClass($(this).attr('data-slug'));


                });
                $(function () {
                    $('#datetimepicker2').datetimepicker({
                        locale: 'es'
                    });
                });


                $('#status-select').select2(

                );


                var $eventSelect = $('#status-select');

                var statu = 0 ;

                $eventSelect.on('select2:select', function (e) {

                    statu = e.params.data.id;

                });



                $('#changeStatus').click(function () {

//                        $(this).prop("disabled","disabled");


                        $eventSelect.select2('val', 'all');

                        var taskID ={{ $task->id }};


                        if (statu) {

                            $.ajax({
                                type: 'POST',
                                url: '{{ URL::to('/') }}/tasks/update-status',
                                headers: {
                                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                },
                                dataType: 'json',

                                data: {id: taskID, status_id: statu},

                                success: function (data) {


                                    if (data[0] == 200) {

                                        $('#status-select').select2('val', statu);
                                        $(".alert-success").html('Estado actualizado.');
                                        $(".alert-success").show(500);
                                        setTimeout(function () {
                                            $(".alert-success").hide(500)
                                        }, 2000);

                                        $('#pipeline-form').attr('data-statu',statu);
                                        $('#pipeline-form').hide();
                                        $('#setPipeline').show();


                                    }

                                }

                            });

                        }


                    });


                $('.summer').summernote();

                $('.descriptionTaskTL').readmore({
                    speed: 75,
                    moreLink: '<a class="readmore more"href="#">Ver más</a>',

                    lessLink: '<a class="readmore less"href="#">Ver menos</a>',
                    heightMargin: 16,
                });


                $(window).resize(function () {

                    ellipses1 = $("#bc1 :nth-child(2)")
                    if ($("#bc1 a:hidden").length > 0) {
                        ellipses1.show()
                    } else {
                        ellipses1.hide()
                    }

                    ellipses2 = $("#bc2 :nth-child(2)")
                    if ($("#bc2 a:hidden").length > 0) {
                        ellipses2.show()
                    } else {
                        ellipses2.hide()
                    }

                });

    //----------------------------------------------------------------

                var status =$('#pipeline-form').attr('data-statu');
                if(status){
                    $('#pipeline-form').hide();
                }


                    $('#setPipeline').click(function () {


                    var status =$('#pipeline-form').attr('data-statu');

                    console.log(status);

                    if(status == 3){

                        $("#alerPipeline").show(500);
                            setTimeout(function () {
                                $("#alerPipeline").hide(500)
                            }, 2000);

                        $('#pipeline-form').hide();
                        $('#setPipeline').hide();

                    }
                    if(status == 6){

                        $("#alerPipeline2").show(500);
                        setTimeout(function () {
                            $("#alerPipeline2").hide(500)
                        }, 2000);

                        $('#pipeline-form').show();
                        $('#setPipeline').hide();

                    }
                    if(status == 1 || status == 5 ) {

                        $('#pipeline-form').show();
                        $('#setPipeline').hide();

                    }

                });


    //----------------------------------------------------------------------------------

                //etiquetar usuarios


                var userselect = $(".js-example-data-array");


                userselect.select2({
                    placeholder: 'Seleccione usuarios',
                });



                var userArray =[];//arreglo global ,guarda usuarios etiquetados


                userselect.on('select2:select', function (e) {

                    userArray.push(e.params.data.id);

                });

                userselect.on('select2:unselect', function (e) {

                    var noUser = e.params.data.id;

                    if(noUser != null){

                        for(var x =0 ;x < userArray.length ;x++){

                            if(noUser == userArray[x]){
    //                        console.log(noUser,userArray[x]);
                                userArray[x]=null;
                            }

                        }
                    }
                });


                $('#etiquetar').click(function () {

                    userselect.select2('val', 'all');

                    var taskId = '{{$task->id}}';
                    var type = 'task';
                    var unit = '{{ $active_unit->id }}';


                    if(userArray.length>0) {
    //                    console.log(userArray.length);

                        $.ajax({

                            type: 'POST',
                            url: '{{ URL::to('/') }}/taskTag',
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                            },

                            data: {userId: userArray, taskId: taskId, type: type, unit: unit},
                            success: function (data) {
                                //
                                var usuarios = data;

                                if (usuarios.length > 0) {

                                    for (var x = 0; x < data.length; x++) {

                                        $('#tabla_tasktags_ajax').append('<button id="user-'+usuarios[x][1]+'" ><span class="glyphicon-class"></span><label>' + usuarios[x][0]+'&nbsp&nbsp</label>' +
                                            '@if($user->canTagOthers())'+
                                            '<span class="glyphicon glyphicon-remove" aria-hidden="true" onClick=untag('+usuarios[x][1]+')> </span>' +
                                            '@endif'+
                                            '</button>');//concatena la variable
                                    }
                                }
                            },
                        });
                        userArray =[];
                    }else{

                        alert("Debe seleccionar un usuario");
                    }

                });

            //------ crear nueva tarea con pipeline -----

                $("#savePipeline").on("click",function(){

                    $(this).hide();
                });

            //-----  fin ----

            });


        /***
        * @param id_pipeline
        * @param user_id
        * @post Remueve la etiqueta del pipeline seleccionado
        *
        */
            var flag = 0

            function untag(index) {

                if (flag == 0) {
                    flag = 1;
                    $.ajax({

                        data: {id_tag: index},
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                        },
                        dataType: 'json',
                        url: "{{ URL::to('/') }}/untag",
                        type: 'POST',
                        success: function (data) {

                            $("#user-" + index).hide();

                            flag = 0;
                        }
                    });

                }
            }

    //-------------------------------fin etiquetar usuarios------------------------

            function deleteAttachsub(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) {



                    $(".option_subattachtask_"+id_item).hide();
                    $("#taskAttach_multiple option:selected").removeAttr("selected");
                    $(".attachtask_"+id_item).show();
                    $(".attachtask_"+id_item).addClass("miniAttach");

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


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

                        if(valor.id==id_item){

                            tt.splice(indice, 1);

                        }
                     });

                    $(".subAttach").children().first().css( "margin-bottom", "6px" );
                    $("#jsonIdAttachments_subtask_aux").val(JSON.stringify(tt));

                  }
                })


                if(!$("#taskAttach_multiple").is(":visible")){

                    $("#taskAttach_multiple").show();
                    $(".alltach").hide();
                    $(".addsubtask").show()
                }


                $(".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");



            }


            function notactive(){


                swal({
                  title: "Activar Archivo",
                  text: "Este archivo fue entregado desde subtarea, para activarse, debe ser entregado de nuevo",
                  icon: "warning",
             //   buttons: true,
                  dangerMode: true,
                })
                .then((willDelete) => {
                /*
                  if (willDelete) {
                    swal("Poof! Your imaginary file has been deleted!", {
                      icon: "success",
                    });
                  } else {
                    swal("Your imaginary file is safe!");
                  }
                  */
                });


            }








        function combinateAttach(id_item,flag,name){

 
/*
            swal({
              title: 'Compartir',
              text: "Estas seguro de compartir el archivo a la tarea?",
              type: 'warning',
              showCancelButton: true,
              confirmButtonColor: '#d33',
              cancelButtonColor: '#3085d6',
              confirmButtonText: 'Enviar'
            }).then((result) => {
              if (result.value) {
*/

                $.ajax({

                    data: {task:{{ $task->id }},attachitem:id_item},
                    headers:{
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    },
                    dataType: 'json',
                    url:"{{ URL::to('/') }}/tasks/{{ $task->id }}/combinateAttachtask ",
                    type:'POST',
                    success:  function (data) {

                        if(data.status == "ok"){
/*
                            swal(
                              'Compartido!',
                              'El archivo fue compartido a la tarea.',
                              'success'
                            )
*/

                            $(".compartido_"+id_item).hide();

                             getAttachByTask();


                             ccont = 0;

                             $(".item_compartido").each(function( index ) {

                              if($(this).css('display') !== 'none') {
                                    ccont++;
                                }

                            });

                            if(ccont==0){

                                $(".nuevo_divCompatido").html("No se encontraron archivos Compartidos");
                                $(".nuevo_divCompatido").css("text-align","center");

                            }


                        }
                    }
                });
/*
              }
            })
*/

            $(".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");



           }





           function getAttachByTask(){


                $.ajax({

                    data: {task:{{ $task->id }}},
                    headers:{
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    },
                    dataType: 'json',
                    url:"{{ URL::to('/') }}/tasks/getAttachByTask ",
                    type:'POST',
                    success:  function (data) {

                        $(".desde_ajax").html(data.todo);


                    }
                });


           }

            function deliverAttach(id_item){
                swal({
                    title: 'Confirma entrega de archivo',
                    text: false,  // "Ingresa "+sweetsms.toLowerCase()+" el archivo "+delete_deliver+"?",
                    type: false,
                    showCancelButton: true,
                    confirmButtonColor: '#5cb85c',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Entregar'
                }).then((result) => {



                    if (result.value) {

                    $.ajax({

                        data: {task:{{ $task->id }}, attachitem:id_item },
                        headers:{
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                        },
                        dataType: 'json',
                        url:"{{ URL::to('/') }}/tasks/{{ $task->id }}/deliverAttachtask",
                        type:'POST',
                        success:  function (data) {
                            if(data.status == "ok"){


                                swal(
                                    'Entregado!',
                                    'El archivo fue entregado correctamente.',
                                    'success'
                                )


                            }

                        }
                    });



                }
            });
            }

            function deleteAttach(id_item,flag,name){


                // console.log("asdasdasd"+name);


                deleteall      = null;
                delete_deliver = "";

                if ( $(".subattachtask_"+id_item).hasClass("desdesub") ) {

                    delete_deliver = " entregado desde subtarea";
                    deleteall      = true;

                }

                sweetsms = (flag)?"Activar":"Eliminar";
                coloract = (flag)?"#5cb85c":"#d33";

                $(".swal2-warning").hide();




                swal({
                  title: 'Confirmar',
                  text: false,  // "Ingresa "+sweetsms.toLowerCase()+" el archivo "+delete_deliver+"?",
                  type: false,
                  showCancelButton: true,
                  confirmButtonColor: coloract,
                  cancelButtonColor: '#3085d6',
                  confirmButtonText: sweetsms
                }).then((result) => {



                  if (result.value) {


                    comment = $(".comment_event").val();

                    $.ajax({

                        data: {task:{{ $task->id }},attachitem:id_item,deleteall:deleteall,activate:flag,task_id:{{ $task->id }},unit_id:{{ $task->unit_id }},comment:comment,name:name},
                        headers:{
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                        },
                        dataType: 'json',
                        url:"{{ URL::to('/') }}/tasks/{{ $task->id }}/deleteAttachtask",
                        type:'POST',
                        success:  function (data) {

                            if(data.status == "ok"){


                                if(flag){


                                    swal(
                                        'Activado!',
                                        'El archivo fue activado correctamente.',
                                        'success'
                                    )


                                    lagr = '"'+$(".subattachtask_"+id_item).data("nameatta")+'"';

                                    $(".subattachtask_"+id_item).html("<a href='{{ URL::to('/') }}/uploads/"+ $(".subattachtask_"+id_item).data("fileatta")+"' target='_blank'>"+$(".subattachtask_"+id_item).data("nameatta")+"<span class='minidatetask_"+id_item+" minifecha' style='margin-left: 6px;font-size: 14px;font-style: inherit;'>"+$(".subattachtask_"+id_item).data("dateatta")+"</span></a><button type='button' title='Eliminar Archivo' onclick='deleteAttach("+id_item+",false,"+lagr+")' class='btn btn-danger btn-xs stack_deleted elementTheTask'>x</button>");

                                    return true;

                                }

                                contentlink = $(".subattachtask_"+id_item).children("a").html();

    /*
                                 $(".subattachtask_"+id_item).data('dateatta',"aaaaaa");
                                 $(".subattachtask_"+id_item).data('nameatta',"bbb");
    */

                                lagr = '"'+$(".subattachtask_"+id_item).data("nameatta")+'"';

                                $(".subattachtask_"+id_item).html("<div><span class='datin'>"+contentlink+"</span><button style='font-size: 8px !important;padding-left: 0.5px !important' type='button' onclick='deleteAttach("+id_item+",true,"+lagr+")' class='btn btn-success btn-xs stack_deleted elementTheTask'><i class='fa fa-check'></i></button></div>");

                                verifyAttachinTask();

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

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

                                    $(".nuevo_div").css("height","38px");
                                    // $(".subAttach").html("No se encontraron archivos Adjuntos");
                                    $("#buttonDownload").hide();

                                }


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

                                    $(".entregados").hide();

                                }



                            }
                        }
                    });



                  }
                })


                $(".swal2-contentwrapper").children().last().css("margin-bottom","0px");

                btndelete = (flag)?"btn-success":"btn-danger";

                $(".swal2-confirm").attr("class","btn "+btndelete+" swal2-confirm");

                if(flag){
                    $(".swal2-confirm").attr("style","");
                }

            //  $("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");


                nop = (flag)?"activar":"eliminar";

                $("#swal2-content").after('<div class="form-group"><p class="help">Ingresa un motivo para '+nop+' el archivo "'+name+'"</p><textarea style="margin-top: 6px;width: 100%;" name="comment_event" class="comment_event" cols="30" rows="10"></textarea></div>');



           }



            function verifyAttachinTask(){



                    $.ajax({

                        data: {task_id:{{ $task->id }},subtask_id:null },
                        headers:{
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                        },
                        dataType: 'json',
                        url:"{{ URL::to('/') }}/tasks/getAttachTask",
                        type:'POST',
                        success:  function (data) {

                            if(data.attachs){

                            //   console.log(data);

                                        /*
                                        if(!$("#taskAttach_multiple").is(":visible")){

                                            $("#taskAttach_multiple").show();
                                            $(".alltach").hide();
                                            $(".addsubtask").show()
                                        }
                                        */

                                        $("#taskAttach_multiple").html("");

                                        linkAttach = "";


                                        data.attachs.forEach( function(valor, indice, array) {


                                            linkAttach += '<option data-createdAt="'+valor.created_at+'" data-filename="'+valor.filename+'" class="miniAttach attachtask_'+valor.id+'" value="'+valor.id+'">'+valor.original_name+'</option>';


                                        });

                                        $("#taskAttach_multiple").append(linkAttach);
                                        $(".filesforTask").show();

                                }else{

                                        $(".filesforTask").hide();

                                }

                        }
                    });
            }



        function subdeleteAttach(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) {


                    if($("#jsonIdAttachments_subtask").val()!=""){

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


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

                                if(valor.id==id_item){

                                    tt.splice(indice, 1);

                                }
                             });


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

                    }



                if($("#jsonIdAttachments_subtask_aux").val()!=""){


                        vv = JSON.parse($("#jsonIdAttachments_subtask_aux").val());

                    //    console.log(vv);

                            vv.forEach( function(valor2, indice2, array2) {

                                if(valor2.id==id_item){

                                    vv.splice(indice2, 1);

                                }
                             });

                        $("#jsonIdAttachments_subtask_aux").val(JSON.stringify(vv));

                    }


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

                    if ( $(".attachtask_"+id_item).length > 0 ) {
                      $("#taskAttach_multiple").show();
                      $(".alltach").hide();
                      $(".addsubtask").show();
                    }

                    $(".attachtask_"+id_item).addClass("miniAttach");
                    $(".attachtask_"+id_item).show();

                    /*
                        if($(".elementTheTask").length==0){ //sub  No existe eliminar al cargar archivos

                            $(".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>
        @include('task.forms.event_scripts')



    @endsection
