const defaultCustomItem = {
    name: '',
    customItem: true,
    size_price: '',
    strength: '',
    qty: '',
};

Vue.component('basketBuilderForm', {

    props: [
        'memberData',
        'parentId',
        'isInline',
        'events',
    ],

    data: function() {
        return {
            deliveryMethods: [],
            siteUrl: '',
            members: [],
            member: {},
            items: [],
            foundItems: [],
            memberQuery: '',
            itemQuery: '',
            errors: [],
            success: false,
            successText: '',
            itemsTotal: 0,
            deliveryMethodId: 0,
            orderId: 0,
            customItemMode: false,
            customItem: {},
            showMemberSearch: true,
            showBuilder: false,
            eventIndex: 0,
        };
    },

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

    watch: {
        memberData(member) {
            if (typeof member.id !== 'undefined') {
                this.selectMember(member);
                this.showMemberSearch = false;
            }
        },
        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 === 'initBasketBuilder') {
                    this.showBuilder = true;
                }
                if (event.name === 'hideBasketBuilder') {
                    this.showBuilder = false;
                }
            }
            // Update event index so that we don't process already processed events
            this.eventIndex = stack.length;
        }
    },

    methods: {
        init() {
            if (this.isInline) {
                this.showBuilder = true;
            }
            if (typeof this.memberData.id !== 'undefined') {
                this.selectMember(this.memberData);
                this.showMemberSearch = false;
            }
            let vm = this;
            this.$http.post('/plugins/BasketBuilder/admin/ajax.php', {
                action: 'init',
            }).then(function (response) {
                let data = JSON.parse(response.data);
                if (data.success) {
                    vm.deliveryMethods = data.deliveryMethods;
                    vm.siteUrl = data.siteUrl;
                    return;
                }
                vm.errors = data.errors;
            });
        },
        searchMembers() {
            let vm = this;
            vm.success = false;
            vm.successText = '';
            vm.orderId = 0;
            this.$http.post('/plugins/BasketBuilder/admin/ajax.php', {
                action: 'searchMembers',
                query: this.memberQuery,
            }).then(function (response) {
                let data = JSON.parse(response.data);
                if (data.success) {
                    vm.members = data.members;
                    return;
                }
                vm.errors = data.errors;
            });
        },

        searchItems() {
            let vm = this;
            vm.success = '';
            this.$http.post('/plugins/BasketBuilder/admin/ajax.php', {
                action: 'searchItems',
                query: this.itemQuery,
            }).then(function (response) {
                let data = JSON.parse(response.data);
                if (data.success) {
                    vm.foundItems = data.items;
                    vm.$nextTick(function () {
                        $(window).trigger('resize.overlay');
                    });
                    return;
                }
                vm.errors = data.errors;
            });
        },

        showCustomItem() {
            // Copy defaults
            this.customItem = Object.assign({}, defaultCustomItem);
            this.customItemMode = true;
        },

        addCustomItem() {
            let item = Object.assign({}, this.customItem);
            item.size = item.qty + 'x' + item.strength;
            this.selectItem(item);
            this.customItemMode = false;
        },

        amendQuantity(index, event) {
            this.items[index].quantity = parseInt(event.target.value);
            this.calculateTotals();
        },

        calculateTotals() {
            this.itemsTotal = 0;
            for (let i = 0; i < this.items.length; i++) {
                let price = this.items[i].size ?
                    this.items[i].size_price :
                    this.items[i].price;
                // Play with numbers a bit so that we don't get crazy decimals
                price = Math.round(price * 100);
                this.$set(this.items[i], 'total', price * this.items[i].quantity / 100);
                this.itemsTotal += price * this.items[i].quantity;
            }
            this.itemsTotal /= 100;
        },

        selectMember(member) {
            if (member.address_shipping === null) {
                member.address_shipping = {};
            }
            this.member = member;
            this.members = [];
            this.memberQuery = '';
        },

        selectItem(item) {
            item.quantity = 1;
            let items = this.items;
            items.push(item);
            this.$set(this, 'items', items);
            this.calculateTotals();
            this.clearItemSearch();
            $('#itemQuery').focus();
        },

        removeItem(index) {
            this.items.splice(index, 1);
            this.calculateTotals();
        },

        clearItemSearch() {
            this.itemQuery = '';
            this.foundItems = [];
        },

        submitBasket() {
            let vm = this;
            this.$http.post('/plugins/BasketBuilder/admin/ajax.php', {
                action: 'createBasket',
                items: this.items,
                memberId: this.member.id,
                deliveryMethodId: this.deliveryMethodId,
                shippingAddress: this.member.address_shipping,
                parentId: this.parentId,
            }).then(function (response) {
                let data = JSON.parse(response.data);
                if (data.success) {
                    vm.items = [];
                    vm.foundItems = [];
                    vm.member = {};
                    vm.members = [];
                    vm.success = true;
                    vm.orderId = data.order.id;
                    vm.successText = 'Basket and order created successfully!';
                    vm.emitEvent('orderCreated');
                    return;
                }
                vm.errors = data.errors;
            });
        },

        sendToMember() {
            let vm = this;
            this.$http.post('/plugins/BasketBuilder/admin/ajax.php', {
                action: 'sendToMember',
                orderId: this.orderId,
            }).then(function (response) {
                let data = JSON.parse(response.data);
                if (data.success) {
                    vm.successText = 'Payment link sent successfully!';
                    return;
                }
                vm.errors = data.errors;
            });
        },

        copyURL() {
            navigator.clipboard.writeText(this.siteUrl + '/shop/checkout/basket_overview.php?order_id=' + this.orderId);
        },
        emitEvent(name, data) {
            this.$parent.emitEvent(name, data)
        },
    },
});
