<div id="appBuscarCliente">
    <div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" id="modal_buscar_cliente_generico">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Buscar o registrar clientes</h5>
                    <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>
                                    </div>
                                </div>
                            </template>
                        </v-select>
                    </div>
                </div>
                <form action="#" autocomplete="off" @submit.prevent="guardarCliente">
                    <div class="modal-body" v-show="!clienteEncontrado">
                        <div class="form-row">
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label for="tipodoc">Tipo de documento:</label>
                                    <select class="form-control" v-model="dataForm.cli_tipodoc" @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="dni" v-if="dataForm.cli_tipodoc==2" name="cli_dni" class="form-control" v-mask="'A########'" v-model="dataForm.cli_dni" @keyup="dataForm.cli_dni+=dataForm.cli_dni.toUpperCase()">
                                        <input type="text" id="dni" v-else name="cli_dni" class="form-control" v-mask="'A#########'" v-model="dataForm.cli_dni" @keyup="dataForm.cli_dni=dataForm.cli_dni.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="dataForm.cli_tipodoc==2">V00000000</small>
                                    <small class="form-text text-muted" v-if="dataForm.cli_tipodoc==3">J000000000</small>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="razon_social">Razón social:</label>
                            <input type="text" id="razon_social" class="form-control" v-model="dataForm.cli_razon_social" maxlength="150" @keyup="dataForm.cli_razon_social=dataForm.cli_razon_social.toUpperCase()">
                        </div>
                        <div class="form-row">
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label for="telefono">Teléfono:</label>
                                    <input type="tel" v-mask="'(####) ###-####'" id="telefono" class="form-control" v-model="dataForm.cli_telefono">
                                    <small class="form-text text-muted">(0000) 000-0000</small>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label for="correo">Correo electrónico:</label>
                                    <input type="text" id="correo" class="form-control" v-model="dataForm.cli_email">
                                    <small class="form-text text-muted">usuario@ejemplo.com</small>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="direccion_uno">Dirección:</label>
                            <input type="text" id="direccion_uno" class="form-control" v-model="dataForm.cli_direccion">
                        </div>
                        <div class="form-check">
                            <label class="form-check-label">
                                <input class="form-check-input" type="checkbox" value="TRUE" v-model="dataForm['cli_natural']">
                                <span class="form-check-sign">Persona natural (no jurídica)</span>
                            </label>
                        </div>
                        <div class="alert alert-warning" v-if="errorForm.length">
                            <h4 class="alert-heading">Por favor, corrija el(los) siguiente(s) error(es):</h4>
                            <p class="mb-1" v-for="row in errorForm">{{ row }}</p>
                        </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/vue-select.js') ?>"></script>
<link rel="stylesheet" href="<?= asset('assets/vue-select.css') ?>">
<script src="<?= asset('assets/vue-the-mask.js') ?>"></script>

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

    new Vue({
        el: '#appBuscarCliente',
        data: {
            ruta: '',
            clientes: [],
            clienteEncontrado: true,
            dataForm: {
                'ruta': '',
                'cli_tipodoc': 2,
                'cli_dni': '',
                'cli_razon_social': '',
                'cli_email': '',
                'cli_telefono': '',
                'cli_direccion': '',
                'cli_natural': true
            },
            errorForm: [],
            cargando: false,
            selected_cli: []
        },
        mounted() {
            var self = this;
            $('#modal_buscar_cliente_generico').on('shown.bs.modal', function(e) {
                $('#tu_cliente > div > div > input').trigger('focus')
            });
            $('#modal_buscar_cliente_generico').on('hidden.bs.modal', function(e) {
                self.clientes = [];
                self.selected_cli = '';
                self.dataForm.cli_dni = '';
                self.dataForm.ruta = '';
                self.errorForm = [];

            });
            self.ruta = document.getElementById('ruta_documento').value;
        },
        methods: {
            guardarCliente() {

                this.errorForm = [];

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

                this.dataForm.ruta = this.ruta;

                if (this.errorForm.length == 0) {
                    this.cargando = true;
                    axios({
                        method: 'post',
                        url: 'facturacion/guardarCliente',
                        data: this.dataForm,
                        transformRequest: serializar(),
                    }).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) {
                    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.dataForm.cli_dni = search;
                        } else {
                            vm.dataForm.cli_dni = '';
                        }
                        vm.clienteEncontrado = false;
                    }
                }).catch(e => notificacion()).finally(() => loading(false));
            }, 350),
            redireccionar() {
                return location.href = baseURL + this.ruta + '/nuevaFactura/' + this.selected_cli.id;
            },
            formatearSelect() {
                this.dataForm.cli_dni = '';
            },
            cne() {
                let dataFormcne = {
                    'tipo': this.dataForm.cli_tipodoc,
                    'cli_dni': this.dataForm.cli_dni
                };
                document.getElementById('btncne').disabled = true;
                axios({
                    method: 'post',
                    url: 'ptv/cne',
                    data: dataFormcne,
                    transformRequest: serializar(),
                }).then(response => {
                    if (response.data.error == 0) {
                        // if (response.data == true) {
                        console.log(response.data);

                        this.dataForm.cli_razon_social = response.data.apellidos + ' ' + response.data.nombres;
                        this.dataForm.cli_direccion = response.data.direccion;
                        // }
                    } else {
                        notificacion('fa fa-ban', 'Advertencia', response.data, 'warning');
                    }
                    document.getElementById('btncne').disabled = false;
                }).catch(e => notificacion()).finally();
            },
        }
    });
</script>