<div class="row" id="AppprodComprasMes" v-cloak>
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <form  @submit.prevent="buscar($event)" id="form_mescomp_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">
                                    <?php foreach ($divisas as $row) : ?>
                                        <option value="<?= $row['div_id'] ?>" <?= ($row['div_facturar'] == 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>
                                    <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" :class="cargando_tabla">
        <div class="row mt-3" v-for="row in meses">
            <div class="col-12">
                <div class="card card-invoice">
                    <div class="card-body" style="width: 95%;">
                        <div class="invoice-detail">
                            <div class="invoice-top text-center mt-3" style="background-color: rgba(222, 222, 222, 0.4);">
                                <h3 class="title"><strong>Mes {{ row.mes }}</strong></h3>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-12">
                <div class="card">
                    <div class="card-body" style="width: 95%;">
                        <div class="invoice-item">
                            <div class="table-responsive">
                                <table class="display nowrap table table-striped table-hover dataTable table-head-bg-primary table-bordered-bd-primary" :id="'tabla_productoscompras'+row.mes">
                                    <thead>
                                        <tr>
                                            <th style="width: 18%;">Descripción</th>
                                            <th>Cantidad</th>
                                            <th>Costo</th>
                                            <th>Venta</th>
                                            <th class="text-center">Facturas</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="row1 in row.productos">
                                            <td style="width: 18%;">
                                                {{row1.producto}}
                                            </td>
                                            <td style="width: 18%;">
                                                {{row1.cantidad}}
                                            </td>
                                            <td class="text-right">{{ moneda(row1.costo, row1.div_locale, row1.div_simbolo) }}</td>
                                            <td class="text-right">{{ moneda(row1.venta, row1.div_locale, row1.div_simbolo) }}</td>
                                            <td style="width: 18%;">
                                                <span v-for="row2 in row1.facturas"><a :href="row2.uri">#FACC{{row2.correlativo}}</a></span>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    new Vue({
        el: '#AppprodComprasMes',
        data: {
            meses: [],
            mes: [01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12],
            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,
            v: [],
        },
        computed: {

        },
        created() {
            this.obtenerSucursalesEmpleado();
        },
        methods: {
            obtenerVentasMES() {
                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';
                for (let o = 0; o < this.mes.length; o++) {
                    if (o < 10) {
                        $("#tabla_productoscompras0" + this.mes[o]).DataTable().destroy();
                    } else {
                        $("#tabla_productoscompras1" + this.mes[o]).DataTable().destroy();
                    }
                }

                axios.get('ingresosegresos/productosVendidosComprasMes', {
                    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) {
                            for (let o = 0; o < this.mes.length; o++) {
                                Object.keys(response.data.meses).forEach((key, i) => {
                                    if (Number(key) == this.mes[o]) {
                                        this.meses.push(response.data.meses[key]);
                                        this.v.push(Number(key));
                                    }
                                });
                            }

                            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);
                                }
                            }
                        }
                    };

                    Object.keys(this.v).forEach((key, i) => {
                        if (this.v[key] < 10) {
                            $("#tabla_productoscompras0" + this.v[key]).DataTable({
                                order: [],
                                dom: 'Bfrtip',
                                buttons: [
                                    $.extend(true, {}, buttonCommon, {
                                        extend: 'excelHtml5',
                                        title: 'Ventas por meses del Año (' + this.anio + ')' +
                                            ' Divisa (' + selectedOptionDiv.text + ')',
                                    }),
                                ]
                            });
                        } else {
                            $("#tabla_productoscompras1" + this.v[key]).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_mescomp_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.v=[];
                this.meses=[];
                this.cargando_tabla = 'is-loading is-loading-lg';
                for (let o = 0; o < this.mes.length; o++) {
                    if (o < 10) {
                        $("#tabla_productoscompras0" + this.mes[o]).DataTable().destroy();
                    } else {
                        $("#tabla_productoscompras1" + this.mes[o]).DataTable().destroy();
                    }
                }

                axios.get('ingresosegresos/productosVendidosComprasMes', {
                    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) {
                            for (let o = 0; o < this.mes.length; o++) {
                                Object.keys(response.data.meses).forEach((key, i) => {
                                    if (Number(key) == this.mes[o]) {
                                        this.meses.push(response.data.meses[key]);
                                        this.v.push(Number(key));
                                    }
                                });
                            }

                            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);
                                }
                            }
                        }
                    };

                    Object.keys(this.v).forEach((key, i) => {
                        if (this.v[key] < 10) {
                            $("#tabla_productoscompras0" + this.v[key]).DataTable({
                                order: [],
                                dom: 'Bfrtip',
                                buttons: [
                                    $.extend(true, {}, buttonCommon, {
                                        extend: 'excelHtml5',
                                        title: 'Ventas por meses del Año (' + this.anio + ')' +
                                            ' Divisa (' + selectedOptionDiv.text + ')',
                                    }),
                                ]
                            });
                        } else {
                            $("#tabla_productoscompras1" + this.v[key]).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>