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

@endsection
@section('title',config('app.name') . ' | ' . __('sales/customer_foreign_trade.document_title'))
@section('css_specific')
    <link href="{{ asset('gentelella/plugins/bootstrap-daterangepicker/daterangepicker.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('sales/customer_foreign_trade.document_title')</h3>
                </div>
                <div class="title_right text-right">
                    <div class="row">
                        <div class="col-md-5 col-xs-12 pull-right">
                            <a href="{{route('customer-foreign-trades.index',request()->except('page'))}}"
                               class="btn btn-sm btn-default">@lang('general.button_discard')
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <!-- /Titulo -->

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

            <!-- Mensajes -->
            <div id="general_messages">
                @include('flash::message')
                @if (!$errors->isEmpty())
                    <div class="alert alert-danger alert-dismissable alert-important" role="alert">
                        <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
                        {{ __('general.error_form') }}
                    </div>
                @endif
            </div>
            <!-- /Mensajes -->

            <!-- Contenido -->
            <div class="row">
                <div class="col-md-12 col-xs-12">
                    <div class="x_panel">
                        <div class="x_title">
                            <h2>@lang('general.text_add')</h2>
                            <div class="clearfix"></div>
                        </div>
                        <div class="x_content">
                            {!! Form::open(['route' => 'customer-foreign-trades.store','method' => 'POST','class' => '','role' => 'form','id'=>'form']) !!}
                            <!-- input hidden -->
                            {!! Form::hidden('amount_total_tmp', old('amount_total_tmp',0)) !!}
                            <!-- /.input hidden -->
                            <div class="row">
                                @if($tax_regimens->isNotEmpty())
                                    <div class="col-md-3 col-xs-12">
                                        <div class="form-group form-group-sm{{ $errors->has('tax_regimen_id') ? ' has-error' : '' }}">
                                            {!! html_entity_decode(Form::label('tax_regimen_id', __('sales/customer_foreign_trade.entry_tax_regimen_id') . '', ['class' => 'control-label'])) !!}
                                            {!! Form::select('tax_regimen_id', $tax_regimens,old('tax_regimen_id',\App\Helpers\Helper::defaultCompany()->tax_regimen_id), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                            @if ($errors->has('tax_regimen_id'))
                                                <span class="help-block"><small>{{ $errors->first('tax_regimen_id') }}</small></span>
                                            @endif
                                        </div>
                                    </div>
                                @endif
                            </div>
                            <div class="row">
                                <div class="col-md-6 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('customer_id') ? ' has-error' : '' }}">
                                        @php
                                            $tmp_customers = [];
                                            if(!empty(old('customer_id'))){
                                                $tmp_customers = \App\Models\Sales\Customer::where('id','=',old('customer_id'))->get()->pluck('text_select2','id');
                                            }
                                        @endphp
                                        {!! html_entity_decode(Form::label('customer_id', __('sales/customer_foreign_trade.entry_customer_id')  . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        <div class="input-group input-group-sm">
                                            {!! Form::select('customer_id', $tmp_customers,old('customer_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required','autofocus']) !!}
                                            <span class="input-group-btn">
                                                <button type="button" class="btn btn-info btn-customer-search"><i class="fa fa-search"></i></button>
                                                <button type="button" class="btn btn-info btn-customer-add"><i class="fa fa-plus"></i></button>
                                            </span>
                                        </div>
                                        @if ($errors->has('customer_id'))
                                            <span class="help-block"><small>{{ $errors->first('customer_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('tax_regimen_customer_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('tax_regimen_customer_id', __('sales/customer_foreign_trade.entry_tax_regimen_customer_id') . '', ['class' => 'control-label'])) !!}
                                        {!! Form::select('tax_regimen_customer_id', $tax_regimen_customers,old('tax_regimen_customer_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                        @if ($errors->has('tax_regimen_customer_id'))
                                            <span class="help-block"><small>{{ $errors->first('tax_regimen_customer_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('branch_office_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('branch_office_id', __('sales/customer_foreign_trade.entry_branch_office_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::select('branch_office_id', $branch_offices,old('branch_office_id',\App\Models\Base\BranchOffice::where('company_id','=',\App\Helpers\Helper::defaultCompany()->id)->get()->first()->id), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                        @if ($errors->has('branch_office_id'))
                                            <span class="help-block"><small>{{ $errors->first('branch_office_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-2 col-xs-7">
                                    <div class="form-group form-group-sm{{ $errors->has('currency_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('currency_id', __('sales/customer_foreign_trade.entry_currency_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::select('currency_id', $currencies,old('currency_id',\App\Models\Catalogs\Currency::first()->id), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                        @if ($errors->has('currency_id'))
                                            <span class="help-block"><small>{{ $errors->first('currency_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-1 col-xs-5">
                                    <div class="form-group form-group-sm{{ $errors->has('currency_value') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('currency_value', __('sales/customer_foreign_trade.entry_currency_value') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::number('currency_value', old('currency_value'), ['class' => 'form-control text-center', 'placeholder' => __('sales/customer_foreign_trade.entry_currency_value'),'required','step' => 'any']) !!}
                                        @if ($errors->has('currency_value'))
                                            <span class="help-block"><small>{{ $errors->first('currency_value') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('date') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('date', __('sales/customer_foreign_trade.entry_date') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        <div class="input-group input-group-sm">
                                            {!! Form::text('date', old('date',\App\Helpers\Helper::dateTime(Date::now())), ['class' => 'form-control', 'placeholder' => __('sales/customer_foreign_trade.entry_date'),'required','autocomplete'=>'off']) !!}
                                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                        </div>
                                        @if ($errors->has('date'))
                                            <span class="help-block"><small>{{ $errors->first('date') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('payment_term_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('payment_term_id', __('sales/customer_foreign_trade.entry_payment_term_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::select('payment_term_id', $payment_terms,old('payment_term_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                        @if ($errors->has('payment_term_id'))
                                            <span class="help-block"><small>{{ $errors->first('payment_term_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('date_due') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('date_due', __('sales/customer_foreign_trade.entry_date_due') . '', ['class' => 'control-label'])) !!}
                                        <div class="input-group input-group-sm">
                                            {!! Form::text('date_due', old('date_due'), ['class' => 'form-control', 'placeholder' => __('sales/customer_foreign_trade.entry_date_due'),'autocomplete'=>'off']) !!}
                                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                        </div>
                                        @if ($errors->has('date_due'))
                                            <span class="help-block"><small>{{ $errors->first('date_due') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm">
                                        {!! html_entity_decode(Form::label('salesperson_id', __('sales/customer_foreign_trade.entry_salesperson_id') . '', ['class' => 'control-label'])) !!}
                                        {!! Form::select('salesperson_id', $salespersons,old('salesperson_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('payment_way_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('payment_way_id', __('sales/customer_foreign_trade.entry_payment_way_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::select('payment_way_id', $payment_ways,old('payment_way_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                        @if ($errors->has('payment_way_id'))
                                            <span class="help-block"><small>{{ $errors->first('payment_way_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('payment_method_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('payment_method_id', __('sales/customer_foreign_trade.entry_payment_method_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::select('payment_method_id', $payment_methods,old('payment_method_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                        @if ($errors->has('payment_method_id'))
                                            <span class="help-block"><small>{{ $errors->first('payment_method_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('cfdi_use_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('cfdi_use_id', __('sales/customer_foreign_trade.entry_cfdi_use_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::select('cfdi_use_id', $cfdi_uses,old('cfdi_use_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                        @if ($errors->has('cfdi_use_id'))
                                            <span class="help-block"><small>{{ $errors->first('cfdi_use_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12 hidden">
                                    <div class="form-group form-group-sm">
                                        {!! html_entity_decode(Form::label('reference', __('sales/customer_foreign_trade.entry_reference') . '', ['class' => 'control-label'])) !!}
                                        {!! Form::text('reference', old('reference'), ['class' => 'form-control', 'placeholder' => __('sales/customer_foreign_trade.entry_reference')]) !!}
                                    </div>
                                </div>
                                @if(!empty(setting('enabled_projects')))
                                    <div class="col-md-3 col-xs-12">
                                        <div class="form-group form-group-sm{{ $errors->has('project_id') ? ' has-error' : '' }}">
                                            {!! html_entity_decode(Form::label('project_id', __('sales/customer_foreign_trade.entry_project_id') . '', ['class' => 'control-label'])) !!}
                                            {!! Form::select('project_id', $projects,old('project_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                            @if ($errors->has('project_id'))
                                                <span class="help-block"><small>{{ $errors->first('project_id') }}</small></span>
                                            @endif
                                        </div>
                                    </div>
                                @endif
                            </div>
                            <div class="row">
                                <div class="col-md-12 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('item') ? ' has-error' : '' }}"
                                         style="margin-top: 20px;">
                                        @if ($errors->has('item'))
                                            <span class="help-block"><small>{{ $errors->first('item') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            <div class="" role="tabpanel" data-example-id="togglable-tabs">
                                <ul id="myTab" class="nav nav-tabs bar_tabs" role="tablist">
                                    <li role="presentation" class="active">
                                        <a href="#tab_products" id="products-tab" role="tab" data-toggle="tab"
                                           aria-expanded="true">@lang('sales/customer_foreign_trade.tab_products')</a>
                                    </li>
                                    <li role="presentation" class="">
                                        <a href="#tab_foreign_trades" id="foreign-trades-tab" role="tab" data-toggle="tab"
                                           aria-expanded="true">@lang('sales/customer_foreign_trade.tab_foreign_trades')</a>
                                    </li>
                                    <li role="presentation" class="">
                                        <a href="#tab_relations" id="relations-tab" role="tab"
                                           data-toggle="tab"
                                           aria-expanded="false">@lang('sales/customer_foreign_trade.tab_relations')</a>
                                    </li>
                                </ul>
                                <div id="myTabContent" class="tab-content">
                                    <div role="tabpanel" class="tab-pane fade active in" id="tab_products"
                                         aria-labelledby="products-tab">
                                        <div class="row">
                                            <div class="col-md-12 col-xs-12">
                                                <div class="table-responsive">
                                                    <table class="table table-items table-condensed table-hover table-bordered table-striped jambo_table"
                                                           id="items" style="min-width: 2000px;">
                                                        <thead>
                                                        <tr>
                                                            <th width="6%"
                                                                class="text-center">@lang('general.column_actions')</th>
                                                            <th width="7%"
                                                                class="text-center">@lang('sales/customer_foreign_trade.column_line_product_id')</th>
                                                            <th class="text-left">
                                                                @lang('sales/customer_foreign_trade.column_line_name')
                                                                <span class="required text-danger">*</span>
                                                            </th>
                                                            <th width="9%"
                                                                class="text-center">
                                                                @lang('sales/customer_foreign_trade.column_line_unit_measure_id')
                                                                <span class="required text-danger">*</span>
                                                            </th>
                                                            <th width="9%"
                                                                class="text-center">
                                                                @lang('sales/customer_foreign_trade.column_line_sat_product_id')
                                                                <span class="required text-danger">*</span>
                                                            </th>
                                                            <th width="3%"
                                                                class="text-center">
                                                                @lang('sales/customer_foreign_trade.column_line_quantity')<span class="required text-danger">*</span>
                                                            </th>
                                                            <th width="6%"
                                                                class="text-center">
                                                                @lang('sales/customer_foreign_trade.column_line_price_unit')
                                                                <span class="required text-danger">*</span>
                                                            </th>
                                                            <th width="4%"
                                                                class="text-center text-nowrap">@lang('sales/customer_foreign_trade.column_line_discount')</th>
                                                            <th width="9%"
                                                                class="text-center text-nowrap">@lang('sales/customer_foreign_trade.column_line_tariff_fraction_id')</th>
                                                            <th width="3%"
                                                                class="text-center text-nowrap">@lang('sales/customer_foreign_trade.column_line_customs_quantity')</th>
                                                            <th width="9%"
                                                                class="text-center text-nowrap">@lang('sales/customer_foreign_trade.column_line_uom_custom_id')</th>
                                                            <th width="5%"
                                                                class="text-center text-nowrap">@lang('sales/customer_foreign_trade.column_line_price_unit_usd')</th>
                                                            <th width="6%"
                                                                class="text-center">@lang('sales/customer_foreign_trade.column_line_taxes')</th>
                                                            <th width="5%" class="text-center">@lang('sales/customer_foreign_trade.column_line_tax_object')</th>
                                                            <th width="6%"
                                                                class="text-right">@lang('sales/customer_foreign_trade.column_line_amount_untaxed')</th>
                                                        </tr>
                                                        </thead>
                                                        <tbody>
                                                        <!-- Items -->
                                                        @php
                                                            $item_row = 1;
                                                            $items = (empty(old('item')) ? [] : old('item'));
                                                        @endphp
                                                        @foreach ($items as $item_row => $item)
                                                            @php
                                                                $tmp_products = [];
                                                                if(!empty(old('item.' . $item_row . '.product_id'))){
                                                                    $tmp_products = \App\Models\Catalogs\Product::where('id','=',old('item.' . $item_row . '.product_id'))->get()->pluck('text_select2','id');
                                                                }
                                                                $tmp_unit_measures = [];
                                                                if(!empty(old('item.' . $item_row . '.unit_measure_id'))){
                                                                    $tmp_unit_measures = \App\Models\Catalogs\UnitMeasure::where('id','=',old('item.' . $item_row . '.unit_measure_id'))->get()->pluck('description_select2','id');
                                                                }
                                                                $tmp_sat_products = [];
                                                                if(!empty(old('item.' . $item_row . '.sat_product_id'))){
                                                                    $tmp_sat_products = \App\Models\Catalogs\SatProduct::where('id','=',old('item.' . $item_row . '.sat_product_id'))->get()->pluck('description_select2','id');
                                                                }
                                                                $tmp_tariff_fractions = [];
                                                                if(!empty(old('item.' . $item_row . '.tariff_fraction_id'))){
                                                                    $tmp_tariff_fractions = \App\Models\Catalogs\TariffFraction::where('id','=',old('item.' . $item_row . '.tariff_fraction_id'))->get()->pluck('description_select2','id');
                                                                }
                                                                $tmp_uom_customs = [];
                                                                if(!empty(old('item.' . $item_row . '.uom_custom_id'))){
                                                                    $tmp_uom_customs = \App\Models\Catalogs\UomCustom::where('id','=',old('item.' . $item_row . '.uom_custom_id'))->get()->pluck('description_select2','id');
                                                                }
                                                            @endphp
                                                            <tr id="item_row_{{ $item_row }}">
                                                                <td class="text-center" style="vertical-align: middle;">
                                                                    <button type="button"
                                                                            onclick="$('#item_row_{{ $item_row }}').remove(); totalItem();"
                                                                            class="btn btn-xs btn-danger"
                                                                            style="margin-bottom: 0;">
                                                                        <i class="fa fa-trash-o"></i>
                                                                    </button>
                                                                    <!-- input hidden -->
                                                                    <input type="hidden" id="item_id_{{ $item_row }}"
                                                                           name="item[{{ $item_row }}][id]"
                                                                           value="{{ old('item.' . $item_row . '.id') }}">
                                                                    <!-- /.input hidden -->
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm">
                                                                        <div class="input-group input-group-sm">
                                                                        {!! Form::select('item[' . $item_row . '][product_id]', $tmp_products,old('item.' . $item_row . '.product_id'), ['class' => 'form-control input-small col-product-id', 'placeholder' => __('general.text_select'),'id' => 'item_product_id_' . $item_row,'data-row' => $item_row]) !!}
                                                                            <span class="input-group-btn">
                                                                                <button type="button" class="btn btn-info btn-product-search" data-row="{{ $item_row }}"><i class="fa fa-search"></i></button>
                                                                            </span>
                                                                        </div>
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm{{ $errors->has('item.'.$item_row.'.name') ? ' has-error' : '' }}">
                                                                        {!! Form::textarea('item[' . $item_row . '][name]', old('item.' . $item_row . '.name'), ['class' => 'form-control input-sm ym-auto-resize col-name-id', 'required','autocomplete'=>'off','id' => 'item_name_' . $item_row, 'placeholder' => __('sales/customer_foreign_trade.column_line_name'),'rows' => 2, 'maxlength' => 1000]) !!}
                                                                        @if ($errors->has('item.'.$item_row.'.name'))
                                                                            <span class="help-block"><small>{{ $errors->first('item.'.$item_row.'.name') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm{{ $errors->has('item.'.$item_row.'.unit_measure_id') ? ' has-error' : '' }}">
                                                                        <div class="input-group input-group-sm">
                                                                            {!! Form::select('item[' . $item_row . '][unit_measure_id]', $tmp_unit_measures,old('item.' . $item_row . '.unit_measure_id'), ['class' => 'form-control input-sm col-unit-measure-id', 'placeholder' => __('general.text_select'),'required','id' => 'item_unit_measure_id_' . $item_row]) !!}
                                                                            <span class="input-group-btn">
                                                                                <button type="button" class="btn btn-info btn-unit-measure-search" data-row="{{ $item_row }}"><i class="fa fa-search"></i></button>
                                                                            </span>
                                                                        </div>
                                                                        @if ($errors->has('item.'.$item_row.'.unit_measure_id'))
                                                                            <span class="help-block"><small>{{ $errors->first('item.'.$item_row.'.unit_measure_id') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm{{ $errors->has('item.'.$item_row.'.sat_product_id') ? ' has-error' : '' }}">
                                                                        <div class="input-group input-group-sm">
                                                                            {!! Form::select('item[' . $item_row . '][sat_product_id]', $tmp_sat_products,old('item.' . $item_row . '.sat_product_id'), ['class' => 'form-control input-sm col-sat-product-id', 'placeholder' => __('general.text_select'),'required','id' => 'item_sat_product_id_' . $item_row]) !!}
                                                                            <span class="input-group-btn">
                                                                                <button type="button" class="btn btn-info btn-sat-product-search" data-row="{{ $item_row }}"><i class="fa fa-search"></i></button>
                                                                            </span>
                                                                        </div>
                                                                        @if ($errors->has('item.'.$item_row.'.sat_product_id'))
                                                                            <span class="help-block"><small>{{ $errors->first('item.'.$item_row.'.sat_product_id') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm{{ $errors->has('item.'.$item_row.'.quantity') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item[' . $item_row . '][quantity]', old('item.' . $item_row . '.quantity'), ['class' => 'form-control input-sm text-right col-quantity', 'required','id' => 'item_quantity_' . $item_row, 'step' => 'any']) !!}
                                                                        @if ($errors->has('item.'.$item_row.'.quantity'))
                                                                            <span class="help-block"><small>{{ $errors->first('item.'.$item_row.'.quantity') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm{{ $errors->has('item.'.$item_row.'.price_unit') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item[' . $item_row . '][price_unit]', old('item.' . $item_row . '.price_unit'), ['class' => 'form-control input-sm text-right col-price-unit', 'required','id' => 'item_price_unit_' . $item_row, 'step' => 'any']) !!}
                                                                        <div class="checkbox" style="margin-top: 5px; margin-bottom: 5px; margin-left: 3px;">
                                                                            <label>
                                                                            {!! Form::checkbox('item[' . $item_row . '][includes_iva]', '1',(!empty(old('item.' . $item_row . '.includes_iva')) ? true : false), ['class' => 'col-includes-iva', 'id' => 'item_includes_iva_' . $item_row, 'style' => 'margin-top: 2px;']) !!} @lang('sales/customer_foreign_trade.text_includes_iva')
                                                                            </label>
                                                                        </div>
                                                                        @if ($errors->has('item.'.$item_row.'.price_unit'))
                                                                            <span class="help-block"><small>{{ $errors->first('item.'.$item_row.'.price_unit') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm{{ $errors->has('item.'.$item_row.'.discount') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item[' . $item_row . '][discount]', old('item.' . $item_row . '.discount'), ['class' => 'form-control input-sm text-center col-discount', 'id' => 'item_discount_' . $item_row, 'step' => 'any']) !!}
                                                                        @if ($errors->has('item.'.$item_row.'.discount'))
                                                                            <span class="help-block"><small>{{ $errors->first('item.'.$item_row.'.discount') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm{{ $errors->has('item.'.$item_row.'.tariff_fraction_id') ? ' has-error' : '' }}">
                                                                        <div class="input-group input-group-sm">
                                                                            {!! Form::select('item[' . $item_row . '][tariff_fraction_id]', $tmp_tariff_fractions,old('item.' . $item_row . '.tariff_fraction_id'), ['class' => 'form-control input-sm col-tariff-fraction-id', 'placeholder' => __('general.text_select'),'id' => 'item_tariff_fraction_id_' . $item_row]) !!}
                                                                            <span class="input-group-btn">
                                                                                <button type="button" class="btn btn-info btn-tariff-fraction-search" data-row="{{ $item_row }}"><i class="fa fa-search"></i></button>
                                                                            </span>
                                                                        </div>
                                                                        @if ($errors->has('item.'.$item_row.'.tariff_fraction_id'))
                                                                            <span class="help-block"><small>{{ $errors->first('item.'.$item_row.'.tariff_fraction_id') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm{{ $errors->has('item.'.$item_row.'.customs_quantity') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item[' . $item_row . '][customs_quantity]', old('item.' . $item_row . '.customs_quantity'), ['class' => 'form-control input-sm text-right col-customs-quantity','id' => 'item_customs_quantity_' . $item_row, 'step' => 'any']) !!}
                                                                        @if ($errors->has('item.'.$item_row.'.customs_quantity'))
                                                                            <span class="help-block"><small>{{ $errors->first('item.'.$item_row.'.customs_quantity') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm{{ $errors->has('item.'.$item_row.'.uom_custom_id') ? ' has-error' : '' }}">
                                                                        <div class="input-group input-group-sm">
                                                                            {!! Form::select('item[' . $item_row . '][uom_custom_id]', $tmp_uom_customs,old('item.' . $item_row . '.uom_custom_id'), ['class' => 'form-control input-sm col-uom-custom-id', 'placeholder' => __('general.text_select'),'id' => 'item_uom_custom_id_' . $item_row]) !!}
                                                                            <span class="input-group-btn">
                                                                                <button type="button" class="btn btn-info btn-uom-custom-search" data-row="{{ $item_row }}"><i class="fa fa-search"></i></button>
                                                                            </span>
                                                                        </div>
                                                                        @if ($errors->has('item.'.$item_row.'.uom_custom_id'))
                                                                            <span class="help-block"><small>{{ $errors->first('item.'.$item_row.'.uom_custom_id') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm{{ $errors->has('item.'.$item_row.'.price_unit_usd') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item[' . $item_row . '][price_unit_usd]', old('item.' . $item_row . '.price_unit_usd'), ['class' => 'form-control input-sm text-right col-price-unit-usd','id' => 'item_price_unit_usd_' . $item_row, 'step' => 'any']) !!}
                                                                        @if ($errors->has('item.'.$item_row.'.price_unit_usd'))
                                                                            <span class="help-block"><small>{{ $errors->first('item.'.$item_row.'.price_unit_usd') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm">
                                                                        {!! Form::select('item[' . $item_row . '][taxes][]', $taxes,old('item.' . $item_row . '.taxes'), ['class' => 'form-control input-sm my-select2 col-taxes','multiple','id' => 'item_taxes_' . $item_row]) !!}
                                                                    </div>
                                                                </td>
                                                                <td>
                                                                    <div class="form-group form-group-sm">
                                                                        {!! Form::select('item[' . $item_row . '][tax_object]', $tax_objects,old('item.' . $item_row . '.tax_object',$item->tax_object ?? ''), ['class' => 'form-control input-sm col-tax-object','id' => 'item_tax_object_' . $item_row]) !!}
                                                                    </div>
                                                                </td>
                                                                <td class="text-right" style="padding-top: 11px;">
                                                                    <span id="item_txt_amount_untaxed_{{ $item_row }}">0</span>
                                                                </td>
                                                            </tr>
                                                        @endforeach
                                                        @php
                                                            $item_row++;
                                                        @endphp
                                                        <!-- /Items -->
                                                        <!-- Agregar nuevo item -->
                                                        <tr id="add_item">
                                                            <td class="text-center">
                                                                <button type="button" onclick="addItem();"
                                                                        class="btn btn-xs btn-primary"
                                                                        style="margin-bottom: 0;">
                                                                    <i class="fa fa-plus"></i>
                                                                </button>
                                                            </td>
                                                            <td class="text-right" colspan="14"></td>
                                                        </tr>
                                                        <!-- Totales -->
                                                        <tr>
                                                            <td></td>
                                                            <td class="text-right" colspan="12" rowspan="3"
                                                                style="vertical-align: middle">
                                                                {!! Form::textarea('comment', old('comment'), ['class' => 'form-control input-sm ym-auto-resize', 'placeholder' => __('sales/customer_foreign_trade.entry_comment'),'rows' => '3']) !!}
                                                            </td>
                                                            <td class="text-right">
                                                                <strong>@lang('general.text_amount_untaxed')</strong>
                                                            </td>
                                                            <td class="text-right"><span id="txt_amount_untaxed">0</span>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td></td>
                                                            <td class="text-right">
                                                                <strong id="txt_amount_tax_label"></strong>
                                                            </td>
                                                            <td class="text-right">
                                                                <span id="txt_amount_tax"></span>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td></td>
                                                            <td class="text-right">
                                                                <strong>@lang('general.text_amount_total')</strong></td>
                                                            <td class="text-right"><span id="txt_amount_total">0</span></td>
                                                        </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div role="tabpanel" class="tab-pane fade" id="tab_foreign_trades"
                                         aria-labelledby="foreign-trades-tab">
                                        <div class="row">
                                            <div class="col-md-3 col-xs-5">
                                                <div class="form-group form-group-sm{{ $errors->has('exchange_rate_usd') ? ' has-error' : '' }}">
                                                    {!! html_entity_decode(Form::label('exchange_rate_usd', __('sales/customer_foreign_trade.entry_exchange_rate_usd') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                                    {!! Form::number('exchange_rate_usd', old('exchange_rate_usd'), ['class' => 'form-control text-center', 'placeholder' => __('sales/customer_foreign_trade.entry_exchange_rate_usd'),'required','step' => 'any']) !!}
                                                    @if ($errors->has('exchange_rate_usd'))
                                                        <span class="help-block"><small>{{ $errors->first('exchange_rate_usd') }}</small></span>
                                                    @endif
                                                </div>
                                            </div>
                                            <div class="col-md-3 col-xs-12">
                                                <div class="form-group form-group-sm{{ $errors->has('operation_type_id') ? ' has-error' : '' }}">
                                                    {!! html_entity_decode(Form::label('operation_type_id', __('sales/customer_foreign_trade.entry_operation_type_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                                    {!! Form::select('operation_type_id', $operation_types,old('operation_type_id',\App\Models\Catalogs\OperationType::first()->id), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                                    @if ($errors->has('operation_type_id'))
                                                        <span class="help-block"><small>{{ $errors->first('operation_type_id') }}</small></span>
                                                    @endif
                                                </div>
                                            </div>
                                            <div class="col-md-3 col-xs-12">
                                                <div class="form-group form-group-sm{{ $errors->has('pediment_id') ? ' has-error' : '' }}">
                                                    {!! html_entity_decode(Form::label('pediment_id', __('sales/customer_foreign_trade.entry_pediment_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                                    {!! Form::select('pediment_id', $pediments,old('pediment_id',\App\Models\Catalogs\Pediment::first()->id), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                                    @if ($errors->has('pediment_id'))
                                                        <span class="help-block"><small>{{ $errors->first('pediment_id') }}</small></span>
                                                    @endif
                                                </div>
                                            </div>
                                            <div class="col-md-3 col-xs-12">
                                                <div class="form-group form-group-sm">
                                                    {!! html_entity_decode(Form::label('reliable_exporter_number', __('sales/customer_foreign_trade.entry_reliable_exporter_number') . '', ['class' => 'control-label'])) !!}
                                                    {!! Form::text('reliable_exporter_number', old('reliable_exporter_number'), ['class' => 'form-control', 'placeholder' => __('sales/customer_foreign_trade.entry_reliable_exporter_number')]) !!}
                                                </div>
                                            </div>
                                            <div class="col-md-3 col-xs-12">
                                                <div class="form-group form-group-sm{{ $errors->has('incoterm_id') ? ' has-error' : '' }}">
                                                    {!! html_entity_decode(Form::label('incoterm_id', __('sales/customer_foreign_trade.entry_incoterm_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                                    {!! Form::select('incoterm_id', $incoterms,old('incoterm_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                                    @if ($errors->has('incoterm_id'))
                                                        <span class="help-block"><small>{{ $errors->first('incoterm_id') }}</small></span>
                                                    @endif
                                                </div>
                                            </div>
                                            <div class="col-md-3 col-xs-12">
                                                <div class="form-group form-group-sm{{ $errors->has('origin_certificate') ? ' has-error' : '' }}">
                                                    {!! html_entity_decode(Form::label('origin_certificate', __('sales/customer_foreign_trade.entry_origin_certificate') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                                    {!! Form::select('origin_certificate', $list_origin_certificates,old('origin_certificate','0'), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                                    @if ($errors->has('origin_certificate'))
                                                        <span class="help-block"><small>{{ $errors->first('origin_certificate') }}</small></span>
                                                    @endif
                                                </div>
                                            </div>
                                            <div class="col-md-6 col-xs-12">
                                                <div class="form-group form-group-sm">
                                                    {!! html_entity_decode(Form::label('number_origin_certificate', __('sales/customer_foreign_trade.entry_number_origin_certificate') . '', ['class' => 'control-label'])) !!}
                                                    {!! Form::text('number_origin_certificate', old('number_origin_certificate'), ['class' => 'form-control', 'placeholder' => __('sales/customer_foreign_trade.entry_number_origin_certificate')]) !!}
                                                </div>
                                            </div>
                                            <div class="col-md-12 col-xs-12">
                                                <div class="form-group form-group-sm">
                                                    {!! html_entity_decode(Form::label('comment_foreign_trade', __('sales/customer_foreign_trade.entry_comment_foreign_trade') . '', ['class' => 'control-label'])) !!}
                                                    {!! Form::textarea('comment_foreign_trade', old('comment_foreign_trade'), ['class' => 'form-control', 'placeholder' => __('sales/customer_foreign_trade.entry_comment_foreign_trade'),'rows' => 3]) !!}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div role="tabpanel" class="tab-pane fade" id="tab_relations"
                                         aria-labelledby="relations-tab">
                                        <div class="row">
                                            <div class="col-md-4 col-xs-12">
                                                <div class="form-group form-group-sm{{ $errors->has('cfdi_relation_id') ? ' has-error' : '' }}">
                                                    {!! html_entity_decode(Form::label('cfdi_relation_id', __('sales/customer_foreign_trade.entry_cfdi_relation_id') . ' ', ['class' => 'control-label'])) !!}
                                                    {!! Form::select('cfdi_relation_id', $cfdi_relations,old('cfdi_relation_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                                    @if ($errors->has('cfdi_relation_id'))
                                                        <span class="help-block"><small>{{ $errors->first('cfdi_relation_id') }}</small></span>
                                                    @endif
                                                </div>
                                            </div>
                                            <div class="col-md-12 col-xs-12">
                                                <div class="table-responsive">
                                                    <table class="table table-items table-condensed table-hover table-bordered table-striped"
                                                           id="items_relation">
                                                        <thead>
                                                        <tr>
                                                            <th width="5%"
                                                                class="text-center">@lang('general.column_actions')</th>
                                                            <th width="25%"
                                                                class="text-center">
                                                                @lang('sales/customer_foreign_trade.column_relation_relation_id')
                                                            </th>
                                                            <th width="65%"
                                                                class="text-center">@lang('sales/customer_foreign_trade.column_relation_uuid')</th>
                                                        </tr>
                                                        </thead>
                                                        <tbody>
                                                        <!-- Items -->
                                                        @php
                                                            $item_relation_row = 1;
                                                            $items_relation = old('item_relation',[]);
                                                        @endphp
                                                        @foreach ($items_relation as $item_relation_row => $item)
                                                            @php
                                                                $tmp_customer_foreign_trade_relations = [];
                                                                if(!empty(old('item_relation.' . $item_relation_row . '.relation_id'))){
                                                                    $tmp = \App\Models\Sales\CustomerInvoice::find(old('item_relation.' . $item_relation_row . '.relation_id'));
                                                                    $tmp_customer_foreign_trade_relations = $tmp->get()->pluck('text_select2','id');
                                                                }
                                                            @endphp
                                                            <tr id="item_relation_row_{{ $item_relation_row }}">
                                                                <td class="text-center"
                                                                    style="vertical-align: middle;">
                                                                    <button type="button"
                                                                            onclick="$('#item_relation_row_{{ $item_relation_row }}').remove();"
                                                                            class="btn btn-xs btn-danger"
                                                                            style="margin-bottom: 0;">
                                                                        <i class="fa fa-trash-o"></i>
                                                                    </button>
                                                                    <!-- input hidden -->
                                                                    <input type="hidden"
                                                                           id="item_relation_id_{{ $item_relation_row }}"
                                                                           name="item_relation[{{ $item_relation_row }}][id]"
                                                                           value="{{ old('item_relation.' . $item_relation_row . '.id') }}">
                                                                    <!-- /.input hidden -->
                                                                </td>
                                                                <td class="text-center align-middle">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_relation.'.$item_relation_row.'.relation_id') ? ' has-error' : '' }}">
                                                                        {!! Form::select('item_relation[' . $item_relation_row . '][relation_id]', $tmp_customer_foreign_trade_relations,old('item_relation.' . $item_relation_row . '.relation_id'), ['class' => 'form-control input-sm col-relation-id', 'placeholder' => __('general.text_select'),'id' => 'item_relation_relation_id_' . $item_relation_row,'data-row' => $item_relation_row]) !!}
                                                                        @if ($errors->has('item_relation.'.$item_relation_row.'.relation_id'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_relation.'.$item_relation_row.'.relation_id') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td class="text-center align-middle">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_relation.'.$item_relation_row.'.uuid_related') ? ' has-error' : '' }}">
                                                                        {!! Form::text('item_relation[' . $item_relation_row . '][uuid_related]',old('item_relation.' . $item_relation_row . '.uuid_related'), ['class' => 'form-control text-center input-sm col-uuid-related','required','id' => 'item_relation_uuid_related_' . $item_relation_row,'data-row' => $item_relation_row]) !!}
                                                                        @if ($errors->has('item_relation.'.$item_relation_row.'.uuid_related'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_relation.'.$item_relation_row.'.uuid_related') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                        @endforeach
                                                        @php
                                                            $item_relation_row++;
                                                        @endphp
                                                        <!-- /Items -->
                                                        <!-- Agregar nuevo item -->
                                                        <tr id="add_item_relation">
                                                            <td class="text-center">
                                                                <button type="button"
                                                                        onclick="addItemCfdiRelation();"
                                                                        class="btn btn-xs btn-primary"
                                                                        style="margin-bottom: 0;">
                                                                    <i class="fa fa-plus"></i>
                                                                </button>
                                                            </td>
                                                            <td class="text-right" colspan="2"></td>
                                                        </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Footer form -->
                            <div class="ln_solid"></div>
                            <div class="row">
                                <div class="col-md-12 col-xs-12 text-right footer-form">
                                    {!! Form::button(__('general.button_pre_invoice'),['type' => 'submit', 'class' => 'btn btn-sm btn-info ladda-button','name' => 'pre_invoice', 'value' => '1']) !!}
                                    &nbsp;&nbsp;
                                    {!! Form::button(__('general.button_invoice'),['type' => 'submit', 'class' => 'btn btn-sm btn-primary ladda-button']) !!}
                                    &nbsp;&nbsp;
                                    <a href="{{route('customer-foreign-trades.index',request()->except('page'))}}"
                                       class="btn btn-sm btn-default">@lang('general.button_discard')</a>
                                </div>
                            </div>
                            <!-- /Footer form -->
                            {!! Form::close() !!}
                        </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>
@endsection
@section('scripts')
    <script type="text/javascript">
        var item_row = "{{ $item_row }}";
        var item_relation_row = "{{ $item_relation_row }}";


        function addItem() {
            var html = '';

            html += '<tr id="item_row_' + item_row + '">';
            html += '<td class="text-center" style="vertical-align: middle;">';
            html += '<button type="button" onclick="$(\'#item_row_' + item_row + '\').remove(); totalItem();" class="btn btn-xs btn-danger" style="margin-bottom: 0;">';
            html += '<i class="fa fa-trash"></i>';
            html += '</button>';
            html += '<input type="hidden" name="item[' + item_row + '][id]" id="item_id_' + item_row + '" /> ';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<div class="input-group input-group-sm">';
            html += '<select class="form-control input-sm col-product-id" name="item[' + item_row + '][product_id]" id="item_product_id_' + item_row + '" data-row="' + item_row + '">';
            html += '<option selected="selected" value="">@lang('general.text_select')</option>';
            html += '</select>';
            html += '<span class="input-group-btn">';
            html += '<button type="button" class="btn btn-info btn-product-search" data-row="' + item_row + '"><i class="fa fa-search"></i></button>';
            html += '</span>';
            html += '</div>';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<textarea class="form-control input-sm col-name-id ym-auto-resize" name="item[' + item_row + '][name]" id="item_name_' + item_row + '" placeholder="{{__('sales/customer_foreign_trade.column_line_name')}}" required rows="2" autocomplete="off" maxlength="1000" />';
            html += '</textarea>';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<div class="input-group input-group-sm">';
            html += '<select class="form-control input-sm col-unit-measure-id" name="item[' + item_row + '][unit_measure_id]" id="item_unit_measure_id_' + item_row + '" required>';
            html += '<option selected="selected" value="">@lang('general.text_select')</option>';
            html += '</select>';
            html += '<span class="input-group-btn">';
            html += '<button type="button" class="btn btn-info btn-unit-measure-search" data-row="' + item_row + '"><i class="fa fa-search"></i></button>';
            html += '</span>';
            html += '</div>';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<div class="input-group input-group-sm">';
            html += '<select class="form-control input-sm col-sat-product-id" name="item[' + item_row + '][sat_product_id]" id="item_sat_product_id_' + item_row + '" required>';
            html += '<option selected="selected" value="">@lang('general.text_select')</option>';
            html += '</select>';
            html += '<span class="input-group-btn">';
            html += '<button type="button" class="btn btn-info btn-sat-product-search" data-row="' + item_row + '"><i class="fa fa-search"></i></button>';
            html += '</span>';
            html += '</div>';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-right col-quantity" name="item[' + item_row + '][quantity]" id="item_quantity_' + item_row + '" required step="any" />';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-right col-price-unit" name="item[' + item_row + '][price_unit]" id="item_price_unit_' + item_row + '" required step="any" />';
            html += '<div class="checkbox" style="margin-top: 5px; margin-bottom: 5px; margin-left: 3px;">';
            html += '<label>';
            html += '<input type="checkbox" class="col-includes-iva" name="item[' + item_row + '][includes_iva]" id="item_includes_iva_' + item_row + '" value="1" style="margin-top: 2px;"> @lang('sales/customer_foreign_trade.text_includes_iva')';
            html += '</label>';
            html += '</div>';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-center col-discount" name="item[' + item_row + '][discount]" id="item_discount_' + item_row + '" step="any" />';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<div class="input-group input-group-sm">';
            html += '<select class="form-control input-sm col-tariff-fraction-id" name="item[' + item_row + '][tariff_fraction_id]" id="item_tariff_fraction_id_' + item_row + '">';
            html += '<option selected="selected" value="">@lang('general.text_select')</option>';
            html += '</select>';
            html += '<span class="input-group-btn">';
            html += '<button type="button" class="btn btn-info btn-tariff-fraction-search" data-row="' + item_row + '"><i class="fa fa-search"></i></button>';
            html += '</span>';
            html += '</div>';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-right col-customs-quantity" name="item[' + item_row + '][customs_quantity]" id="item_customs_quantity_' + item_row + '" step="any" />';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<div class="input-group input-group-sm">';
            html += '<select class="form-control input-sm col-uom-custom-id" name="item[' + item_row + '][uom_custom_id]" id="item_uom_custom_id_' + item_row + '">';
            html += '<option selected="selected" value="">@lang('general.text_select')</option>';
            html += '</select>';
            html += '<span class="input-group-btn">';
            html += '<button type="button" class="btn btn-info btn-uom-custom-search" data-row="' + item_row + '"><i class="fa fa-search"></i></button>';
            html += '</span>';
            html += '</div>';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-right col-price-unit-usd" name="item[' + item_row + '][price_unit_usd]" id="item_price_unit_usd_' + item_row + '" step="any" />';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<select class="form-control input-sm my-select2 col-taxes" name="item[' + item_row + '][taxes][]" id="item_taxes_' + item_row + '" multiple>';
            @foreach($taxes as $key => $value)
                html += '<option value="{{ $key }}">{{ $value }}</option>';
            @endforeach
                html += '</select>';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<select class="form-control input-sm col-tax-object" name="item[' + item_row + '][tax_object]" id="item_tax_object_' + item_row + '">';
            html += '<option selected="selected" value="">@lang('general.text_select')</option>';
            @foreach($tax_objects as $key => $value)
                html += '<option value="{{ $key }}">{{ $value }}</option>';
            @endforeach
                html += '</select>';
            html += '</div>';
            html += '</td>';
            html += '<td class="text-right" style="padding-top: 11px;">';
            html += '<span id="item_txt_amount_untaxed_' + item_row + '">0</span>';
            html += '</td>';
            html += '</tr>';

            $("#form #items tbody #add_item").before(html);

            /* Configura lineas*/
            initItem();

            totalItem();
            item_row++;
        }

        function initItem() {
            /*Para impuestos*/
            $("#form #items tbody .my-select2").select2({
                placeholder: "@lang('general.text_select')",
                theme: "bootstrap",
                dropdownAutoWidth: true,
                language: "{{ str_replace('_', '-', app()->getLocale()) }}",
            });
            /*Busqueda de productos*/
            $("#form #items tbody .col-product-id").select2({
                ajax: {
                    url: "{{route('products/autocomplete')}}",
                    dataType: "JSON",
                    delay: 250,
                    data: function (params) {
                        return {
                            term: $.trim(params.term),
                        };
                    },
                    processResults: function (data, page) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                templateResult: formatRepoCode,
                templateSelection: formatRepoCodeSelection,
                placeholder: "@lang('general.text_select')",
                theme: "bootstrap",
                dropdownAutoWidth: true,
                language: "{{ str_replace('_', '-', app()->getLocale()) }}",
                minimumInputLength: 3
            });
            /*Autoresize*/
            ymAutoResizeTextArea();
            /*Para unidades de medida*/
            $("#form #items tbody .col-unit-measure-id").select2({
                ajax: {
                    url: "{{route('unit-measures/autocomplete')}}",
                    dataType: "JSON",
                    delay: 250,
                    data: function (params) {
                        return {
                            term: $.trim(params.term),
                        };
                    },
                    processResults: function (data, page) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                templateResult: formatRepoCode,
                templateSelection: formatRepoCodeSelection,
                placeholder: "@lang('general.text_select')",
                theme: "bootstrap",
                dropdownAutoWidth: true,
                language: "{{ str_replace('_', '-', app()->getLocale()) }}",
                minimumInputLength: 2
            });
            /*Para productos sat*/
            $("#form #items tbody .col-sat-product-id").select2({
                ajax: {
                    url: "{{route('sat-products/autocomplete')}}",
                    dataType: "JSON",
                    delay: 250,
                    data: function (params) {
                        return {
                            term: $.trim(params.term),
                        };
                    },
                    processResults: function (data, page) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                templateResult: formatRepoCode,
                templateSelection: formatRepoCodeSelection,
                placeholder: "@lang('general.text_select')",
                theme: "bootstrap",
                dropdownAutoWidth: true,
                language: "{{ str_replace('_', '-', app()->getLocale()) }}",
                minimumInputLength: 3
            });
            /*Para tarifas arancelarias*/
            $("#form #items tbody .col-tariff-fraction-id").select2({
                ajax: {
                    url: "{{route('tariff-fractions/autocomplete')}}",
                    dataType: "JSON",
                    delay: 250,
                    data: function (params) {
                        return {
                            term: $.trim(params.term),
                        };
                    },
                    processResults: function (data, page) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                templateResult: formatRepoCode,
                templateSelection: formatRepoCodeSelection,
                placeholder: "@lang('general.text_select')",
                theme: "bootstrap",
                dropdownAutoWidth: true,
                language: "{{ str_replace('_', '-', app()->getLocale()) }}",
                minimumInputLength: 3
            });
            /*Para unidad aduana*/
            $("#form #items tbody .col-uom-custom-id").select2({
                ajax: {
                    url: "{{route('uom-customs/autocomplete')}}",
                    dataType: "JSON",
                    delay: 250,
                    data: function (params) {
                        return {
                            term: $.trim(params.term),
                        };
                    },
                    processResults: function (data, page) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                templateResult: formatRepoCode,
                templateSelection: formatRepoCodeSelection,
                placeholder: "@lang('general.text_select')",
                theme: "bootstrap",
                dropdownAutoWidth: true,
                language: "{{ str_replace('_', '-', app()->getLocale()) }}",
                minimumInputLength: 3
            });
        }

        function totalItem() {
            $.ajax({
                url: "{{ route('customer-foreign-trades/total-lines') }}",
                type: "POST",
                dataType: "JSON",
                data: $("#form").serialize(),
                success: function (data) {
                    if (data) {
                        $.each(data.items, function (key, value) {
                            $("#item_txt_amount_untaxed_" + key).html(value);
                        });
                        var html_taxes_label = ''
                        var html_taxes = ''
                        $.each(data.taxes, function (key, value) {
                            html_taxes_label += value.name + '<br/>';
                            html_taxes += value.amount_tax + '<br/>';
                        });
                        $("#form #txt_amount_untaxed").html(data.amount_untaxed);
                        $("#form #txt_amount_tax_label").html(html_taxes_label);
                        $("#form #txt_amount_tax").html(html_taxes);
                        $("#form #txt_amount_total").html(data.amount_total);
                        $("#form input[name='amount_total_tmp']").val(data.amount_total_tmp);
                    }
                },
                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);
                    }
                }
            });
        }

        function addItemCfdiRelation() {
            var html = '';

            html += '<tr id="item_relation_row_' + item_relation_row + '">';
            html += '<td class="text-center" style="vertical-align: middle;">';
            html += '<button type="button" onclick="$(\'#item_relation_row_' + item_relation_row + '\').remove();" class="btn btn-xs btn-danger" style="margin-bottom: 0;">';
            html += '<i class="fa fa-trash"></i>';
            html += '</button>';
            html += '<input type="hidden" name="item_relation[' + item_relation_row + '][id]" id="item_relation_id_' + item_relation_row + '" /> ';
            html += '</td>';
            html += '<td class="text-center align-middle">';
            html += '<div class="form-group form-group-sm">';
            html += '<select class="form-control input-sm col-relation-id" name="item_relation[' + item_relation_row + '][relation_id]" id="item_relation_relation_id_' + item_relation_row + '" data-row="' + item_relation_row + '">';
            html += '<option selected="selected" value="">@lang('general.text_select')</option>';
            html += '</select>';
            html += '</div>';
            html += '</td>';
            html += '<td class="text-center align-middle">';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="text" class="form-control input-sm text-center col-uuid-related" name="item_relation[' + item_relation_row + '][uuid_related]" id="item_relation_uuid_related_' + item_relation_row + '" required />';
            html += '</div>';
            html += '</td>';
            html += '</tr>';

            $("#form #items_relation tbody #add_item_relation").before(html);

            /* Configura select2 */
            initItemCfdiRelation();

            item_relation_row++;
        }


        function initItemCfdiRelation() {
            /*Busqueda de facturas*/
            $("#form #items_relation tbody .col-relation-id").select2({
                ajax: {
                    url: "{{route('customer-foreign-trades/autocomplete-cfdi')}}",
                    dataType: "JSON",
                    delay: 250,
                    data: function (params) {
                        return {
                            term: $.trim(params.term),
                            customer_id: $("#form select[name='customer_id']").val(),
                        };
                    },
                    processResults: function (data, page) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                placeholder: "@lang('general.text_select')",
                theme: "bootstrap",
                width: "auto",
                dropdownAutoWidth: true,
                language: "{{ str_replace('_', '-', app()->getLocale()) }}",
                minimumInputLength: 2
            });
        }

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

            /* Configura select2 para buscar cliente*/
            $("#form select[name='customer_id']").select2({
                ajax: {
                    url: "{{route('customers/autocomplete')}}",
                    dataType: "JSON",
                    delay: 250,
                    data: function (params) {
                        return {
                            term: $.trim(params.term),
                        };
                    },
                    processResults: function (data, page) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                placeholder: "@lang('general.text_select')",
                theme: "bootstrap",
                width: "100%",
                dropdownAutoWidth: true,
                allowClear: true,
                language: "{{ str_replace('_', '-', app()->getLocale()) }}",
                minimumInputLength: 3
            }).on("change", function () { //Selecciona cliente
                let id = $(this).val();
                if (id) {
                    $.ajax({
                        url: "{{ route('customers/get-customer') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id,
                        success: function (data) {
                            $("#form select[name='salesperson_id']").val(data.salesperson_id);
                            $("#form select[name='payment_term_id']").val(data.payment_term_id);
                            $("#form select[name='payment_way_id']").val(data.payment_way_id);
                            $("#form select[name='payment_method_id']").val(data.payment_method_id);
                            $("#form select[name='cfdi_use_id']").val(data.cfdi_use_id);
                            $("#form select[name='tax_regimen_customer_id']").val(data.tax_regimen_id);
                        },
                        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);
                            }
                        }
                    });
                }
            });
            /* Selecciona sucursal */
            $("#form select[name='branch_office_id']").on("change", function () {
                let id = $(this).val();
                if (id) {
                    $.ajax({
                        url: "{{ route('branch-offices/get-branch-office') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id,
                        success: function (data) {
                            $("#form input[name='date']").val(data.cfdi_date_time);
                            totalItem();
                        },
                        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);
                            }
                        }
                    });
                }
            }).trigger("change");
            /* Selecciona moneda */
            $("#form select[name='currency_id']").on("change", function () {
                let id = $(this).val();
                if (id) {
                    $.ajax({
                        url: "{{ route('currencies/get-currency') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id,
                        success: function (data) {
                            $("#form input[name='currency_value']").val(data.rate);
                            totalItem();
                        },
                        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);
                            }
                        }
                    });
                }
            }).trigger("change");

            /* init de Funciones */
            initItem();
            initItemCfdiRelation();
            totalItem();

            /*Modal para buscar clientes*/
            $(".btn-customer-search").on("click", function (e) {
                e.preventDefault();
                $.ajax({
                    url: "{{route('customers/modal-search')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "active_btn_select=1",
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_customer_search").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);
                        }
                    }
                });
            });
            /*Seleccionar cliente*/
            $(document).on("click", '#form_modal_customer_search #customers .btn-select-customer', function (e) {
                e.preventDefault();
                let option = new Option($(this).attr('data-name'), $(this).attr('data-id'), false, true);
                $("#form select[name='customer_id']").append(option).trigger('change');
                $("#modal_customer_search").modal("hide");
            });
            /*Modal para buscar alta de clientes*/
            $(".btn-customer-add").on("click", function (e) {
                e.preventDefault();
                $.ajax({
                    url: "{{route('customers/modal-create')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "",
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_customer_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 cliente*/
            $(document).on("submit", '#form_modal_customer_create', function (e) {
                e.preventDefault();
                var form = $(this);
                form.find(".help-block").remove();
                form.find(".form-control").parent().removeClass("has-error");
                $.ajax({
                    url: "{{ route('customers.store') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: $("#form_modal_customer_create").serialize(),
                    success: function (data) {
                        if (data) {
                            let option = new Option(data.name, data.id, false, true);
                            $("#form select[name='customer_id']").append(option).trigger('change');
                            $("#modal_customer_create").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_customer_create #modal_general_messages").html(alertMessage("danger", message));
                            }
                            setTimeout(function () {
                                $("#form_modal_customer_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);
                        }
                    }
                });
            });

            /* Eventos en items */
            /*Modal para buscar productos*/
            $(document).on('click', '#form #items tbody .btn-product-search', function (e) {
                e.preventDefault();
                let row = $(this).attr('data-row');
                $.ajax({
                    url: "{{route('products/modal-search')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "active_btn_select=1&row_origin="+ row,
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_product_search").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);
                        }
                    }
                });
            });
            /*Seleccionar producto*/
            $(document).on("click", '#form_modal_product_search #products .btn-select-product', function (e) {
                e.preventDefault();
                let option = new Option($(this).attr('data-code'), $(this).attr('data-id'), false, true);
                $("#form #items tbody #item_product_id_" + $(this).attr('data-row-origin') + "").append(option).trigger('select2:select');
                $("#modal_product_search").modal("hide");
            });
            /*Selecciona producto*/
            $(document).on('select2:select', '#form #items tbody .col-product-id', function (e) {
                let id = $(this).val();
                let row = $(this).attr('data-row');
                if (id) {
                    $.ajax({
                        url: "{{ route('products/get-product') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id,
                        success: function (data) {
                            $("#form #item_name_" + row).val(data.description);
                            if(data.unit_measure_id) {
                                let option = new Option(data.unit_measure_description_select2, data.unit_measure_id, false, true);
                                $("#form #item_unit_measure_id_" + row).append(option).trigger('change');
                            }
                            if(data.sat_product_id) {
                                let option = new Option(data.sat_product_description_select2, data.sat_product_id, false, true);
                                $("#form #item_sat_product_id_" + row).append(option).trigger('change');
                            }
                            if(data.tariff_fraction_id) {
                                let option = new Option(data.tariff_fraction_description_select2, data.tariff_fraction_id, false, true);
                                $("#form #item_tariff_fraction_id_" + row).append(option).trigger('change');
                            }
                            if(data.uom_custom_id) {
                                let option = new Option(data.uom_custom_description_select2, data.uom_custom_id, false, true);
                                $("#form #item_uom_custom_id_" + row).append(option).trigger('change');
                            }
                            $("#form #item_price_unit_" + row).val(data.price);
                            let tmp = $.map(data.taxes_1, function (value, index) {
                                return [value];
                            });
                            $("#form #item_taxes_" + row).val(tmp);
                            initItem();
                            totalItem();
                        },
                        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);
                            }
                        }
                    });
                }
            });
            /*Modal para buscar unidades de medida*/
            $(document).on('click', '#form #items tbody .btn-unit-measure-search', function (e) {
                e.preventDefault();
                let row = $(this).attr('data-row');
                $.ajax({
                    url: "{{route('unit-measures/modal-search')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "active_btn_select=1&row_origin="+ row,
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_unit_measure_search").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);
                        }
                    }
                });
            });
            /*Seleccionar unidad de medida*/
            $(document).on("click", '#form_modal_unit_measure_search #unit_measures .btn-select-unit-measure', function (e) {
                e.preventDefault();
                let option = new Option($(this).attr('data-description-select2'), $(this).attr('data-id'), false, true);
                $("#form #items tbody #item_unit_measure_id_" + $(this).attr('data-row-origin') + "").append(option).trigger('select2:select');
                $("#modal_unit_measure_search").modal("hide");
            });
            /*Modal para buscar productos del sat*/
            $(document).on('click', '#form #items tbody .btn-sat-product-search', function (e) {
                e.preventDefault();
                let row = $(this).attr('data-row');
                $.ajax({
                    url: "{{route('sat-products/modal-search')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "active_btn_select=1&row_origin="+ row,
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_sat_product_search").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);
                        }
                    }
                });
            });
            /*Seleccionar producto del sat*/
            $(document).on("click", '#form_modal_sat_product_search #sat_products .btn-select-sat-product', function (e) {
                e.preventDefault();
                let option = new Option($(this).attr('data-description-select2'), $(this).attr('data-id'), false, true);
                $("#form #items tbody #item_sat_product_id_" + $(this).attr('data-row-origin') + "").append(option).trigger('select2:select');
                $("#modal_sat_product_search").modal("hide");
            });
            /*Modal para buscar fracciones arancelarias*/
            $(document).on('click', '#form #items tbody .btn-tariff-fraction-search', function (e) {
                e.preventDefault();
                let row = $(this).attr('data-row');
                $.ajax({
                    url: "{{route('tariff-fractions/modal-search')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "active_btn_select=1&row_origin="+ row,
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_tariff_fraction_search").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);
                        }
                    }
                });
            });
            /*Seleccionar fraccion arancelaria*/
            $(document).on("click", '#form_modal_tariff_fraction_search #tariff_fractions .btn-select-tariff-fraction', function (e) {
                e.preventDefault();
                let option = new Option($(this).attr('data-description-select2'), $(this).attr('data-id'), false, true);
                $("#form #items tbody #item_tariff_fraction_id_" + $(this).attr('data-row-origin') + "").append(option).trigger('select2:select');
                $("#modal_tariff_fraction_search").modal("hide");
            });
            /*Modal para buscar unidad aduanas*/
            $(document).on('click', '#form #items tbody .btn-uom-custom-search', function (e) {
                e.preventDefault();
                let row = $(this).attr('data-row');
                $.ajax({
                    url: "{{route('uom-customs/modal-search')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "active_btn_select=1&row_origin="+ row,
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_uom_custom_search").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);
                        }
                    }
                });
            });
            /*Seleccionar unidad aduana*/
            $(document).on("click", '#form_modal_uom_custom_search #uom_customs .btn-select-uom-custom', function (e) {
                e.preventDefault();
                let option = new Option($(this).attr('data-description-select2'), $(this).attr('data-id'), false, true);
                $("#form #items tbody #item_uom_custom_id_" + $(this).attr('data-row-origin') + "").append(option).trigger('select2:select');
                $("#modal_uom_custom_search").modal("hide");
            });
            $(document).on("change", "#form #items tbody .col-includes-iva,#form #items tbody .col-taxes", function () {
                totalItem();
            });
            $(document).on("keyup", "#form #items tbody .col-quantity,#form #items tbody .col-price-unit,#form #items tbody .col-discount", function () {
                totalItem();
            });

            /* Eventos en items cfdi relation */
            /*Selecciona factura*/
            $(document).on('select2:select', '#form #items_relation tbody .col-relation-id', function (e) {
                let id = $(this).val();
                let row = $(this).attr('data-row');
                if (id) {
                    $.ajax({
                        url: "{{ route('customer-foreign-trades/get-customer-foreign-trade') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id,
                        success: function (data) {
                            $("#form #item_relation_uuid_related_" + row).val(data.uuid);
                        },
                        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
