var productDetail = new Vue({
    el: "#productDetail",
    data: {
        productId: 0,
        userId: 0,
        userIdentity: '', //2-会员机构；3-供应商；4-普通机构
        userToken: '',
        images: [],
        price: 564,
        priceFlag: 2,
        recommendType: 1,
        recommendPage: 1,
        recommends: [],
        parameters: [],
        isShow:false,
        ladderList:[],//阶梯价
        deailData:{},
        promotions:{},//促销活动信息
        recommde:false,
        recommdeindex:0,
        number:0,
        minBuyNumber:0,
        buyRetailPrice:0,
        allTotalPrice:0,
        typedata:0,
        promotionsId:0,//活动商品id
        giftData:[],//赠品
        isQuantity:false,
        isStock:false,
        cartAlert:false

    },
    computed: {},
    methods: {
        getImages: function(){
            var _self = this;
            if(this.productId ===0){return;}
            $.getJSON(spiServer + "/product/detail/images",{productId: this.productId}).done(function (r) {
                if (r.code === 0 && r.data) {
                    _self.images = r.data;
                    setTimeout(function(){
                        if (isPC) {
                            var magnifier = new ImageMagnifier(
                                '#imgShown .smallImage li'
                                ,'#imgShown .bigImage'
                                ,'#imgShown .zoomImage'
                                ,'#imgShown .mask'
                                ,'#imgShown .zoom'
                                ,"on"
                            ).init();
                        } else {
                            var swiper = new Swiper('#swiperImage', {
                                loop : true,
                                autoplay: {
                                    delay: 2000,
                                    disableOnInteraction: false
                                },
                                pagination: {
                                    el: '.swiper-pagination',
                                    type: 'fraction'
                                }
                            });
                        }
                    },500);
                }
            });
        },
    toLogin:function() {
    location.href ='/login.html';
   },
        productDetail:function(){
         var _self = this;
            if(_self.productId ===0){return;}
            $.getJSON(spiServer + "/product/detail/price",{
                // userId:this.userId,
                // productId: this.productId
                userId:10684,
                productId: _self.productId
            }).done(function (r) {
                if (r.code === 0 && r.data) {
                _self.priceFlag = r.data.priceFlag;
                _self.number = r.data.minBuyNumber;//最小起訂量
                _self.buyRetailPriceStep = r.data.step;
                _self.minBuyNumber = r.data.minBuyNumber;
                _self.buyRetailPrice = r.data.price;
                    console.log(r)
                    if(r.data.ladderPriceFlag==1){
                        _self.ladderPrice();
                     }else {
                        _self.allTotalPrice = _self.number * _self.deailData.price;
                     }
                   _self.deailData =r.data;
                    if(_self.deailData.actStatus==1){
                    _self.promotions =  _self.deailData.promotions;
                    _self.promotionsId = _self.deailData.promotions.id;
                     _self.promotionsProduct();
                    }

                }
            });
        },
        changeCountAdd:function () { //数量增加按钮
        var _this = this;
            if(_this.buyRetailPriceStep == 2){
					_this.number += _this.minBuyNumber
				}else{
					_this.number++
				}
				_this.allTotalPrice = _this.number * _this.deailData.price;
				_this.calculatPerice()
        },
        changeCountSub:function(){//popup弹窗数量减按钮
           var _this = this;
				if(_this.number<=_this.minBuyNumber){
					_this.number= _this.minBuyNumber;
					_this.isQuantity =true;
					 layer.tips('此商品最小起批量为' + _this.minBuyNumber, $(this).parent().find(".calc-input"), {
                        tips: 1,
                        time: 3000
                         });
					return
				}else{
					if(_this.buyRetailPriceStep == 2){
						_this.number-=_this.minBuyNumber
					}else{
						_this.number--
					}
					_this.allTotalPrice = _this.number * _this.deailData.price;
					_this.calculatPerice();
					_this.isQuantity =false
				}
			 },
			 changeNumber:function(e){
			   var  _this=this;
				var _value = e.detail.value;
				if(!_value){
					_this.number = _this.minBuyNumber
				}else if(_value < _this.minBuyNumber){
					_this.layer.msg('该商品最小起订量为'+_this.minBuyNumber,2000);
					_this.number = _this.minBuyNumber
				}else if( _value % _this.minBuyNumber !=0 ){
					_this.layer.msg('购买量必须为起订量的整数倍',2000);
					_this.number = _this.minBuyNumber
				}else{
					_this.number = e.detail.value;
					_this.allTotalPrice = _this.number * _this.deailData.price;
					_this.calculatPerice();
				}
			},
        calculatPerice:function(){//判断是否为阶梯价然后做计算价格处理
              var _this = this;
				if(_this.deailData.ladderPriceFlag == '1'){
					_this.ladderList.forEach(function (item,index) {
						if(_this.number>=item.buyNum){
							_this.buyRetailPrice = item.buyPrice
							_this.allTotalPrice = _this.number*item.buyPrice
						}
					})
				}else{
					_this.buyRetailPrice = _this.deailData.price;
				}
			},
		addShopCart:function(){ //加入购物车
			    var _this = this;
               $.getJSON(spiServer + "/shoppingCart/addCart",{
                        productID: _this.productId,
                        userID: _this.userId,
                        productCount: _this.number,
                   }).done(function (res) {
                          if(res.code==0){
                                _this.cartAlert = true;
                                _this.typedata = res.data;//商品种数
                            }else {

                                _this.cartAlert = false;
                            }
                })
                // request.addCart(params,function (res) {
                //         if(res.code==0){
                //             _this.cartAlert = true;
                //             _this.typedata = res.data;//商品种数
                //         }else {
                //
                //             _this.cartAlert = false;
                //         }
                // })
			},
		buyShopCart:function(){//立即购买
			    var _this = this;
                var productid = _this.productId;
                    allCount =  _this.number;
                var confirmorder ={
                        allPrice:_this.allTotalPrice,
                        productID:productid,
                        productCount:allCount,
                        type:1
                    };
                   _util.setStorageItem('confirmGoodsInfo',JSON.stringify({data:confirmorder}));
                    window.location.href = '/order/confirmOrder.jsp?type=1';
			},
		Continueshop:function(){ //继续购物
			 var _this = this;
			    _this.cartAlert = false;
			     location.reload()
			},
			settlement:function(){//去结算
			   window.location.href = "/shopping/cart.html"
			},
        getRecommends: function(){
            var _self = this;
            if(this.productId ===0){return;}
            $.getJSON(spiServer + "/product/detail/recommend",{
                productId: this.productId,
                recommendType: this.recommendType
            }).done(function (r) {
                if (r.code === 0 && r.data) {
                    // _self.recommendPage = Math.ceil(r.data.length / 7);
                    if(r.data.length > 0){
                        _self.recommends = r.data;
                        _self.recommde =true;
                    }else {
                       _self.recommde =false;
                    }
                    if(r.data.length<7){
                        var length = 7-r.data.length;
                        _self.recommdeindex = length;
                    }else {
                        var remainderres=r.data.length%7;
                         _self.recommdeindex= 7-remainderres;
                    }
                }
            });
        },
        ladderPrice:function(){
            var _self = this;
            if(this.productId ===0){return;}
            $.getJSON(spiServer + "/product/ladderPrice",{
                productId: this.productId
            }).done(function (r) {
                if (r.code === 0 && r.data) {
                    console.log(r)
                   _self.ladderList =r.data;
                   _self.ladderList.forEach(function (item,index) {
						if(_self.number>=item.buyNum){
							_self.buyRetailPrice = item.buyPrice
							_self.allTotalPrice = _self.buyRetailPrice*_self.number;
						}
					})

                }
            });
        },
        clubupgrade:function(){
            location.href='/myAccount/club/clubupgrade.jsp'
        },
        getParameters: function(){
            var _self = this;
            if(this.productId ===0){return;}
            $.getJSON(spiServer + "/product/detail/parameter",{
                productId: this.productId
            }).done(function (r) {
                if (r.code === 0 && r.data) {
                    _self.parameters = r.data;
                }
            });
        },
        activity:function () {
           var _this = this;
           _this.isShow = !_this.isShow;
        },
        activeBtn:function () {
           var _this = this;
            _this.isShow = false;
        },
        promotionsProduct:function () {//赠品接口
            var _self = this;
            if(_self.promotionsId ===0){return;}
            $.getJSON(spiServer + "/product/promotions/gifts",{
                promotionsId: _self.promotionsId
            }).done(function (r) {
                if (r.code === 0 && r.data) {
                    console.log(r)
                    _self.giftData = r.data;
                }
            });
        }
    },
    created: function () {
        this.productId = getUrlParam("id") ? getUrlParam("id")*1 : 0;
        var userInfo = localStorage.getItem('userInfo');
        if(userInfo){
            this.userId = JSON.parse(userInfo).userId*1;
        }
        this.getImages();
    },
    mounted: function () {
        this.productDetail();
        this.getRecommends();
        $('.productInfo').slide({
            mainCell:".tabCon"
            ,titCell:".tabTit span"
            ,trigger: "click"
        });
        if(globalUserData){
           console.log(globalUserData)
            globalUserData.userId ? globalUserData.userId : globalUserData.userID;
            this.userIdentity = globalUserData.identity ? globalUserData.identity : globalUserData.userIdentity;
            this.userToken = globalUserData.token;
        }
         //相關推薦輪播
        var mySwiper = new Swiper('#productRecommend',{
                slidesPerView: 7,
                spaceBetween: 12,
                slidesPerGroup: 7,
                autoplay: {
                    delay:10000,
                    disableOnInteraction: false,//是否禁止autoplay。默认为true：停止。
                },
                loop: false,
                observer: true, //修改swiper自己或子元素时，自动初始化swiper
                observeParents: true, //修改swiper的父元素时，自动初始化swiper
                pagination: {
                    el: '.swiper-pagination',
                    clickable: true,
                },
                on:{
                    init:function() {
                        var length = this.slides.length;
                        if(length < 8) {
                            this.autoplay.stop();
                        }
                    }
                }
       })

    }
});
