var shoppingCart = new Vue({
    el: "#shoppingCart",
    data: {
        userId: 0,
        userIdentity: '',
        userToken: '',
        listLoading: true,
        listData: [],
        invalidData: [],
        promotionsList: [],
        kindCount: 0,
        totalCount: 0,
        totalPrice: 0,
        reducedPrice: 0,
        originalPrice: 0,
        allChecked: true,
        submitIds: [],//去结算商品Ids

    },
    watch:{
        listData: {
            handler: function() {
                console.log('obj.a changed');
            },
            immediate: true,
            deep: true
        }
    },
    methods: {
        getCartLists: function () {
            var _self = this;
            if(this.userId ===0){return;}
            tokenAjax("get", "/shoppingCart/list", {userId: this.userId},function (r) {
                if (r.code === 0 && r.data) {
                    _self.listData = r.data.list;
                    _self.invalidData = r.data.invalid;
                    _self.kindCount = r.data.kindCount;
                    _self.totalCount = r.data.totalCount;
                    _self.totalPrice = r.data.totalPrice;
                    _self.promotionsList = r.data.promotions;
                    // 默认全选
                    _self.listData.forEach(function(supplier){
                        supplier.checked = true;
                        if(supplier.cartList.length>0){
                            supplier.cartList.forEach(function(cartItem){
                                _self.submitIds.push(cartItem.productId);
                            })
                        }
                    });
                    _self.allChecked = true;
                    _self.computedPrice();
                }
                _self.listLoading = false;
            });
        },
        toggleThisLadder: function(event){
            var el = event.currentTarget;
            if($(el).hasClass("on")){
                $(el).removeClass("on").siblings('.mFixed').hide();
                if(!isPC){looseBody();}
            }else{
                $(el).addClass("on").siblings('.mFixed').show();
                if(!isPC){fixedBody();}
            }
        },
        hideThisLadder: function(event){
            var el = event.currentTarget;
            $(el).parents('.priceTag').find('.tag').removeClass("on").siblings('.mFixed').hide();
            if(!isPC){looseBody();}
        },
        ckeckSupplier: function(event, supplierChecked){
            var el = event.currentTarget;
            var _self = this;
            var cartList = $(el).parents('.supplierItem').find('input[name=cartList]');
            this.$nextTick(function(){
                if (supplierChecked) {
                    $.each(cartList, function (index, item) {
                        if (!_self.submitIds.includes(item.value*1)){
                            _self.submitIds.push(item.value*1);
                        }
                    });
                }else{
                    $.each(cartList, function (index, item) {
                        var loc = _self.submitIds.indexOf(item.value*1);
                        if(loc >=0 ){
                            _self.submitIds.splice(loc, 1);
                            _self.allChecked = false;
                        }
                    });
                }
                _self.computedPrice();
            });
        },
        ckeckAll: function(){
            var _self = this;
            this.$nextTick(function(){
                if (_self.allChecked) {
                    _self.submitIds = [];
                    _self.listData.forEach(function(supplier){
                        supplier.checked = true;
                        if(supplier.cartList.length>0){
                            supplier.cartList.forEach(function(cartItem){
                                _self.submitIds.push(cartItem.productId);
                            })
                        }
                    });
                }else{
                    _self.submitIds = [];
                    _self.listData.forEach(function(supplier){
                        supplier.checked = false;
                    });
                }
                _self.computedPrice();
            });
        },
        setPromotions:function(){
            var _self = this;
            this.promotionsList.forEach(function(promotions){
                promotions.productList.forEach(function(product){
                    _self.listData.map(function(supplier){
                        supplier.cartList.map(function(cart){
                            if(product.productId === cart.productId){
                                product.number = cart.number
                            }
                        });
                    });
                });
            });
        },
        computedPrice: function(){
            var _self = this;
            this.$nextTick(function(){
                var originalPrice = 0;
                var reducedPrice = 0;
                var totalPrice = 0;
                var kindCount = 0;
                var totalCount = 0;
                _self.listData.forEach(function(supplier){
                    var supplierOriginalPrice = 0;
                    var supplierPrice = 0;
                    if(supplier.cartList.length>0){
                        supplier.cartList.forEach(function(cart){
                            if (_self.submitIds.includes(cart.productId*1)){
                                supplierOriginalPrice += cart.originalPrice*cart.number;
                                supplierPrice += cart.price*cart.number;
                                kindCount += 1;
                                totalCount += cart.number;
                            }
                        })
                    }
                    supplier.originalPrice = supplierOriginalPrice;
                    originalPrice += supplier.originalPrice;
                    supplier.totalPrice = supplierPrice;
                    totalPrice += supplier.totalPrice;
                });
                _self.promotionsList.forEach(function(promotions){
                    if(promotions.mode ===2){
                        var promotionsPrice = 0;
                        promotions.productList.forEach(function(product){
                            promotionsPrice += product.number * product.price;
                        });
                        if(promotionsPrice>=promotions.touchPrice){
                            reducedPrice += promotions.reducedPrice;
                            totalPrice -= promotions.reducedPrice;

                        }
                    } else if (promotions.type===1 && promotions.mode ===1) {
                        promotions.productList.forEach(function(product){
                            reducedPrice += product.number * (product.originalPrice - product.price);
                        });
                    }
                });
                _self.reducedPrice = reducedPrice;
                _self.originalPrice = originalPrice;
                _self.totalPrice = totalPrice;
                _self.kindCount = kindCount;
                _self.totalCount = totalCount;
            });
        },
        cartNumberSub: function(cart){
            cart.number -= cart.step;
            if (cart.number<cart.min){
                cart.number = cart.min;
            }
            this.numberChange(cart);
        },
        cartNumberAdd: function(cart){
            cart.number += cart.step;
            if (cart.number>cart.stock){
                cart.number = cart.stock;
            }
            this.numberChange(cart);
        },
        cartNumberChange: function(cart){
            cart.number = Math.ceil(cart.number/cart.step)*cart.step;
            this.numberChange(cart);
        },
        numberChange: function(cart){
            if(cart.ladderFlag){
                cart.ladderPrices.forEach(function(ladder){
                    if(cart.number>=ladder.buyNum){
                        cart.price = ladder.buyPrice;
                        cart.originalPrice = ladder.buyPrice;
                    }
                });
            }
            // 设置优惠数量
            this.setPromotions();
            // 计算价格
            this.computedPrice();
            // 更新购物车
            var _self = this;
            this.$nextTick(function(){
                _self.updateCart(cart);
            });
        },
        updateCart: function(cart){
            tokenAjax("post", "/shoppingCart/update", {
                userID: this.userId,
                productID: cart.productId,
                productCount: cart.number
            },function (res) {
                console.log(res);
            });
        },
        deleteCart: function(productIds){
            var _self = this;
            alertInfo("确定要删除该商品？",function(){
                // 删除逻辑
                tokenAjax("post", "/shoppingCart/delete", {
                    userID: _self.userId,
                    productIDs: productIds
                },function (res) {
                    window.location.reload();
                });
            })
        },
        deleteSelected: function(){
            var productIds = this.submitIds.join(",");
            this.deleteCart(productIds);
        },
        submitCart: function(){
            if (this.submitIds.length>0){
                var productIds = this.submitIds.join(",");
                window.localStorage.setItem("shoppingProductIds", productIds);
                // type:（1购物车提交[对应表cm_cart]，2直接购买提交, 3协销下单）
                window.location.href = '/shopping/confirm.html?type=1';
            }
        }
    },
    created: function () {
        if(globalUserData){
            this.userId = globalUserData.userId;
            this.userIdentity = globalUserData.identity;
            this.userToken = globalUserData.token;
        }
        // 获取列表数据
        this.getCartLists();
    },
    mounted: function () {
        var _self = this;
        var minAwayBtm = $("footer").height();
        //处理滚动条控制底部提交fixed
        $(window).scroll(function() {
            var awayBtm = $(document).height() - $(window).scrollTop() - $(window).height();
            if(minAwayBtm <= awayBtm){
                $(".summaryWrap").addClass('fixed');
            }else{
                $(".summaryWrap").removeClass("fixed");
            }
        });
    }
});
