<div id="appBuscarCliente">
    <div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" id="modal_cliente_crear_orden">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Buscar o registrar clientes</h5>&nbsp;&nbsp;
                    <button type="button" class="btn btn-sm" @click="clienteEncontrado = !clienteEncontrado">
                        registrar
                    </button>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <v-select id="tu_cliente" v-model="selected_cli" label="cliente" :filterable="false" :options="clientes" @search="onSearch" @input="redireccionar">
                            <template slot="no-options">
                                Escribe para buscar el cliente
                            </template>
                            <template slot="option" slot-scope="option">
                                <div class="d-flex ml-0 pl-0">
                                    <div class="avatar ml-0 pl-0">
                                        <span class="avatar-title rounded-circle border border-white bg-info ml-0 pl-0" style="width: 40px; height: 40px;">{{ option.cliente.charAt() }}</span>
                                    </div>
                                    <div class="flex-1 pt-1 ml-2">
                                        <h6 class="fw-bold mb-1">{{ option.cliente.toUpperCase() }}</h6>
                                        <small>{{ option.dni }}</small>
                                    </div>
                                </div>
                            </template>
                        </v-select>
                    </div>
                </div>
                <form action="#" autocomplete="off" @submit.prevent="guardarCliente" id="form_cliente">
                    <div class="modal-body" v-show="!clienteEncontrado">
                        <div class="form-row">
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label for="cli_tipodoc">Tipo de documento:</label>
                                    <select class="form-control" id="cli_tipodoc" name="cli_tipodoc" v-model="tipoci" @change="formatearSelect()">
                                        <option value="" disabled>selecione un documento</option>
                                        <?php foreach ($tipos_de_documentos as $row) : ?>
                                            <option value="<?= $row['tipodoc_id'] ?>"><?= $row['tipodoc_codigo'] ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label for="dni">Nº de documento:</label>
                                    <div class="input-group">
                                        <input type="text" id="cli_dni" v-if="tipoci==2" name="cli_dni" class="form-control" v-mask="'A########'" v-model="clidni" @keyup="clidni=clidni.toUpperCase()">
                                        <input type="text" id="cli_dni" v-else name="cli_dni" class="form-control" v-mask="'A#########'" v-model="clidni" @keyup="clidni=clidni.toUpperCase()">
                                        <div class="input-group-append">
                                            <button class="btn btn-primary" type="button" id="btncne" @click="cne()">CNE</button>
                                        </div>
                                    </div>
                                    <small class="form-text text-muted" v-if="tipoci==2">V00000000</small>
                                    <small class="form-text text-muted" v-if="tipoci==3">J000000000</small>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="cli_razon_social">Razón social:</label>
                            <input type="text" id="cli_razon_social" name="cli_razon_social" class="form-control" maxlength="150" onkeyup="this.value=this.value.toUpperCase()">
                        </div>
                        <div class="form-row">
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label for="cli_telefono">Teléfono:</label>
                                    <input type="tel" v-mask="'(####) ###-####'" id="cli_telefono" name="cli_telefono" class="form-control">
                                    <small class="form-text text-muted">(0000) 000-0000</small>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label for="cli_email">Correo electrónico:</label>
                                    <input type="text" id="cli_email" class="form-control" name="cli_email">
                                    <small class="form-text text-muted">usuario@ejemplo.com</small>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="cli_direccion">Dirección:</label>
                            <input type="text" id="cli_direccion" class="form-control" name="cli_direccion">
                        </div>
                        <div class="form-check">
                            <label for="cli_natural" class="form-check-label">
                                <input class="form-check-input" type="checkbox" id="cli_natural" name="cli_natural" checked>
                                <span class="form-check-sign">Persona natural (no jurídica)</span>
                            </label>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <div class=" alert alert-warning" role="alert" v-for="row in errorForm">
                                    {{ row }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary  btn-sm" data-dismiss="modal">Cerrar</button>
                        <button v-if="cargando" class="btn btn-sm btn-primary" disabled>
                            <i class="loader loader-info"></i>
                        </button>
                        <button v-else type="submit" class="btn btn-primary  btn-sm">Registrar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="<?= asset('assets/underscore-min.js') ?>"></script>
<script src="<?= asset('assets/vue-the-mask.js') ?>"></script>

<script>
    Vue.component('v-select', VueSelect.VueSelect)

    new Vue({
        el: '#appBuscarCliente',
        data: {
            clientes: [],
            clienteEncontrado: true,
            errorForm: [],
            selected_cli: [],
            cargando: false,
            tipoci:2,
            clidni:''
        },
        mounted() {
            var self = this;
            $('#modal_cliente_crear_orden').on('shown.bs.modal', function(e) {
                $('#tu_cliente > div > div > input').trigger('focus')
            });
            $('#modal_cliente_crear_orden').on('hidden.bs.modal', function(e) {
                self.resetearFormulario();
            });
        },
        methods: {
            resetearFormulario() {
                this.clientes = [];
                this.selected_cli = [];
                document.getElementById('form_cliente').reset();
            },
            guardarCliente() {

                this.errorForm = [];

                let form_cliente = document.getElementById('form_cliente');
                let formData = new FormData(form_cliente);

                if (!formData.get('cli_tipodoc'))
                    this.errorForm.push('El campo Tipo de Documento es obligatorio.');
                if (!formData.get('cli_telefono'))
                    this.errorForm.push('El campo Teléfono es obligatorio.');
                if (!formData.get('cli_direccion'))
                    this.errorForm.push('El campo Dirección es obligatorio.');
                if (!formData.get('cli_dni'))
                    this.errorForm.push('El campo Número de Documento es obligatorio.');
                if (!formData.get('cli_razon_social'))
                    this.errorForm.push('El campo Razón Social es obligatorio.');
                if (formData.get('cli_email')) {
                    if (!validaEmail(formData.get('cli_email')))
                        this.errorForm.push('El Correo Electrónico debe tener un formato válido.');
                }

                formData.set('cli_natural', formData.get('cli_natural') ? true : false);

                if (this.errorForm.length == 0) {
                    this.cargando = true;
                    axios({
                        method: 'post',
                        url: 'planilla/guardarCliente',
                        data: formData,
                    }).then(response => {
                        if (response.data.errors == null) {
                            location.href = response.data;
                        } else {
                            let total_errores = response.data.errors.length
                            for (let i = 0; i < total_errores; i++) {
                                notificacion('fa fa-ban', 'Advertencia', response.data.errors[i], 'warning');
                            }
                        }
                    }).catch(e => notificacion()).finally(() => this.cargando = false);
                }
            },
            onSearch(search, loading) {
                if (search.trim() && search.trim().length > 3) {
                    loading(true);
                    this.search(loading, search, this);
                }
            },
            search: _.debounce((loading, search, vm) => {
                axios.get('notadecredito/buscarCliente/', {
                    params: {
                        'buscar': search
                    }
                }).then(response => {
                    if (response.data.length > 0) {
                        vm.clientes = response.data;
                        vm.clienteEncontrado = true;
                    } else {
                        vm.clientes = [];
                        if (!isNaN(search) || !isNaN(search.charAt(1)) || !isNaN(search.charAt(2))) {
                            vm.clidni = 'V'+search;
                        } else {
                             vm.clidni = '';
                        }
                        vm.clienteEncontrado = false;
                    }
                }).catch(e => notificacion()).finally(() => loading(false));
            }, 350),
            redireccionar() {
                axios.get('planilla/agregarCliente/' + Number(this.selected_cli.id)).then(response => {
                    if (response.data.errors == null) {
                        location.href = response.data;
                    } else {
                        let total_errores = response.data.errors.length
                        for (let i = 0; i < total_errores; i++) {
                            notificacion('fa fa-ban', 'Advertencia', response.data.errors[i], 'warning');
                        }
                    }
                }).catch(e => notificacion());
            },
            cne() {
                let dataFormcne = {
                    'tipo': this.tipoci,
                    'cli_dni': this.clidni
                };
                document.getElementById('btncne').disabled = true;
                axios({
                    method: 'post',
                    url: 'planilla/cne',
                    data: dataFormcne,
                    transformRequest: serializar(),
                }).then(response => {
                    if (response.data.error == 0) {
                        // if (response.data == true) {
                        console.log(response.data);
                        document.getElementById('razon_social').value = response.data.apellidos + ' ' + response.data.nombres;
                        document.getElementById('direccion_uno').value = response.data.direccion;
                        // }
                    } else {
                        notificacion('fa fa-ban', 'Advertencia', response.data, 'warning');
                    }
                    document.getElementById('btncne').disabled = false;
                }).catch(e => notificacion()).finally();
            },
            formatearSelect() {
                this.clidni = '';
            },
        }
    });
</script>