<div id="appCatEmp">
    <div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" id="modal-cat_emp">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header mh">
                    <h4 class="modal-title">Asignar Empleados</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_cat_emp" @submit.prevent="guardarCatEmp">
                                <div class="form-row">
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="e_categoria">Categorías</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text">
                                                        <i class="flaticon-mark-1"></i>
                                                    </span>
                                                </div>
                                                <select name="e_categoria" id="e_categoria" class="form-control">
                                                    <option value="" disabled>Seleccionar categoria</option>
                                                    <option :value="row.id" v-for="row in categorias">
                                                        {{ row.categoria }}
                                                    </option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="select_empleado">Empleados</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text">
                                                        <i class="fas fa-user-tie"></i>
                                                    </span>
                                                </div>
                                                <v-select id="select_empleado" v-model="select_empleado" :options="empleados" :reduce="row => row.id" label="empleado" style="width: 315px;" />
                                            </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>
                    </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 class="card-category text-primary pb-2" style="padding-left: 10px;"> <i class="fas fa-list-ul"></i>Lista de Empleados</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_cat_emp">
                                <thead>
                                    <tr>
                                        <th>Categoría</th>
                                        <th>Empleado</th>
                                        <th>Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="row in array_cat_emp">
                                        <td style="height: inherit;">{{ row.categoria.categoria }}</td>
                                        <td style="height: inherit;">{{ row.empleado.empleado }}</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="editarCatEmp(row)">
                                                    <i class="fa fa-edit text-info"></i>
                                                </button>
                                                <button type="button" title="Eliminar" class="btn btn-link btn-primary" @click="eliminarCatEmp(row)">
                                                    <i class="fa fa-trash text-dark"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    Vue.component('v-select', VueSelect.VueSelect)

    new Vue({
        el: '#appCatEmp',
        data: {
            id_cat_emp: '',
            categorias: [],
            select_empleado: null,
            empleados: [],
            array_cat_emp: [],
            errorForm: [],
            cargando: false
        },
        mounted() {

            var self = this;

            self.resetear();

            $('#modal-cat_emp').on('shown.bs.modal', function(e) {
                $('#e_categoria').trigger('focus');
                self.obtenerCategorias();
                self.obtenerEmpleados();
                self.obtenerCatEmp();
            });

            $('#modal-cat_emp').on('hidden.bs.modal', function(e) {
                self.resetear();
            });
        },
        methods: {
            eliminarTabla() {
                if ($.fn.DataTable.isDataTable('#tabla_cat_emp')) {
                    $('#tabla_cat_emp').DataTable().destroy();
                }
            },
            redibujarTabla() {
                $(document).ready(function() {
                    $("#tabla_cat_emp").DataTable({
                        retrieve: true,
                        dom: 'Bfrtip',
                        buttons: [{
                            title: 'Motores',
                            extend: 'excelHtml5',
                            exportOptions: {
                                columns: [0, 1, 2]
                            }
                        }]
                    });
                });
            },
            resetear() {
                this.errorForm = [];
                this.id_cat_emp = '';
                document.getElementById('form_cat_emp').reset();
                document.getElementById('e_categoria').selectedIndex = 0;
                this.select_empleado = null;
            },
            guardarCatEmp() {

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

                if (!formData.get('e_categoria'))
                    this.errorForm.push('EL campo Categoria es obligatorio');
                if (!this.select_empleado) {
                    this.errorForm.push('EL campo Empleado es obligatorio');
                } else {
                    formData.append('empleado', this.select_empleado);
                }

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

                if (this.errorForm.length == 0) {
                    this.cargando = true;
                    axios({
                        method: 'post',
                        url: 'planilla/guardarCategoriaEmpleado',
                        data: formData
                    }).then(response => {
                        if (response.data.errors == null) {
                            this.eliminarTabla();
                            this.obtenerCatEmp();
                        } else {
                            this.errorForm = response.data.errors;
                        }
                    }).catch(e => notificacion()).finally(() => {
                        this.cargando = false;
                    });
                }
            },
            editarCatEmp(cat_emp) {
                this.id_cat_emp = cat_emp.id;
                document.getElementById('e_categoria').value = cat_emp.categoria.id;
                this.select_empleado = cat_emp.empleado.id;
            },
            obtenerCatEmp() {
                this.resetear();
                this.eliminarTabla();
                axios.get('planilla/obtenerCategoriasEmpleados').then(response => {
                    this.array_cat_emp = response.data;
                }).catch(e => notificacion()).finally(() => {
                    this.cargando = false;
                    this.redibujarTabla();
                });
            },
            eliminarCatEmp(cat_emp) {
                axios.get('planilla/eliminarCategoriaEmpleado/' + cat_emp.id).then(response => {
                    if (response.data == true) {
                        let posicion = this.array_cat_emp.findIndex((item) => item.id == cat_emp.id);
                        this.array_cat_emp.splice(posicion, 1);
                        this.eliminarTabla();
                        this.redibujarTabla();
                        notificacion('fa fa-trash', '', 'Relación eliminada', 'danger');
                    }
                }).catch(e => notificacion()).finally(() => {
                    this.cargando = false;
                });
            },
            obtenerCategorias() {
                axios.get('planilla/obtenerCategorias').then(response => {
                    this.categorias = response.data;
                }).catch(e => notificacion()).finally(() => {
                    this.cargando = false;
                });
            },
            obtenerEmpleados() {
                axios.get('planilla/obtenerEmpleados').then(response => {
                    this.empleados = response.data;
                }).catch(e => notificacion()).finally(() => {
                    this.cargando = false;
                });
            },
        }
    })
</script>