Vue.component('patientOrders', {

    props: [
        'routes',
        'events',
    ],

    data: function() {
        return {
            orders: [],
            loading: false,
            errors: {},
            success: false,
            display: 3,
            eventIndex: 0,
        };
    },

    watch: {
        events(stack) {
            // Because there may be more than one event at a time, loop through new events
            for (let i = this.eventIndex; i < stack.length; i++) {
                let event = stack[i];
                if (event.name === 'orderCreated') {
                    this.load();
                }
            }
            // Update event index so that we don't process already processed events
            this.eventIndex = stack.length;
        }
    },

    mounted: function() {
        this.init();
    },

    computed: {
        canLoadMore() {
            if (!this.orders.length) {
                return false;
            }
            return this.orders.length > this.display;
        }
    },

    methods: {
        init() {
            this.load();
        },
        load() {
            this.loading = true;
            let vm = this;

            this.$http.post(this.routes['admin-member-orders-load'], [])
                .then((response) => {

                    const data = response.data;

                    vm.orders = data.orders;
                    vm.loading = false;
                    vm.emitEvent('ordersLoaded');
                    this.bindModals();
                });
        },
        addOrderAction(orderId) {
            this.emitEvent('initBasketBuilder', {
                orderId: orderId > 0 ? orderId : null,
            });
        },
        loadMore() {
            this.display += 10;
            this.emitEvent('ordersLoaded');
            this.bindModals();
        },
        addNoteAction(id) {
            this.emitEvent('initAddNote', {
                orderID: id,
            })
        },
        emitEvent(name, data) {
            this.$parent.emitEvent(name, data);
        },
        bindModals() {
            this.$nextTick(function () {
                $('.viewOrderButton').mtcOverlay({
                    onClose() {

                    },
                    onOpen() {

                    }
                });
            });
        }
    },
});
