<template>
    <div class="container is-max-widescreen is-max-desktop animate__animated" :class="animation" v-show="!init">
        <pedidos-admin-dropdown-descargar :gdc="gdc"></pedidos-admin-dropdown-descargar>
        <table v-show="this.subpedidos.length !== 0" class="table is-fullwidth is-striped is-bordered">
            <thead>
                <tr>
                    <th>Núcleo</th>
                    <th><abbr title="Total a Pagar">Total $</abbr></th>
                    <th class="is-1"><abbr title="Aprobacion">Aprobación</abbr></th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <th></th>
                    <th>Total de los aprobados</th>
                    <th>$ {{ totalAprobados() }}</th>
                </tr>
            </tfoot>
            <tbody>
                <subpedido-row v-for="subpedido in this.subpedidos"
                               :subpedido="subpedido" :key="subpedido.id">
                </subpedido-row>
            </tbody>
        </table>
        <p class="has-text-centered" v-show="this.subpedidos.length === 0">
            Todavía no hay ningún pedido para administrar.
        </p>
    </div>
</template>

<script>
import SubpedidoRow from "./SubpedidoRow";
import PedidosAdminDropdownDescargar from "./PedidosAdminDropdownDescargar.vue";
export default {
    name: "PedidosAdminBody",
    components: {
        SubpedidoRow,
        PedidosAdminDropdownDescargar
    },
    data() {
        return {
            gdc: 0,
            subpedidos: [],
            dropdownActivo: false
        }
    },
    computed: {
        hayAprobados: function() {
            return this.subpedidos.filter(sp => sp.aprobado).length > 0
        }
    },
    beforeCreate() {
        axios.get("/admin/obtener_sesion").then(response => {
            this.gdc = response.data.gdc;
            this.fetchSubpedidos();
        });
    },
    methods: {
        fetchSubpedidos() {
            axios.get("/api/subpedidos/resources", {
                params: {
                    grupo_de_compra: this.gdc
                }
            }).then(response => {
                this.subpedidos = response.data.data
            });
        },
        totalAprobados() {
            let suma = 0;
            let aprobados = this.subpedidos.filter(sp => sp.aprobado);
            for (let i = 0; i < aprobados.length; i++) {
                suma += parseFloat(aprobados[i].total.replace(/,/g, ''));
            }
            return suma;
        }
    },
    mounted() {
        Event.$on('sync-aprobacion', (_) => {
            this.fetchSubpedidos();
        })
    }
}
</script>

<style>

</style>