<div class="row" id="AppMes" v-cloak>
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <form @submit.prevent="buscar($event)" id="form_mes_busqueda">
                    <div class="form-row">
                        <div class="col-sm-6">
                            <div class="form-group form-floating-label">
                                <input id="mes_anio" type="text" class="form-control input-border-bottom" v-model.number="anio">
                                <label for="mes_anio" class="placeholder">Año</label>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group input-group form-floating-label">
                                <select id="mes_divisas" class="form-control input-border-bottom" ref="divisa">
                                <option value="0">Todas</option>    
                                <?php foreach ($divisas as $row) : ?>
                                        <option value="<?= $row['div_id'] ?>" <?= ($row['div_predeterminado'] == 1) ? 'selected' : '' ?>><?= $row['div_descripcion'] ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <label for="mes_divisas" class="placeholder">Divisa</label>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="form-group input-group form-floating-label">
                                <select id="sucursal" v-model="sucursal_predeterminada" class="form-control input-border-bottom" :disabled="disabled">
                                    <option disabled value="">Seleccione un elemento</option>
                                    <?php if ($todosucursales) : ?>
                                        <option value="0">Todas</option>
                                    <?php endif; ?>
                                    <option v-for="row in sucursales_empleado" :value="row.su_id"><span v-if="disabled==false">Sucursal: </span>{{row.su_nombre}}</option>
                                </select>
                                <label for="sucursal" class="placeholder" v-if="disabled===false">Sucursal</label>
                            </div>
                        </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="form-row">
                        <div class="col-12 text-right">
                            <button type="submit" class="btn btn-border btn-info btn-sm mr-2">Buscar</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="col-12">
        <div class="card">
            <div class="card-body" :cargando="cargando_tabla">
                <div class="table-responsive">
                    <table class="display nowrap table table-striped table-hover dataTable table-head-bg-primary table-bordered-bd-primary" id="tabla_meses">
                        <thead>
                            <tr>
                                <th class="text-center">Mes</th>
                                <th class="text-center">Cant. Art</th>
                                <th class="text-left">Costo</th>
                                <th class="text-left">Venta</th>
                                <th class="text-left">Ganancia</th>
                                <th class="text-left">Porcentaje</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="row in meses">
                                <td class="text-center">{{ row.mes }}</td>
                                <td class="text-center">{{ row.cantidad }}</td>
                                <td class="text-right">{{ moneda(row.costo, row.div_locale, row.div_simbolo) }}</td>
                                <td class="text-right">{{ moneda(row.venta, row.div_locale, row.div_simbolo) }}</td>
                                <td class="text-right">{{ moneda(row.ganancia, row.div_locale, row.div_simbolo) }}</td>
                                <td class="text-right">{{ decimal(row.porcentaje, row.div_locale) }}%</td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th class="text-center">Total</th>
                                <th class="text-center">{{ art_total }}</th>
                                <th class="text-right">{{ costo }}</th>
                                <th class="text-right">{{ venta }}</th>
                                <th class="text-right">{{ ganancia }}</th>
                                <th class="text-right">{{ porcentaje }}</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    new Vue({
        el: '#AppMes',
        data: {
            meses: [],
            anio: moment().format('YYYY'),
            divisa: '',
            art_total: 0,
            costo: 0,
            venta: 0,
            ganancia: 0,
            porcentaje: 0,
            errorForm: [],
            cargando: false,
            cargando_tabla: 'is-loading is-loading-lg',
            sucursal_predeterminada:'',
            sucursales_empleado: [],
            sucursals: '',
            disabled: false
        },
        created() {
            this.obtenerSucursalesEmpleado();
        },
        mounted() {

        },
        methods: {
            obtenerVentasMES() {
                let select_divisa = document.getElementById('mes_divisas');
                let selectedOptionDiv = select_divisa.options[select_divisa.selectedIndex];

                axios.get('ingresosegresos/produccionMes', {
                    params: {
                        anio: this.anio,
                        divisa: this.$refs.divisa.value,
                        sucursal: this.sucursal_predeterminada
                    }
                }).then(response => {
                    if (response.data.errors == null) {
                        if (Object.keys(response.data.meses).length > 0) {
                            this.meses = response.data.meses;
                            this.art_total = response.data.art_total
                            this.costo = response.data.costo;
                            this.venta = response.data.venta;
                            this.ganancia = response.data.ganancia;
                            this.porcentaje = response.data.porcentaje;
                        }
                    } else {
                        this.errorForm = response.data.errors;
                    }
                }).catch(e => notificacion()).finally(() => {
                    this.cargando_tabla = '';

                    let buttonCommon = {
                        exportOptions: {
                            format: {
                                body: function(data, row, column, node) {
                                    return convertir_a_float(data);
                                }
                            }
                        }
                    };

                    $("#tabla_meses").DataTable({
                        order: [],
                        dom: 'Bfrtip',
                        buttons: [
                            $.extend(true, {}, buttonCommon, {
                                extend: 'excelHtml5',
                                title: 'Ventas por meses del Año (' + this.anio + ')' +
                                    ' Divisa (' + selectedOptionDiv.text + ')',
                            }),
                        ]
                    });
                });
            },
            obtenerSucursalesEmpleado() {
                axios
                    .get("ingresosegresos/obtenerSucursalesEmpleado")
                    .then((response) => {
                        this.sucursales_empleado = response.data.sucursales;
                        this.sucursal_predeterminada = response.data.id;
                        if (response.data.desactivar == true) {
                            this.disabled = true
                        }
                        this.obtenerVentasMES();
                    })
                    .catch((e) => notificacion());
            },
            resetearFormulario() {
                document.getElementById('form_mes_busqueda').reset();
                this.anio = moment().format('YYYY');
                this.errorForm = [];
            },
            buscar(event) {

                let select_divisa = document.getElementById('mes_divisas');
                let selectedOptionDiv = select_divisa.options[select_divisa.selectedIndex];

                this.errorForm = [];
                this.cargando = true;
                this.cargando_tabla = 'is-loading is-loading-lg';
                $("#tabla_meses").DataTable().destroy();

                axios.get('ingresosegresos/produccionMes', {
                    params: {
                        anio: this.anio,
                        divisa: this.$refs.divisa.value,
                        sucursal:this.sucursal_predeterminada
                    }
                }).then(response => {
                    if (response.data.errors == null) {
                        this.meses = response.data.meses;
                        this.art_total = response.data.art_total
                        this.costo = response.data.costo;
                        this.venta = response.data.venta;
                        this.ganancia = response.data.ganancia;
                        this.porcentaje = response.data.porcentaje;
                    } else {
                        this.errorForm = response.data.errors;
                    }
                }).catch(e => notificacion()).finally(() => {
                    this.cargando = false;
                    this.cargando_tabla = '';

                    let buttonCommon = {
                        exportOptions: {
                            format: {
                                body: function(data, row, column, node) {
                                    return convertir_a_float(data);
                                }
                            }
                        }
                    };

                    $("#tabla_meses").DataTable({
                        order: [],
                        dom: 'Bfrtip',
                        buttons: [
                            $.extend(true, {}, buttonCommon, {
                                extend: 'excelHtml5',
                                title: 'Ventas por meses del Año (' + this.anio + ')' +
                                    ' Divisa (' + selectedOptionDiv.text + ')',
                            }),
                        ]
                    });
                });

            },
            moneda(num, div_locale, div_simbolo, decimal = 2) {
                return monedaMoneda(num, div_locale, div_simbolo, decimal);
            },
            decimal(num, div_locale, decimal = 2) {
                return monedaDecimal(num, div_locale, decimal);
            }
        }
    });
</script>