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
        }
    },
    filters: {
        NumFormat: function (text) {//处理金额
            return Number(text).toFixed(2);
        }
    },
    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();}
        },
        ckeckItem: function(event){
            var el = event.currentTarget;
            if(!$(el).prop("checked")){
                $(el).parents('.supplierItem').find('.supplierTit').find('input.check').prop("checked", false);
            }
            this.computedPrice();
        },
        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 totalPrice = 0;
                var reducedPrice = 0;
                var originalPrice = 0;
                var kindCount = 0;
                var totalCount = 0;
                _self.listData.forEach(function(supplier){
                    var supplierPrice = 0;
                    var supplierReducedPrice = 0;
                    if(supplier.cartList.length>0){
                        supplier.cartList.forEach(function(cart){
                            if (_self.submitIds.includes(cart.productId*1)){
                                supplierPrice += cart.price*cart.number;
                                kindCount += 1;
                                totalCount += cart.number;
                                // 单品满减
                                if(cart.promotions && cart.promotions.type*1===1 && cart.promotions.mode*1===2){
                                    // 单品满减-重新计算供应商总价/满减金额
                                    if(cart.price*cart.number >= cart.promotions.touchPrice){
                                        supplierPrice -= cart.promotions.reducedPrice;
                                        supplierReducedPrice += cart.promotions.reducedPrice;
                                    }
                                }
                            }
                        });
                        // 店铺满减
                        if(supplier.promotions && supplier.promotions.mode*1===2){
                            // 店铺满减-计算供应商总价/满减金额
                            if(supplierPrice >= supplier.promotions.touchPrice){
                                supplierPrice -= supplier.promotions.reducedPrice;
                                supplierReducedPrice += supplier.promotions.reducedPrice;
                            }
                        }
                    }
                    supplier.totalPrice = supplierPrice;
                    supplier.reducedPrice = supplierReducedPrice;
                    supplier.originalPrice = (supplierPrice+supplierReducedPrice);
                    totalPrice += supplier.totalPrice;
                    reducedPrice += supplier.reducedPrice;
                    originalPrice += supplier.originalPrice;
                });
                // 总促销计算
                _self.promotionsList.forEach(function(promotions){
                    // 凑单满减
                    if(promotions.mode*1===2 && promotions.type*1===2){
                        var total = 0;
                        promotions.productList.forEach(function(product){
                            if (_self.submitIds.includes(product.productId*1)){
                                total += product.number * product.price;
                            }
                        });
                        if(total>=promotions.touchPrice){
                            totalPrice -= promotions.reducedPrice;
                            reducedPrice += promotions.reducedPrice;
                        }
                    }
                });
                _self.totalPrice = totalPrice;
                _self.reducedPrice = reducedPrice;
                _self.originalPrice = originalPrice;
                _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;
            ShoppingApi.DeleteCartProducts({userID:_self.userId,productIDs:productIds},function(response){
                if(response.code === 0){
                    CAIMEI.dialog('删除成功',true,function () {
                        _self.getCartLists();
                    })
                }else{
                    CAIMEI.Alert(response.msg,'确定',true, function(){});
                }
            })
        },
        deletefailureList:function(){
            var _self = this;
            var delGoodsList='';
            _self.invalidData.forEach(function(item){
                delGoodsList+= item.productId+','
            });
            CAIMEI.Modal('确定清空全部失效商品吗？','取消','确定',function(){
                _self.deleteCart(delGoodsList)
            });
        },
        deleteCartOne:function(productIds){
            var _self = this;
            CAIMEI.Modal('确定删除该商品吗？','取消','确定',function(){
                _self.deleteCart(productIds);
            });
        },
        deleteSelected: function(){
            var _self = this;
            var productIds = _self.submitIds.join(",");
            if(productIds == ''){
                CAIMEI.dialog('请选择要删除的商品~');
                return false;
            }
            CAIMEI.Modal('确定删除选中的商品吗？','取消','确定',function(){
                _self.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");
            }
        });
    }
});
