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

@endsection
@section('title',config('app.name') . ' | ' . __('base/cfdi_download.document_title'))
@section('css_specific')
    <link href="{{ asset('gentelella/plugins/bootstrap-daterangepicker/daterangepicker.css') }}" rel="stylesheet"/>
    <link href="{{ asset('gentelella/plugins/google-code-prettify/bin/prettify.min.css') }}" rel="stylesheet"/>
@endsection
@section('css')

@endsection
@section('content')
    <div id="modals">

    </div>

    <!-- page content -->
    <div class="right_col" role="main">
        <div class="">

            <!-- Titulo -->
            <div class="page-title">
                <div class="title_left">
                    <h3>@lang('base/cfdi_download.document_title')</h3>
                </div>
                <div class="title_right text-right">
                    <div class="row">
                        <div class="col-md-12 col-xs-12 pull-right">
                            <a href="#"
                               class="btn btn-sm btn-success btn-cfdi-download-deposit-add">@lang('general.button_create_deposit')
                            </a>
                            &nbsp;
                            <a href="#"
                               class="btn btn-sm btn-success btn-cfdi-download-expense-add">@lang('general.button_create_expense')
                            </a>
                            &nbsp;
                            @if(!empty(setting('diot')) || \Auth::user()->new_user)
                            <a href="{{route('diots.index')}}"
                               class="btn btn-sm btn-success">@lang('general.button_diot')
                            </a>
                            @endif
                            &nbsp;
                            <a href="{{route('cfdi-downloads/create-sat-login')}}"
                               class="btn btn-sm btn-success">@lang('general.button_cfdi_downloads')
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <!-- /Titulo -->

            <div class="clearfix"></div>

            <!-- Mensajes -->
            <div id="general_messages">
                @include('flash::message')
            </div>
            <!-- /Mensajes -->

            <!-- Filtros -->
            <div class="row">
                <div class="col-md-12 col-xs-12">
                    <div class="x_panel">
                        <div class="x_content">
                            <div class="filter-data">
                                {!! Form::open(['route' => 'cfdi-downloads.index','method' => 'GET','class' => '','role' => 'form','id'=>'form']) !!}
                                <div class="row">
                                    <div class="col-md-2 col-xs-12">
                                        <div class="form-group form-group-sm">
                                            {!! html_entity_decode(Form::label('filter_name', __('base/cfdi_download.entry_name_uuid') , ['class' => 'control-label'])) !!}
                                            {!! Form::text('filter_name', request()->input('filter_name'), ['class' => 'form-control', 'placeholder' => __('base/cfdi_download.entry_name_uuid'),'autofocus']) !!}
                                        </div>
                                    </div>
                                    <div class="col-md-2 col-xs-12">
                                        <div class="form-group form-group-sm">
                                            {!! html_entity_decode(Form::label('filter_date_from', __('general.text_date_from') . '', ['class' => 'control-label'])) !!}
                                            <div class="input-group input-group-sm">
                                                {!! Form::text('filter_date_from', request()->input('filter_date_from',\App\Helpers\Helper::date(Date::parse('first day of this month')->subMonth())), ['class' => 'form-control', 'placeholder' => __('general.text_date_from'),'autocomplete'=>'off']) !!}
                                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-2 col-xs-12">
                                        <div class="form-group form-group-sm">
                                            {!! html_entity_decode(Form::label('filter_date_to', __('general.text_date_to') . '', ['class' => 'control-label'])) !!}
                                            <div class="input-group input-group-sm">
                                                {!! Form::text('filter_date_to', request()->input('filter_date_to',\App\Helpers\Helper::date(Date::parse('last day of this month'))), ['class' => 'form-control', 'placeholder' => __('general.text_date_to'),'autocomplete'=>'off']) !!}
                                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 col-xs-12">
                                        <div class="form-group form-group-sm">
                                            {!! html_entity_decode(Form::label('filter_emisor', __('base/cfdi_download.entry_emisor') , ['class' => 'control-label'])) !!}
                                            {!! Form::text('filter_emisor', request()->input('filter_emisor'), ['class' => 'form-control', 'placeholder' => __('base/cfdi_download.help_emisor')]) !!}
                                        </div>
                                    </div>
                                    <div class="col-md-3 col-xs-12">
                                        <div class="form-group form-group-sm">
                                            {!! html_entity_decode(Form::label('filter_receptor', __('base/cfdi_download.entry_receptor') , ['class' => 'control-label'])) !!}
                                            {!! Form::text('filter_receptor', request()->input('filter_receptor'), ['class' => 'form-control', 'placeholder' => __('base/cfdi_download.help_receptor')]) !!}
                                        </div>
                                    </div>
                                    <div class="col-md-2 col-xs-12">
                                        <div class="form-group form-group-sm">
                                            {!! html_entity_decode(Form::label('filter_type', __('base/cfdi_download.entry_type') , ['class' => 'control-label'])) !!}
                                            {!! Form::select('filter_type', ['1' => __('base/cfdi_download.tab_received'),'2' => __('base/cfdi_download.tab_issued')],request()->input('filter_type'), ['class' => 'form-control', 'placeholder' => __('general.text_all')]) !!}
                                        </div>
                                    </div>
                                    <div class="col-md-2 col-xs-12">
                                        <div class="form-group form-group-sm">
                                            {!! html_entity_decode(Form::label('filter_cfdi_type_id', __('base/cfdi_download.entry_cfdi_type_id') , ['class' => 'control-label'])) !!}
                                            {!! Form::select('filter_cfdi_type_id', $cfdi_types,request()->input('filter_cfdi_type_id'), ['class' => 'form-control', 'placeholder' => __('general.text_all')]) !!}
                                        </div>
                                    </div>
                                    <div class="col-md-2 col-xs-12">
                                        <div class="form-group form-group-sm">
                                            {!! html_entity_decode(Form::label('filter_status', __('base/cfdi_download.entry_status') , ['class' => 'control-label'])) !!}
                                            {!! Form::select('filter_status', $sat_status,request()->input('filter_status'), ['class' => 'form-control', 'placeholder' => __('general.text_all')]) !!}
                                        </div>
                                    </div>
                                </div>
                                <div class="row" style="margin-top: 10px;">
                                    <div class="col-md-4 col-xs-5 text-left">
                                        <div class="form-inline">
                                        <span>
                                            <span class="hidden-xs">@lang('general.text_item_per_page')</span>
                                            {!! Form::select('limit', $limits,request()->input('limit',setting('list_limit','100')), ['class' => 'form-control input-sm', 'placeholder' => __('general.text_select'),'onchange' => 'this.form.submit()']) !!}
                                        </span>
                                        </div>
                                    </div>
                                    <div class="col-md-8 col-xs-7 text-right footer-form">
                                        {!! Form::button(__('general.button_search'),['type' => 'submit', 'class' => 'btn btn-sm btn-default', 'id' => 'btn_search']) !!}
                                        &nbsp;
                                        {!! Form::button(__('general.button_validate_status_sat'),['type' => 'submit', 'class' => 'btn btn-sm btn-default','name' => 'validate_status_sat','value' => '1']) !!}
                                        &nbsp;
                                        {!! Form::button(__('general.button_edit_selected'),['type' => 'submit', 'class' => 'btn btn-sm btn-default', 'id' => 'btn_edit_selected']) !!}
                                        &nbsp;
                                        {!! Form::button(__('general.button_download_xmlpdf'),['type' => 'submit', 'class' => 'btn btn-sm btn-default','name' => 'download_xmlpdf','value' => '1']) !!}
                                        &nbsp;
                                        {!! Form::button(__('general.button_delete_selected'),['type' => 'submit', 'class' => 'btn btn-sm btn-default','id' => 'btn_delete_selected']) !!}
                                        &nbsp;
                                        <a href="{{route('cfdi-downloads/export-to-excel',request()->except('page'))}}" class="btn btn-sm btn-excel">
                                            @lang('general.button_export_to_excel')
                                        </a>
                                    </div>
                                </div>
                                {!! Form::close() !!}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- /Filtros -->

            <!-- Contenido -->
            <div class="row">
                <div class="col-md-12 col-xs-12">
                    <div class="x_panel">
                        <div class="x_title">
                            <h2>@lang('general.text_list')</h2>
                            <div class="clearfix"></div>
                        </div>
                        <div class="x_content">
                            <!-- Filtros -->

                            <!-- /Filtros -->
                            <!-- Datos -->
                            <div class="table-responsive table-data table-dropdown">
                                <table class="table table-striped table-hover table-condensed">
                                    <thead>
                                    <tr class="mini">
                                        <th class="text-center" style="width: 25px;">
                                            <input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);"/>
                                        </th>
                                        <th class="text-center">@sortablelink('type',
                                            __('base/cfdi_download.column_type'))
                                        </th>
                                        <th class="text-center">@sortablelink('cfdiType.name',
                                            __('base/cfdi_download.column_cfdi_type'))
                                        </th>
                                        <th class="text-center">@sortablelink('name',
                                            __('base/cfdi_download.column_name'))
                                        </th>
                                        <th class="text-center" style="width: 80px;">@sortablelink('date',
                                            __('base/cfdi_download.column_date'))
                                        </th>
                                        <th class="text-center">@sortablelink('uuid',
                                            __('base/cfdi_download.column_uuid'))
                                        </th>
                                        <th class="text-left">@sortablelink('emisor',
                                            __('base/cfdi_download.column_emisor'))
                                        </th>
                                        <th class="text-left">@sortablelink('receptor',
                                            __('base/cfdi_download.column_receptor'))
                                        </th>
                                        <th class="text-left">@sortablelink('expense_type_id',
                                            __('base/cfdi_download.column_expense_type'))
                                        </th>
                                        <th class="text-left">@sortablelink('paymentWay.name',
                                            __('base/cfdi_download.column_payment_way'))
                                        </th>
                                        <th class="text-center">@sortablelink('currency.code',
                                            __('base/cfdi_download.column_currency'))
                                        </th>
                                        <th class="text-center">@sortablelink('amount_total',
                                            __('base/cfdi_download.column_amount_total'))
                                        </th>
                                        <th class="text-center">@sortablelink('balance',
                                            __('base/cfdi_download.column_balance'))
                                        </th>
                                        <th class="text-center">@sortablelink('status',
                                            __('base/cfdi_download.column_status'))
                                        </th>
                                        <th class="text-center" width="5%">@lang('general.column_actions')</th>
                                    </tr>
                                    </thead>
                                    <tbody class="" style="font-size: 95%;">
                                    @forelse($results as $result)
                                        <tr class="mini">
                                            <td class="text-center">
                                                <input class="" type="checkbox" name="selected[]" value="{{$result->id}}"/>
                                            </td>
                                            <td class="text-center">{{$result->type_name}}</td>
                                            <td class="text-center">{{$result->cfdiType->name ?? ''}}</td>
                                            <td class="text-center">
                                                {{$result->name}}
                                                @if($result->conciled)
                                                    <br/>
                                                    <small class="text-muted">{{ __('base/cfdi_download.text_conciled') }}</small>
                                                @endif
                                                @if(!$result->file_xml_exists)
                                                    <br>
                                                    <label class="label label-warning">{{ __('general.text_xml_not_found') }}</label>
                                                @endif
                                            </td>
                                            <td class="text-center">{{ \App\Helpers\Helper::convertSqlToDateTime($result->date) }}</td>
                                            <td class="text-center">
                                                <small>{{ $result->uuid }}</small>
                                            </td>
                                            <td class="text-left">
                                                {{ $result->emisor }}
                                                @if(!empty($result->emisor) && !empty($result->comment))
                                                    <br>
                                                    <small class="text-muted">{{ $result->comment }}</small>
                                                @endif
                                                @if(!empty(setting('black_list_sat')))
                                                @if($result->blackListSatEmisor)
                                                    <br>
                                                    <label class="label label-danger">RFC en lista negra ({{$result->blackListSatEmisor->status_sat}})</label>
                                                @endif
                                                @endif
                                            </td>
                                            <td class="text-left">
                                                {{ $result->receptor }}
                                                @if(!empty($result->receptor) && empty($result->emisor) && !empty($result->comment))
                                                    <br>
                                                    <small class="text-muted">{{ $result->comment }}</small>
                                                @endif
                                                @if(!empty(setting('black_list_sat')))
                                                @if($result->blackListSatReceptor)
                                                    <br>
                                                    <label class="label label-danger">RFC en lista negra ({{$result->blackListSatReceptor->status_sat}})</label>
                                                @endif
                                                @endif
                                            </td>
                                            <td class="text-left">
                                                <span id="txt_expense_type_{{$result->id}}">
                                                {{ $result->expenseType->name ?? '' }}
                                                </span>
                                            </td>
                                            <td class="text-left">{{$result->paymentWay->name ?? ''}}</td>
                                            <td class="text-center">{{ $result->currency->code ?? '' }}</td>
                                            <td class="text-right">{{ money($result->amount_total,$result->currency->code ?? 'MXN',true) }}</td>
                                            <td class="text-right">
                                                <span id="txt_balance_{{$result->id}}">{{ money($result->balance,$result->currency->code ?? 'MXN',true) }}</span>
                                            </td>
                                            <td class="text-center" title="{{ $result->is_cancelable }}">{{ $result->status }}</td>
                                            <!-- Acciones -->
                                            <td class="text-center nowrap">
                                                {!! Form::open(['route' => ['cfdi-downloads.destroy', $result->id],'method' => 'DELETE','class' => 'hidden','role' => 'form','id' => 'form' . $result->id ]) !!}
                                                {!! Form::close() !!}
                                                <div class="btn-group btn-group-xs">
                                                    <button type="button" class="btn btn-default dropdown-toggle"
                                                            data-toggle="dropdown" data-toggle-position="left"
                                                            aria-expanded="false">
                                                        <i class="fa fa-ellipsis-h"></i>
                                                    </button>
                                                    <ul class="dropdown-menu dropdown-menu-right pull-right"
                                                        style="padding-top: 10px; padding-bottom: 10px;">
                                                        <li>
                                                            <a href="#" class="link-edit" data-id="{{$result->id}}" data-url="{{route('cfdi-downloads/modal-edit',['id' => $result->id])}}">
                                                                <i class="fa fa-pencil"></i> @lang('general.button_edit')
                                                            </a>
                                                        </li>
                                                        @if(!empty($result->file_xml))
                                                            <li>
                                                                <a class="" href="{{route('cfdi-downloads/download-xml',['cfdi_download' => $result->id])}}" title="{{__('general.button_download_xml')}}">
                                                                    <i class="fa fa-download"></i> {{__('general.button_download_xml')}}
                                                                </a>
                                                            </li>
                                                        @endif
                                                        @if(!empty($result->file_pdf))
                                                            <li>
                                                                <a class="" href="{{route('cfdi-downloads/download-pdf',['cfdi_download' => $result->id])}}" title="{{__('general.button_download_pdf')}}" target="_blank">
                                                                    <i class="fa fa-download"></i> {{__('general.button_download_pdf')}}
                                                                </a>
                                                            </li>
                                                        @endif
                                                        @if(!empty($result->file_acuse))
                                                            <li>
                                                                <a class="" href="{{route('cfdi-downloads/download-acuse',['cfdi_download' => $result->id])}}" title="{{__('general.button_download_acuse')}}" target="_blank">
                                                                    <i class="fa fa-download"></i> {{__('general.button_download_acuse')}}
                                                                </a>
                                                            </li>
                                                        @endif
                                                        <li>
                                                            <a href="#" class="" onclick="$('#form{{$result->id}}').submit();">
                                                                <i class="fa fa-trash-o"></i> @lang('general.button_delete')
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a href="#" class="link-payments" data-id="{{$result->id}}" data-url="{{route('cfdi-downloads/modal-payments',['id' => $result->id])}}">
                                                                <i class="fa fa-money"></i> @lang('general.button_payments')
                                                            </a>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="16" class="text-center">@lang('general.text_no_results')</td>
                                        </tr>
                                    @endforelse
                                    </tbody>
                                </table>
                            </div>
                            <!-- /Datos -->
                            <div class="ln_solid"></div>
                            <!-- Pie de pagina -->
                            <div class="row">
                                @if($results->total() > 0)
                                    <div class="col-md-5 col-xs-12 text-left hidden-xs">
                                    <span class="btn btn-sm btn-default">{{ $results->firstItem() }}
                                        - {{ $results->lastItem() }} @lang('general.text_of') {{ $results->total() }}</span>
                                    </div>
                                    <div class="col-md-7 col-xs-12 text-right">
                                        {{ $results->appends(request()->except('page'))->links() }}
                                    </div>
                                @endif
                            </div>
                            <!-- /Pie de pagina -->
                        </div><!-- /x_content -->
                    </div><!-- /x_panel -->
                </div>
            </div><!-- /Contenido -->

        </div>
    </div><!-- /page content -->
@endsection
@section('scripts_specific')
    <script src="{{ asset('gentelella/plugins/bootstrap-daterangepicker/daterangepicker.js') }}"></script>
    <script src="{{ asset('gentelella/plugins/bootstrap-wysiwyg/js/bootstrap-wysiwyg.min.js') }}"></script>
    <script src="{{ asset('gentelella/plugins/jquery.hotkeys/jquery.hotkeys.js') }}"></script>
    <script src="{{ asset('gentelella/plugins/google-code-prettify/src/prettify.js') }}"></script>
@endsection
@section('scripts')
    <script type="text/javascript">

        $(function () {
            /*Configura datepicker*/
            moment.locale("{{ substr(app()->getLocale(),0,2) }}");
            $("#form input[name='filter_date_from']").daterangepicker({
                singleDatePicker: true,
                showDropdowns: true,
                locale: {
                    format: "{{ setting('date_picker_format','DD-MM-YYYY') }}"
                },
                autoUpdateInput: false
            }, function (chosen_date) {
                $("#form input[name='filter_date_from']").val(chosen_date.format("{{ setting('date_picker_format','DD-MM-YYYY') }}"));
            });
            $("#form input[name='filter_date_to']").daterangepicker({
                singleDatePicker: true,
                showDropdowns: true,
                locale: {
                    format: "{{ setting('date_picker_format','DD-MM-YYYY') }}"
                },
                autoUpdateInput: false,
            }, function (chosen_date) {
                $("#form input[name='filter_date_to']").val(chosen_date.format("{{ setting('date_picker_format','DD-MM-YYYY') }}"));
            });

            /*Modal para editar*/
            $(".link-edit").on("click", function () {
                let id = $(this).attr('data-id');
                let url = $(this).attr('data-url');
                if (id && url) {
                    $.ajax({
                        url: url,
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id ,
                        success: function (data) {
                            $("#modals").html(data.html);
                            $("#modal_cfdi_download_edit").modal("show");
                        },
                        error: function (error, textStatus, errorThrown) {
                            if (error.status == 422) {
                                var message = error.responseJSON.error;
                                $("#general_messages").html(alertMessage("danger", message));
                            } else if (error.status == 403 || error.status == 401) {
                                location.href = "{{ route('login') }}";
                            } else {
                                alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                            }
                        }
                    });
                }
            });

            /*Submit para editar*/
            $(document).on("submit", '#form_modal_cfdi_download_edit', function (e) {
                e.preventDefault();
                $.ajax({
                    url: $(this).attr('action'),
                    type: "POST",
                    dataType: "JSON",
                    data: $(this).serialize(),
                    success: function (data) {
                        $("#txt_expense_type_" + data.id).html(data.expense_type);
                        $("#modal_cfdi_download_edit").modal("hide");
                        $("#general_messages").html(alertMessage("success", data.msg_success));
                        $("div.alert").not(".alert-important").delay(40000).fadeOut(350);
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            let message = error.responseJSON.error;
                            $("#modal_general_messages").html(alertMessage("danger", message));
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });

            /*Modal para agregar gastos*/
            $(".btn-cfdi-download-expense-add").on("click", function (e) {
                e.preventDefault();
                $.ajax({
                    url: "{{route('cfdi-downloads/modal-create-expense')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "",
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_cfdi_download_expense_create").modal("show");
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            var message = error.responseJSON.error;
                            $("#general_messages").html(alertMessage("danger", message));
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });
            /*Alta de gasto*/
            $(document).on("submit", '#form_modal_cfdi_download_expense_create', function (e) {
                e.preventDefault();
                var form = $(this);
                form.find(".help-block").remove();
                form.find(".form-control").parent().removeClass("has-error");
                $.ajax({
                    url: "{{ route('cfdi-downloads/store-expense') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: $("#form_modal_cfdi_download_expense_create").serialize(),
                    success: function (data) {
                        if (data) {
                            $("#modal_cfdi_download_expense_create .modal-body").html(alertRichMessage('success', data.success));
                            $("#modal_cfdi_download_expense_create .modal-footer").remove();
                            $("#modal_cfdi_download_expense_create .modal-dialog").removeClass('modal-lg')
                            setTimeout(function () {
                                location.reload();
                            }, 2000);
                        }
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            let message = error.responseJSON.error;
                            //Si trae objecto con errores
                            if(typeof(message) === "object"){
                                $.each( message, function( key, value ) {
                                    form.find("[name='"+key+"']").after(messageSmallHelpBlock(value)).parent().addClass("has-error");
                                });
                            }else{
                                $("#form_modal_cfdi_download_expense_create #modal_general_messages").html(alertMessage("danger", message));
                            }
                            setTimeout(function () {
                                $("#form_modal_cfdi_download_expense_create #modal_general_messages").html("");
                            }, 12000);
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });

            /*Modal para agregar ingresos*/
            $(".btn-cfdi-download-deposit-add").on("click", function (e) {
                e.preventDefault();
                $.ajax({
                    url: "{{route('cfdi-downloads/modal-create-deposit')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "",
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_cfdi_download_deposit_create").modal("show");
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            var message = error.responseJSON.error;
                            $("#general_messages").html(alertMessage("danger", message));
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });
            /*Alta de gasto*/
            $(document).on("submit", '#form_modal_cfdi_download_deposit_create', function (e) {
                e.preventDefault();
                var form = $(this);
                form.find(".help-block").remove();
                form.find(".form-control").parent().removeClass("has-error");
                $.ajax({
                    url: "{{ route('cfdi-downloads/store-deposit') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: $("#form_modal_cfdi_download_deposit_create").serialize(),
                    success: function (data) {
                        if (data) {
                            $("#modal_cfdi_download_deposit_create .modal-body").html(alertRichMessage('success', data.success));
                            $("#modal_cfdi_download_deposit_create .modal-footer").remove();
                            $("#modal_cfdi_download_deposit_create .modal-dialog").removeClass('modal-lg')
                            setTimeout(function () {
                                location.reload();
                            }, 2000);
                        }
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            let message = error.responseJSON.error;
                            //Si trae objecto con errores
                            if(typeof(message) === "object"){
                                $.each( message, function( key, value ) {
                                    form.find("[name='"+key+"']").after(messageSmallHelpBlock(value)).parent().addClass("has-error");
                                });
                            }else{
                                $("#form_modal_cfdi_download_deposit_create #modal_general_messages").html(alertMessage("danger", message));
                            }
                            setTimeout(function () {
                                $("#form_modal_cfdi_download_deposit_create #modal_general_messages").html("");
                            }, 12000);
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });
            /*Modal para pagos*/
            $(".link-payments").on("click", function () {
                let id = $(this).attr('data-id');
                let url = $(this).attr('data-url');
                if (id && url) {
                    $.ajax({
                        url: url,
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id ,
                        success: function (data) {
                            $("#modals").html(data.html);
                            $("#modal_cfdi_download_payments").modal("show");
                        },
                        error: function (error, textStatus, errorThrown) {
                            if (error.status == 422) {
                                var message = error.responseJSON.error;
                                $("#general_messages").html(alertMessage("danger", message));
                            } else if (error.status == 403 || error.status == 401) {
                                location.href = "{{ route('login') }}";
                            } else {
                                alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                            }
                        }
                    });
                }
            });
            /*Alta de pagos*/
            $(document).on("submit", '#form_modal_cfdi_download_payments', function (e) {
                e.preventDefault();
                var form = $(this);
                form.find(".help-block").remove();
                form.find(".form-control").parent().removeClass("has-error");
                $.ajax({
                    url: "{{ route('cfdi-downloads/store-payment') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: $("#form_modal_cfdi_download_payments").serialize(),
                    success: function (data) {
                        if (data) {
                            $("#form_modal_cfdi_download_payments #txt_amount_payment").html(data.amount_payment);
                            $("#form_modal_cfdi_download_payments #txt_balance").html(data.balance);
                            $("#txt_balance_" + $("#form_modal_cfdi_download_payments input[name='cfdi_download_id']").val()).html(data.balance);
                            $("#form_modal_cfdi_download_payments #modal_general_messages").html(alertMessage("success", data.success));
                            $("#form_modal_cfdi_download_payments input[name='amount_payment']").val('');
                            setTimeout(function () {
                                $("#form_modal_cfdi_download_payments #modal_general_messages").html("");
                            }, 3000);

                            //
                            $("#form_modal_cfdi_download_payments #payments tbody").html("");
                            $.ajax({
                                url: "{{route('cfdi-downloads/payments')}}",
                                type: "GET",
                                dataType: "JSON",
                                data: "id=" + $("#form_modal_cfdi_download_payments input[name='cfdi_download_id']").val(),
                                success: function (data) {
                                    $("#form_modal_cfdi_download_payments #payments tbody").html(data.html);
                                },
                                error: function (error, textStatus, errorThrown) {
                                    if (error.status == 422) {
                                        var message = error.responseJSON.error;
                                        $("#form_modal_cfdi_download_payments #modal_general_messages").html(alertMessage("danger", message));
                                    } else if (error.status == 403 || error.status == 401) {
                                        location.href = "{{ route('login') }}";
                                    } else {
                                        alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                                    }
                                }
                            });
                        }
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            let message = error.responseJSON.error;
                            //Si trae objecto con errores
                            if(typeof(message) === "object"){
                                $.each( message, function( key, value ) {
                                    form.find("[name='"+key+"']").after(messageSmallHelpBlock(value)).parent().addClass("has-error");
                                });
                            }else{
                                $("#form_modal_cfdi_download_payments #modal_general_messages").html(alertMessage("danger", message));
                            }
                            setTimeout(function () {
                                $("#form_modal_cfdi_download_payments #modal_general_messages").html("");
                            }, 12000);
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });
            /*Modal para editar*/
            $("#btn_edit_selected").on("click", function (e) {
                e.preventDefault();
                $.ajax({
                    url: "{{route('cfdi-downloads/modal-edit-selected')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "",
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_cfdi_download_edit_selected").modal("show");

                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            var message = error.responseJSON.error;
                            $("#general_messages").html(alertMessage("danger", message));
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });
            /*Editar seleccioandos*/
            $(document).on("submit", '#form_modal_cfdi_download_edit_selected', function (e) {
                e.preventDefault();
                var form = $(this);
                form.find(".help-block").remove();
                form.find(".form-control").parent().removeClass("has-error");
                //alert(JSON.stringify($("input[name='selected\[\]']:checked").val()));
                $.ajax({
                    url: "{{ route('cfdi-downloads/update-selected') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: $("#form_modal_cfdi_download_edit_selected").serialize() + "&" + $("input[name='selected\[\]']:checked").serialize(),
                    success: function (data) {
                        if (data.msg_success) {
                            $("#modal_cfdi_download_edit_selected .modal-body").html(alertRichMessage('success', data.msg_success));
                            $("#modal_cfdi_download_edit_selected .modal-footer").remove();
                            $("#modal_cfdi_download_edit_selected .modal-dialog").removeClass('modal-lg')
                            //Actualizamos datos visibles

                            setTimeout(function () {
                                location.reload();
                            }, 2000);
                        }else{
                            $("#modal_cfdi_download_edit_selected").modal("hide");
                        }
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            let message = error.responseJSON.error;
                            //Si trae objecto con errores
                            if(typeof(message) === "object"){
                                $.each( message, function( key, value ) {
                                    form.find("[name='"+key+"']").after(messageSmallHelpBlock(value)).parent().addClass("has-error");
                                });
                            }else{
                                $("#form_modal_cfdi_download_edit_selected #modal_general_messages").html(alertMessage("danger", message));
                            }
                            setTimeout(function () {
                                $("#form_modal_cfdi_download_edit_selected #modal_general_messages").html("");
                            }, 12000);
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });
            $("#btn_delete_selected").on("click", function (e) {
                e.preventDefault();
                if(confirm("{{__('general.text_confirm')}}")){
                    $.ajax({
                        url: "{{ route('cfdi-downloads/delete-selected') }}",
                        type: "POST",
                        dataType: "JSON",
                        data: $("input[name='selected\[\]']:checked").serialize(),
                        success: function (data) {
                            $("#general_messages").html(alertMessage("success", data.msg_success));
                            setTimeout(function () {
                                $("#btn_search").trigger("click");
                            }, 2000);
                        },
                        error: function (error, textStatus, errorThrown) {
                            if (error.status == 422) {
                                var message = error.responseJSON.error;
                                $("#general_messages").html(alertMessage("danger", message));
                            } else if (error.status == 403 || error.status == 401) {
                                location.href = "{{ route('login') }}";
                            } else {
                                alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                            }
                        }
                    });
                }
            });
        });

    </script>
@endsection
