<div id="appBuscarProveedores">
    <div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" id="modal_buscar_proveedor">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Buscar o registrar proveedores</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">
                        <div class="input-icon">
                            <span class="input-icon-addon">
                                <i :class="icon_buscador"></i>
                            </span>
                            <input type="text" id="buscador" class="form-control" placeholder="buscar proveedor" @input="buscarProveedor" @keydown="seleccionarProducto">
                        </div>
                    </div>
                </div>
                <form action="#" autocomplete="off" @submit.prevent="guardarProveedor" id="form_proveedor">
                    <div class="modal-body" v-show="!proveedorEncontrado">
                        <div class="form-row">
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label for="tipodoc">Tipo de documento:</label>
                                    <select class="form-control" id="tipodoc" name="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="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="dni" v-else name="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="razon_social">Razón social:</label>
                            <input type="text" id="razon_social" name="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="telefono">Teléfono:</label>
                                    <input type="tel" v-mask="'(####) ###-####'" id="telefono" name="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="correo">Correo electrónico:</label>
                                    <input type="text" id="correo" name="correo" class="form-control">
                                    <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" name="direccion_uno" class="form-control">
                        </div>
                        <div class="form-check">
                            <label class="form-check-label" for="prov_personafisica">
                                <input class="form-check-input" type="checkbox" id="prov_personafisica" name="prov_personafisica">
                                <span class="form-check-sign">Persona fisica</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/vue-the-mask.js') ?>"></script>
<script>
    var currentFocus;
    new Vue({
        el: '#appBuscarProveedores',
        data: {
            proveedores: [],
            proveedorEncontrado: true,
            ruta: '',
            icon_buscador: 'fa fa-search',
            errorForm: [],
            cargando: false,
            tipoci:2,
            clidni:''
        },
        mounted() {

            var self = this;

            function resetear() {
                self.proveedores = [];
                self.ruta = '';
                self.errorForm = [];
                document.getElementById('form_proveedor').reset();
            }

            $('#modal_buscar_proveedor').on('shown.bs.modal', function(e) {
                $('#buscador').trigger('focus');
            });

            $('#modal_buscar_proveedor').on('hidden.bs.modal', function(e) {
                resetear();
            });
        },
        methods: {
            guardarProveedor() {

                this.ruta = document.getElementById('ruta_documento').value;

                this.errorForm = [];

                let form_proveedor = document.getElementById('form_proveedor');
                var formData = new FormData(form_proveedor);
                formData.append('ruta', this.ruta);

                if (!formData.get('tipodoc'))
                    this.errorForm.push('El campo Tipo de Documento es obligatorio.');
                if (!formData.get('telefono'))
                    this.errorForm.push('El campo Teléfono es obligatorio.');
                if (!formData.get('direccion_uno'))
                    this.errorForm.push('El campo Dirección es obligatorio.');
                if (!formData.get('dni'))
                    this.errorForm.push('El campo Número de Documento es obligatorio.');
                if (!formData.get('razon_social'))
                    this.errorForm.push('El campo Razón Social es obligatorio.');
                if (!formData.get('correo')) {
                    this.errorForm.push('El Correo Electrónico es obligatorio.');
                } else if (!validaEmail(formData.get('correo'))) {
                    this.errorForm.push('El Correo Electrónico debe tener un formato válido.');
                }

                formData.set('prov_personafisica', formData.has('prov_personafisica') ? true : false);

                if (this.errorForm.length == 0) {
                    this.cargando = true;
                    axios({
                        method: 'post',
                        url: 'compras/guardarProveedor',
                        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;
                    });
                }
            },
            buscarProveedor(event) {
                this.ruta = document.getElementById('ruta_documento').value;
                this.icon_buscador = 'is-loading pr-3';
                this.bus_prov(event.target.value, event, this);
            },
            bus_prov: _.debounce((search, event, vm) => {

                currentFocus = 0;
                let a, b;
                var x = document.getElementsByClassName("autocomplete-items");

                for (var i = 0; i < x.length; i++) {
                    x[i].parentNode.removeChild(x[i]);
                }

                if (!search) {
                    vm.icon_buscador = 'fa fa-search';
                    return false;
                }

                axios.get('compras/buscarProveedores', {
                    params: {
                        buscar: search.trim()
                    }
                }).then(response => {
                    console.log(response.data)
                    if (response.data.length > 0) {
                        vm.proveedores = response.data;
                        vm.proveedorEncontrado = true;
                    } else {
                        vm.proveedores = [];
                        if (!isNaN(search) || !isNaN(search.charAt(1)) || !isNaN(search.charAt(2))) {
                            document.getElementById('dni').value = 'V'+search;
                        } else {
                            document.getElementById('dni').value = '';
                        }
                        vm.proveedorEncontrado = false;
                    }
                }).catch(e => console.log(e)).finally(() => {

                    vm.icon_buscador = 'fa fa-search';

                    currentFocus = -1;

                    a = document.createElement("div");
                    a.id = event.target.id + 'autocomplete-list';
                    a.classList.add('autocomplete-items');
                    event.target.parentNode.appendChild(a);

                    vm.proveedores.forEach((item, index) => {

                        b = document.createElement("div");

                        if (item.imagen) {
                            b.innerHTML += "<img src='" + item.imagen + "' class='avatar-img rounded-circle' style='width: 50px; height: 50px; margin-right: 15px'>";
                        }

                        if (item.prov_razonsocial.substr(0, search.length).toUpperCase() == search.toUpperCase()) {
                            b.innerHTML += "<strong>" + item.prov_razonsocial.substr(0, search.length) + "</strong>";
                            b.innerHTML += "<span>" + item.prov_razonsocial.substr(search.length) + "</span>";
                        } else {
                            b.innerHTML += "<strong>" + item.prov_razonsocial + "</strong>";
                        }

                        b.innerHTML += " <br> <small class='text-muted' style='margin-right: 5px'> Documento: " + item.prov_cifnif + "</small> ";
                        b.innerHTML += "<input type='hidden' value='" + item.prov_id + "' data-name='" + item.prov_razonsocial + "'>";

                        b.addEventListener("click", function(e) {

                            event.target.value = this.getElementsByTagName("input")[0].getAttribute('data-name');
                            let id_proveedor = this.getElementsByTagName("input")[0].value;

                            return location.href = baseURL + vm.ruta + '/nuevaFactura/' + id_proveedor;

                            for (var i = 0; i < x.length; i++) {
                                x[i].parentNode.removeChild(x[i]);
                            }
                        });

                        a.appendChild(b);
                    });
                });
            }, 350),
            seleccionarProducto(event) {

                var x = document.getElementById(event.target.id + 'autocomplete-list');

                if (x) x = x.getElementsByTagName("div");

                if (event.key == 'ArrowDown') {
                    currentFocus++;
                    active(x);
                } else if (event.key == 'ArrowUp') {
                    currentFocus--;
                    active(x);
                } else if (event.key == 'Enter') {
                    event.preventDefault();
                    if (currentFocus > -1) {
                        if (x) x[currentFocus].click();
                    }
                }
            },
            cne() {
                let dataFormcne = {
                    'tipo': this.tipoci,
                    'cli_dni': this.clidni
                };
                document.getElementById('btncne').disabled = true;
                axios({
                    method: 'post',
                    url: 'facturacion/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 = '';
            },
        }
    });

    function active(x) {

        if (!x) return false;

        for (var i = 0; i < x.length; i++) {
            x[i].classList.remove("autocomplete-active");
        }

        if (currentFocus >= x.length) currentFocus = 0;
        if (currentFocus < 0) currentFocus = (x.length - 1);

        x[currentFocus].classList.add("autocomplete-active");
    }

    function closeAllLists(elmnt) {
        let inp = document.getElementById("buscador");
        let x = document.getElementsByClassName("autocomplete-items");
        for (var i = 0; i < x.length; i++) {
            if (elmnt != x[i] && elmnt != inp) {
                x[i].parentNode.removeChild(x[i]);
            }
        }
    }

    document.addEventListener("click", function(e) {
        closeAllLists(e.target);
    });
    
</script>
