<template>
    <div>
        <Table :columns="columns" :border="true" :data="data" :loading="loading"/>
        <Page @on-change="retrieveProducts" :total="pagination.total" style="margin-top:10px;"/>
    </div>
</template>

<script>
    export default {
        name: 'ProductsList',
        mounted() {
            this.retrieveProducts();
        },
        data() {
            return {
                columns: [
                    {
                        title: 'Nazwa',
                        key: 'name'
                    },
                    {
                        title: 'Kcal',
                        key: 'kcal'
                    },
                    {
                        title: 'Węglowodany (g)',
                        key: 'carbohydrates'
                    },
                    {
                        title: 'Białk (g)',
                        key: 'protein'
                    },
                    {
                        title: 'Tłuszcz (g)',
                        key: 'fat'
                    }
                ],
                data: [],
                pagination: {
                    total: 0
                },
                loading: true,
            };
        },
        methods: {
            retrieveProducts(page = 1) {
                this.loading = true;
                this.$axios.get('/product', {
                    params: {
                        page: page
                    }
                })
                    .then((res) => {
                        let data = res.data.data.products;
                        let products = data.data;
                        let pagination = {
                            'current_page': data.current_page,
                            'per_page': data.per_page,
                            'total': data.total
                        };
                        this.data = products;
                        this.pagination = pagination;
                        this.loading = false;
                    })
                    .catch(() => {
                        this.loading = false;
                        this.$Message.error('Błąd!');
                    });
            }
        }
    };
</script>
