<template>
    <h3>Recent Orders - {{ customer.acc_no }} {{ customer.name }}</h3>
    <v-progress-linear color="blue" :active="orders_loading" indeterminate>
    </v-progress-linear>
    <v-container>
        <v-row>
            <v-col cols=4 v-for="item in sortedOrders" :key="item.id">
                <v-card>
                    <v-card-title>
                        Order: {{ item.doc_no }}
                    </v-card-title>
                    <v-card-subtitle>
                        {{ formatDate(item.doc_date,"DD/MM/YYYY") }}
                    </v-card-subtitle>
                    <v-card-text>
                        <v-list>
                            <v-list-item v-for="(i, index) in item.products" :key="index" style="border-bottom: 1px dotted #000;">
                                {{ i.code }} - {{ i.name }} x {{ i.quantity }}
                            </v-list-item>
                        </v-list>
                    </v-card-text>
                </v-card>
            </v-col>
        </v-row>
    </v-container>
</template>
<script>
import axios from 'axios'
import Customer from '@/types/CustomerType.vue'
import methods from '@/CommonMethods.vue'
export default {
    props:{
        customer: new Customer()
    },
    watch: {
        customer() {
            this.getCustomerRecentOrders(this.customer.acc_no)
        }
    },
    mixins: [methods],
    data() {
        return {
            orders_loading: false,
            orders: []
        }
    },
    computed: {
        sortedOrders() {
            let sorted = this.orders
            sorted.sort((a, b) => {
                if (a.doc_date < b.doc_date){
                    return 1
                }
                if (a.doc_date > b.doc_date){
                    return -1
                }
                return 0
            })
            return sorted
        }
    },
    methods: {
        getCustomerRecentOrders(acc_no){
            this.orders_loading = true
            let url = this.$api_url + "/customers/" + acc_no + "/orders/recent"
            axios.get(url)
                .then(resp => {
                    this.orders = resp.data
                })
                .catch(err => {
                    console.log(err)
                })
                .finally(() => {
                    this.orders_loading = false
                })

        }
    }
}
</script>
