let addToCartApp = new Vue({
    el: '#addToCartApp',
    data: function () {
        return {
            store: cartStore,
            shippingCategory: null,
            parentCatalogId: null,
            childProducts: [],
            childAvailableProducts: [],
            childWaitingProducts: [],
            productsForCart: [],
            isSubmitting: false,
            isSubmittingForWaitingList: false,
            waitingProduct: {},
            waitingCustomerName: null,
            waitingCustomerEmail: null,
            waitingCustomerItems: [],
            showAjaxMessage: false,
            ajaxMessage: null,
            ajaxMessageClass: {},
        }
    },
    validations: {
        waitingCustomerName: {
            required
        },
        waitingCustomerEmail: {
            required,
            email
        },
        waitingCustomerItems: {
            required,
            minLength: minLength(1),
        }
    },
    computed: {
        hasStock: function(){
            if(this.childProducts.hasOwnProperty("length")){
                for(let i=0;i < this.childProducts.length;i++){
                    if(this.childProducts[i].hasOwnProperty("stock") && this.childProducts[i].stock > 0){
                        return true
                    }
                }
            }
        }
    },
    mounted: function () {
        this.shippingCategory = $('#shippingCategory').val();
        this.parentCatalogId = $('#parentCatalogId').val();
        $.get(`products/${this.parentCatalogId}/variations`, (payload) => {
            let items = []
            payload.child_products.forEach((item) => {
                item.payWithRewardPoints = false;
                item.qtyToAdd = 0;
                item.qtyAddedToCart = 0;
                item.addedToCartOn = 0;
                items.push(item);
            });
            let waiting_items = []
            let waiting_item_ids = []
            let available_items = []
            let all_child_items = []
            let product_gtag_list = []

            for (let i in items){
                if (items[i].stock < 1) {
                    waiting_items.push(items[i])
                    waiting_item_ids.push(parseInt(items[i].catalogid))
                }else {
                    available_items.push(items[i])
                }
            }

            // If there is no available item, display maximum 4 waiting items.
            // else, display only the available items.
            if(available_items.length < 1) {
                all_child_items = available_items.concat(waiting_items.slice(0,4))
            } else {
                all_child_items = available_items
            }

            for (let i in all_child_items) {
                let a = all_child_items[i]
                let a_price = a.onsale ? parseFloat(a.saleprice) : parseFloat(a.price)
                a_price = a_price.toFixed(2)

                product_gtag_list.push({
                    item_id: a.catalogid,
                    item_name: a.name,
                    item_brand: "Salt Water Fish",
                    item_category: a.category,
                    currency: 'USD',
                    value: a_price,
                })
            }

            try{
                setTimeout(() => {
                    gtag("event", "view_item", { currency: "USD", items: product_gtag_list, });
                }, 6000);
            } catch (e) {
                console.log(e.message)
            }

            try {
                dataLayer.push({ event: 'view_item', ecommerce: { items: product_gtag_list } });
            } catch (e) {
                console.log(e.message)
            }

            /* Sorting the array based on price */
            // for (let i in all_child_items) {
            //     let a = all_child_items[i]
            //     let price = a.onsale ? parseFloat(a.saleprice) : parseFloat(a.price)
            //     if(!(price in sorted_child_items)) {
            //         sorted_child_items[price] = [a]
            //     } else {
            //         sorted_child_items[price].push(a)
            //     }
            // }
            //
            // all_child_items = []
            // let keys = Object.keys(sorted_child_items).sort()
            // for (let i in keys) {
            //     all_child_items.concat( sorted_child_items[keys[i]] )
            // }

            // this.childProducts.concat(all_child_items)
            Vue.set(this, 'childProducts', all_child_items )
            Vue.set(this, 'childAvailableProducts', available_items )
            Vue.set(this, 'childWaitingProducts', waiting_items )

            /* Set the waiting products as selected by default*/
            Vue.set(this, 'waitingCustomerItems', waiting_item_ids )
        });
        localdb.getItem('customerData').then(result => {
            if (result) {
                this.waitingCustomerName = `${result.firstName} ${result.lastName}`;
                this.waitingCustomerEmail = result.email;
            }
        });
    },
    methods: {
        getPrefixedValue: function (value, prefix) {
            return String(prefix) + String(value)
        },
        getFormattedPrice: function (price) {
            let floatPrice = parseFloat(price);
            return floatPrice.toFixed(2);
        },
        incrementQty: function (item) {
            if (!item.shipping_category_key in this.store.state.shippingCategories) {
                alert('Shipping category for this product is not available. Please reload the page and try again.');
                return false;
            }

            let stock = parseInt(item.stock);

            if (isNaN(stock)) {
                stock = 0;
            }

            if (stock < 1) {
                $('#alertModal .modal-body').html(`${item.name} is not available in stock.`);
                $('#alertModal').modal('show');
                return false;
            }

            let qtyToAdd = parseInt(item.qtyToAdd);
            let newQty = qtyToAdd + 1;

            let minAllowedQty = item.minimumorder ? item.minimumorder : 1;
            let maxAllowedQty = item.maximumorder ? item.maximumorder : 99;

            let itemInCartStore = this.store.state.shippingCategories[item.shipping_category_key]['products'].find(loopItem => {
                return parseInt(loopItem.catalogid) === parseInt(item.catalogid);
            });

            if (itemInCartStore) {
                item.qtyAddedToCart = itemInCartStore.qtyAddedToCart;
                if (newQty + itemInCartStore.qtyAddedToCart > stock) {
                    $('#alertModal .modal-body').html(`Adding more ${item.name} will exceed the available stock.`);
                    $('#alertModal').modal('show');
                    return false;
                }

                if (newQty + itemInCartStore.qtyAddedToCart > maxAllowedQty) {
                    $('#alertModal .modal-body').html(`Cannot add more qty for ${item.name}.`);
                    $('#alertModal').modal('show');
                    return false;
                }
            } else {
                if (newQty < minAllowedQty) {
                    newQty = minAllowedQty;
                }

                if (newQty > stock) {
                    $('#alertModal .modal-body').html(`Adding more ${item.name} will exceed the available stock.`);
                    $('#alertModal').modal('show');
                    return false;
                }
                if (newQty > maxAllowedQty) {
                    $('#alertModal .modal-body').html(`Cannot add more qty for ${item.name}.`);
                    $('#alertModal').modal('show');
                    return false;
                }
            }

            item.qtyToAdd = newQty;
        },
        decrementQty: function (item) {
            if (!item.shipping_category_key in this.store.state.shippingCategories) {
                alert('Shipping category for this product is not available. Please reload the page and try again.');
                return false;
            }

            let qtyToAdd = parseInt(item.qtyToAdd);
            let newQty = qtyToAdd - 1;

            if (newQty < 0 || newQty < item.minimumorder) {
                item.qtyToAdd = 0;
            } else {
                item.qtyToAdd = newQty;
            }
        },
        addToCart: function () {
            this.productsForCart = [];
            let addedAnyItem = false;
            this.childProducts.forEach(item => {
                if (item.qtyToAdd > 0) {
                    item.addedToCartOn = new Date().getTime();
                    this.productsForCart.push(item);
                    addedAnyItem = true;
                }
            });

            if (!addedAnyItem) {
                $('#alertModal .modal-body').html('Please choose at least one item to add in your cart.');
                $('#alertModal').modal('show');
                return false;
            }

            this.isSubmitting = true;

            this.store.dispatch('CLEAR_LAST_ADDED_ITEMS', this.productsForCart);
            this.store.dispatch('CLEAR_LAST_DENIED_ITEMS', this.productsForCart);

            let allPromises = [];
            this.productsForCart.forEach(item => {
                let promise;
                allPromises.push(
                    new Promise((resolve, reject) => {
                        this.store.dispatch('SYNC_VENDOR', item).then(result => {
                            resolve('available');
                        }).catch(error => {
                            this.store.dispatch('ADD_LAST_DENIED_ITEMS', item);
                            reject('not available')
                        });
                    })
                )
            });

            Promise.all(allPromises).then(result => {
                let fb_items_addToCart = []

                this.productsForCart.forEach(item => {
                    this.store.dispatch('ADD_TO_CART', item);
                    this.store.dispatch('ADD_LAST_ADDED_ITEMS', item);
                    try{
                        gtag("event", "add_to_cart", {
                            currency: "USD",
                            value: String(item.price),
                            items: [{
                                item_id: String(item.catalogid),
                                item_name: String(item.name),
                                item_brand: "Salt Water Fish",
                                price: String(item.price),
                                quantity: String(item.qtyToAdd),
                            }],
                        });
                    } catch (e) {
                        console.log(e.message)
                    }
                    try {
                        ga('ec:addProduct', {
                            'id': String(item.catalogid),
                            'name': String(item.name),
                            'price': String(item.price),
                            'quantity': String(item.qtyToAdd),
                            'category': String(item.category)
                        });
                        ga('ec:setAction', 'add');
                        ga('send', 'event', 'Product', 'click');
                        ga('send', 'event', 'UX', 'click', 'add to cart');
                    } catch (err) {
                        console.log(err.message)
                    }

                    fb_items_addToCart.push({
                        'id': String(item.catalogid),
                        'quantity': String(item.qtyToAdd),
                        'name': String(item.name),
                    })
                });

                try {
                    fbq('track', 'AddToCart', {contents: fb_items_addToCart, content_type: 'product'});
                } catch (err) {
                    console.log(err.message)
                }

                if (this.store.state.lastAddedItems.length || this.store.state.lastDeniedItems.length) {
                    this.store.dispatch('FETCH_CATEGORY_SHIPPING_CHARGE', {shippingCategoryKey: this.shippingCategory}).then(result => {
                        this.store.dispatch('FETCH_CATEGORY_TAX', {shippingCategoryKey: this.shippingCategory}).then(result => {
                            localdb.setItem('cartStore', this.store.state).then(result => {
                                $.post('/cart-snapshot', {cart_store: JSON.stringify(this.store.state)});
                                this.isSubmitting = false;
                                $('#addToCartConfirmModal').modal('show');
                            });
                        });
                    });
                }
            }).catch(result => {
                this.isSubmitting = false;
                $('#addToCartConfirmModal').modal('show');
            });
        },
        showWaitingListModal: function(item) {
            this.waitingProduct = item;
            $('#waitingListModal').modal('show');
        },
        joinWaitingList: function() {
            this.showAjaxMessage = false;
            this.$v.$touch();
            if ($('.waitingCustomerEmailNewsletter').is(":checked")){
                this.waitingCustomerEmailNewsletter = true
            }else{
                this.waitingCustomerEmailNewsletter = false
            }
            if (!this.$v.$invalid) {
                this.isSubmittingForWaitingList = true;
                let formData = {
                    waitingProductIds: [],
                    waitingCustomerName: this.waitingCustomerName,
                    waitingCustomerEmail: this.waitingCustomerEmail,
                    waitingCustomerEmailNewsletter: this.waitingCustomerEmailNewsletter,
                    waitingParentCatalogId: this.parentCatalogId
                };
                if (this.waitingCustomerItems) {
                    formData['waitingProductIds'] = this.waitingCustomerItems;
                }
                formData['waitingProductIds'] = JSON.stringify(formData['waitingProductIds']);

                setTimeout(() => {
                    $.post('/waiting-products/create', formData, response => {
                        this.isSubmittingForWaitingList = false;

                        if (response.success) {
                            this.ajaxMessageClass = {
                                'alert': true,
                                'alert-brand-color-accent-secondary': true
                            }
                        } else {
                            this.ajaxMessageClass = {
                                'alert': true,
                                'alert-brand-color-accent-primary': true
                            }
                        }

                        if (response.message) {
                            this.ajaxMessage = response.message;
                            this.showAjaxMessage = true;
                        }
                    });
                }, 1000);
            }
        },
        handleKeyUp: function(item) {

        },
        selectUnselectWaitingItem: function(element_name, $event) {
            let element = $('input[name="'+element_name+'"]')

            //debugger;

            if($event) {
                if($event.target !== element[0]) {
                    element.prop( "checked", !element[0].checked );
                }
            }

            let newId = parseInt(element.val())

            if(element[0].checked) {
                if(!this.waitingCustomerItems.includes(newId)){          //checking weather array contain the id
                    this.waitingCustomerItems.push(newId);               //adding to array because value doesn't exists
                }else{
                    this.waitingCustomerItems.splice(this.waitingCustomerItems.indexOf(newId), 1);  //deleting
                }
            } else {
                if(this.waitingCustomerItems.includes(newId)) {
                    this.waitingCustomerItems.splice(this.waitingCustomerItems.indexOf(newId), 1);  //deleting
                }
            }

            // console.log(this.waitingCustomerItems, $event)

            Vue.set(this, 'waitingCustomerItems', this.waitingCustomerItems )
        },
        // clickWaitingItem: function($event) {
        //     let element = jQuery($event.target)
        //     element.prop( "checked", !element[0].checked );
        //     this.waitingCustomerItems.push(element.val())
        //
        //     console.log(element, element[0], element.val(), element.value, element[0].value)
        //
        //     Vue.set(this, 'waitingCustomerItems', this.waitingCustomerItems )
        //     // if(element.checked) {
        //     //     jQuery(element).removeAttr('checked');
        //     // } else {
        //     //     jQuery(element).attr('checked', 'checked');
        //     // }
        // }
    }
});

let addToCartConfirmApp = new Vue({
    el: '#addToCartConfirmApp',
    data: {
        store: cartStore
    },
    computed: {
        lastAddedItems: function () {
            return this.store.state.lastAddedItems;
        },
        lastDeniedItems: function () {
            return this.store.state.lastDeniedItems;
        },
        cartSubTotal: function () {
            return this.store.getters.cartSubTotal;
        },
        cartTotalItems: function () {
            return this.store.getters.cartTotalItems;
        },
        cartTotalQuantities: function () {
            return this.store.getters.cartTotalQuantities;
        },
        lastAddedItemsTotalQty: function() {
            let totalQty = 0;
            this.store.state.lastAddedItems.forEach(item => {
                totalQty += item.qtyToAdd;
            });
            return totalQty;
        },
        lastDeniedItemsTotalQty: function() {
            let totalQty = 0;
            this.store.state.lastDeniedItems.forEach(item => {
                totalQty += item.qtyToAdd;
            });
            return totalQty;
        }
    }
});

$('#addToCartConfirmModal').on('hidden.bs.modal', function () {
    addToCartApp.productsForCart.forEach(item => {
        item.qtyToAdd = 0;
    });
    $('#headerCartDropdown').addClass('animated tada');
});

$('#headerCartDropdown').on('animationend', function () {
    $('#headerCartDropdown').removeClass('animated tada');
});

$('#waitingListModal').on('hidden.bs.modal', function(e) {
    addToCartApp.waitingProduct = {};
    addToCartApp.showAjaxMessage = false;
    addToCartApp.$v.$reset();
});
