<div id="appMotores">
    <div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" id="modal-motores">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header mh">
                    <h4 class="modal-title">Registrar Motor</h4>
                    <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="row">
                        <div class="col">
                            <form id="form_motor" @submit.prevent="guardarMotores">
                                <div class="form-row">
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="m_marca">Marca</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text">
                                                        <i class="fas fa-trademark"></i>
                                                    </span>
                                                </div>
                                                <select name="m_marca" id="m_marca" class="form-control">
                                                    <option value="" disabled>Seleccionar marca</option>
                                                    <option :value="row.id" v-for="row in marcas">
                                                        {{ row.marca }}
                                                    </option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="motor">Motor</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text">
                                                        <i class="flaticon-settings"></i>
                                                    </span>
                                                </div>
                                                <input type="text" id="motor" name="motor" maxlength="100" class="form-control" onkeyup="this.value=this.value.toUpperCase()">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="modelo">Modelo</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text">
                                                        <i class="fas fa-tag"></i>
                                                    </span>
                                                </div>
                                                <input type="text" id="modelo" name="modelo" maxlength="100" class="form-control" onkeyup="this.value=this.value.toUpperCase()">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="m_tipo">Tipo</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text">
                                                        <i class="fas fa-trademark"></i>
                                                    </span>
                                                </div>
                                                <select name="m_tipo" id="m_tipo" class="form-control">
                                                    <option value="" selected disabled>Seleccionar tipo de motor</option>
                                                    <option :value="row.id" v-for="row in tipos">
                                                        {{ row.tipo }}
                                                    </option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group pull-right">
                                    <button type="submit" class="btn btn-sm boton-primario-p">Registrar</button>
                                </div>
                            </form>
                            <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>
                    <div class="row">
                        <div class="col" style="margin: 0 auto; max-width: 97%;">
                            <table class="display table table-striped table-hover dataTable" id="tabla_motores">
                                <thead>
                                    <tr>
                                        <th style="height: inherit;">Marca</th>
                                        <th style="height: inherit;">Motor</th>
                                        <th style="height: inherit;">Modelo</th>
                                        <th style="height: inherit;">Tipo</th>
                                        <th class="text-center" style="height: inherit; width: 20%">Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="row in motores">
                                        <td style="height: inherit;">{{ row.marca.marca }}</td>
                                        <td style="height: inherit;">{{ row.motor }}</td>
                                        <td style="height: inherit;">{{ row.modelo }}</td>
                                        <td style="height: inherit;">{{ row.tipo.tipo }}</td>
                                        <td class="text-center" style="height: inherit; width: 20%">
                                            <div class="form-button-action">
                                                <button type="button" title="Editar" class="btn btn-link btn-primary" @click="editarMotor(row)">
                                                    <i class="fa fa-edit text-info"></i>
                                                </button>
                                                <button type="button" title="Eliminar" class="btn btn-link btn-primary" @click="eliminarMotor(row)">
                                                    <i class="fa fa-trash text-dark"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    new Vue({
        el: '#appMotores',
        data: {
            id_motor: '',
            marcas: [],
            motores: [],
            tipos: [],
            errorForm: [],
            cargando: false
        },
        mounted() {

            var self = this;

            this.resetear();

            $('#modal-motores').on('shown.bs.modal', function(e) {
                $('#m_marca').trigger('focus');
                self.obtenerMarcas();
                self.obtenerMotores();
                self.obtenerTipoMotor();
            });

            $('#modal-motores').on('hidden.bs.modal', function(e) {
                self.resetear();
            });
        },
        methods: {
            eliminarTabla() {
                if ($.fn.DataTable.isDataTable('#tabla_motores')) {
                    $('#tabla_motores').DataTable().destroy();
                }
            },
            redibujarTabla() {
                $(document).ready(function() {
                    $("#tabla_motores").DataTable({
                        retrieve: true,
                        dom: 'Bfrtip',
                        buttons: [{
                            title: 'Motores',
                            extend: 'excelHtml5',
                            exportOptions: {
                                columns: [0, 1, 2]
                            }
                        }]
                    });
                });
            },
            resetear() {
                this.errorForm = [];
                this.id_motor = '';
                document.getElementById('form_motor').reset();
                document.getElementById('m_marca').selectedIndex = 0;
                document.getElementById('m_tipo').selectedIndex = 0;
            },
            guardarMotores() {

                this.errorForm = [];
                let form_motor = document.getElementById('form_motor');
                let formData = new FormData(form_motor);

                if (!formData.get('motor'))
                    this.errorForm.push('EL campo Motor es obligatorio');
                if (!formData.get('m_marca'))
                    this.errorForm.push('EL campo Marca es obligatorio');
                if (!formData.get('m_tipo'))
                    this.errorForm.push('EL campo Tipo es obligatorio');

                if (this.id_motor) {
                    formData.append('id', this.id_motor);
                }

                if (this.errorForm.length == 0) {
                    this.cargando = true;
                    axios({
                        method: 'post',
                        url: 'planilla/guardarMotores',
                        data: formData
                    }).then(response => {
                        if (response.data.errors == null) {
                            this.obtenerMotores();
                            notificacion('fa fa-check', 'Guardado', 'Registro exitoso', 'success');
                        } else {
                            this.errorForm = response.data.errors;
                        }
                    }).catch(e => notificacion()).finally(() => {
                        this.cargando = false;
                    });
                }
            },
            editarMotor(motor) {
                this.id_motor = motor.id;
                document.getElementById('motor').value = motor.motor;
                document.getElementById('m_marca').value = motor.marca.id;
                document.getElementById('modelo').value = motor.modelo;
                document.getElementById('m_tipo').value = motor.tipo.id;
            },
            obtenerMotores() {
                this.resetear();
                axios.get('planilla/obtenerMotores').then(response => {
                    this.motores = response.data;
                    this.eliminarTabla();
                }).catch(e => notificacion()).finally(() => {
                    this.cargando = false;
                    this.redibujarTabla();
                });
            },
            eliminarMotor(motor) {
                axios.get('planilla/eliminarMotor/' + motor.id).then(response => {
                    if (response.data == true) {
                        let posicion = this.motores.findIndex((item) => item.id == motor.id);
                        this.motores.splice(posicion, 1);
                        this.eliminarTabla();
                        notificacion('fa fa-trash', 'Eliminado', motor.motor.toUpperCase(), 'danger');
                    }
                }).catch(e => notificacion()).finally(() => {
                    this.cargando = false;
                    this.redibujarTabla();
                });
            },
            obtenerMarcas() {
                axios.get('planilla/obtenerMarcas').then(response => {
                    this.marcas = response.data;
                }).catch(e => notificacion()).finally(() => {
                    this.cargando = false;
                });
            },
            obtenerTipoMotor() {
                axios.get('planilla/obtenerTipoMotor').then(response => {
                    this.tipos = response.data;
                }).catch(e => notificacion()).finally(() => {
                    this.cargando = false;
                });
            },
        }
    })
</script>