var e = getApp(), r = e.request,rq=r,t = require("../../../../utils/util.js"), o = require("../../../../utils/common.js"),oo=e.globalData,os=oo.setting;
var regeneratorRuntime = require('../../../../utils/runtime.js');
var ut= require('../../../../utils/util.js');
var py = require("../../../../utils/pay.js");


Page({
    data: {
        url: os.url,
        resourceUrl: os.imghost,
        iurl: os.imghost,
        order: null,
        optionIsGoup: !1,
        user_note: "",
        conf:null,
    },
    onLoad: function(e) {
        var th=this;
        var r = void 0 !== e.isGoup && e.isGoup;
				// console.log('e*************>>>>>>', e);
				this.data.group_id = e.group_id;
        getApp().getConfig2(function (e) {
			
            th.setData({conf: e,sales_rules:e.sales_rules, userInfo: getApp().globalData.userInfo});
            //--- 看后台是不是有开通等级卡 ---
            if(e.switch_list){
            	    var s_list=JSON.parse(e.switch_list);
									th.setData({sys_switch: s_list});
					var is_open_offline=s_list.is_pricing_open;
                    var user=getApp().globalData.userInfo;
                   //如果后台有开启等级价的功能
            	   if(parseInt(s_list.rank_switch)==2 && user['card_expiredate']){
            		   var str = user['card_expiredate'].replace(/-/g, '/');
            		   var end = new Date(str);
            		   end = Date.parse(end) / 1000;
            		   var now = ut.gettimestamp();					   							  
            		   //--- 判断是等级会员，且在有效期范围内 ---
            		   if(user.card_field && now<end){
            			   th.setData({card_field:user.card_field})
            		   }	   
            	   }
				   //-- 判断有没有过期 --
				   getApp().request.promiseGet("/store/storemoduleendtime/page?store_id=" +os.stoid + "&type=6",{}).then(res=>{
				   		  //未购买
				   		  if(res.data.code!=0 || !res.data.data || !res.data.data.pageData || !res.data.data.pageData.length){
				   			 is_open_offline=0; 
				   		  }else{
							 //已经过期
							 var item=res.data.data.pageData[0];
							 if(item.end_time<ut.gettimestamp()){
							 	 is_open_offline=0;
							 } 
						  }
				   		  
				   		  th.data.is_open_offline=is_open_offline;
				   })
				   
            }	
        },1)

        this.setData({
						team_status: e.team_status,
            optionIsGoup: r,
        }), this.requestOrderDetail(e.order_id), wx.removeStorageSync("order:order_detail:update");
    },
    onShow: function() {

         var fy=ut.fy_back('/pages/user/order_list/order_list',1);
         if(fy) return false;
         py.set_fir();

        wx.getStorageSync("order:order_detail:update") && (wx.removeStorageSync("order:order_detail:update"), 
        this.requestOrderDetail(this.data.order.order_id));
    },
    requestOrderDetail: function(e) {
        var o = this,oid=e,th=this;
        r.get(o.data.url + "/api/weshop/order/get/"+os.stoid+"/"+e, {
            success: function(e) {
                var r = e.data.data;
                r.addTimeFormat = t.format(r.add_time);
                if (r.order_status == 0 && r.pay_status==0 ){
                    r.order_status_detail="待支付"; r.pay_btn=1;
                }
                if (r.order_status == 1 && r.pay_status == 1 && r.shipping_status== 0)
                {
                  //自提的话
                  if (r.exp_type==1)
                  {
                   r.order_status_detail = "待自提";
                  }
                  else
                  {
                    r.order_status_detail = "待发货";
                  }
                }
               
                if (r.order_status == 1 && r.pay_status == 1 && r.shipping_status == 1){
                    r.order_status_detail = "待收货";r.receive_btn=1;
                    if (r.exp_type == 0) r.shipping_btn=1;
                }
                if (r.order_status == 1 && r.pay_status == 1 && r.shipping_status == 2){
                  r.order_status_detail = "待收货"; r.receive_btn = 1;
                  if (r.exp_type == 0) r.shipping_btn = 1;
                }
                if (r.order_status == 2){
                   r.order_status_detail = "待评价"; if (r.exp_type == 0) r.shipping_btn = 1;
                }
                if (r.order_status == 3)
                   r.order_status_detail = "已取消";
                if (r.order_status == 4){
                  r.order_status_detail = "已完成"; if (r.exp_type == 0) r.shipping_btn = 1;
                }
                if (r.order_status == 5)
                   r.order_status_detail = "已作废";
                if (r.order_status == 6)
                  r.order_status_detail = "退款完成";
				if (r.pt_status == 1 && r.pt_prom_id>0)
				  r.order_status_detail = "组团中";  
				 

              r['is_all_return'] = 0;

               //------获取订单商品-------
               rq.get("/api/weshop/ordergoods/list",{
                    data: { store_id: os.stoid, order_id: oid},
                    success:async function (eb) {
                         r.order_goods=eb.data.data.pageData;
                         var glist =  r.order_goods;
                         for(var i in glist){
                            if(glist[i].is_gift){
                                r.is_prom=1;
                            }
                         }

                          //------------对比一下有没有退款记录------------
                          await getApp().request.promiseGet("/api/weshop/order/returngoods/page",{
                              data: { order_id: r.order_id, store_id: os.stoid,
                                  user_id:oo.user_id, pageSize: 20 }
                          }).then(rs=>{
                              var ttd=rs;
                              //--看一下订单的总数量--
                              var gtype_num = r.order_goods.length;
                              if(ttd.data.data.pageData == undefined) return false;
                              var goodslist = r.order_goods;

                              //----没有相关的退款记录----
                              if (ttd.data.data.total==0){
                                  r['is_all_return'] = 0;

                                  goodslist.forEach(function (ee, ii) {
                                      if (r['order_status'] == 1 && r['pay_status'] == 1 && gtype_num>1){
                                          //是不是可以单个商品退款
                                          if(th.check_for_return_btn(r) ) {
                                              goodslist[ii]['return_btn']=1;
                                          }
                                      }
                                  });
                              }else{
                                  //--------整单退--------
                                  if (ttd.data.data.pageData[0]['goods_id_list'] != null
                                      && ttd.data.data.pageData[0]['goods_id_list'] != ''){


                                      var eea = ttd.data.data.pageData[0];
                                      //1.退款正在进行中，
                                      //2.退款被拒绝就要显示可以退款
                                      //3.退款已经完成
                                      r['is_all_return']=1;
                                      r['is_all_return_status'] = ttd.data.data.pageData[0].status;

                                      if (r['order_status'] == 1 && r['pay_status'] == 1) {
                                          switch (eea.status) {
                                              case 0:
                                              case 1:
                                                  r.order_status_detail="退款中";
                                                  r['return_btn'] = 2; break;
                                              case 2:
                                                  r.order_status_detail="退款完成";
                                                  r['return_btn'] = 4; break;
                                              case 3:
                                                  r['return_btn'] = 3; break;
                                              default:
                                                  r['return_btn'] = 0;
                                          }
                                      }
                                  }else{
                                      //1.退款正在进行中，
                                      //2.退款被拒绝就要显示可以退款
                                      //3.退款已经完成
                                      r['is_all_return'] = 0;
                                      var rt_ok_num=0;

                                      //if(r['order_status'] == 1 && r['pay_status'] == 1) {
                                          goodslist.forEach(function (eeb, iii) {
                                              if(r['order_status'] == 1 && r['pay_status'] == 1)
                                                  goodslist[iii]['return_btn'] = 1; //申请退款
                                              ttd.data.data.pageData.forEach(function (eea, ii) {
                                                  var st = eea.status;
                                                  if (eea.goods_id == eeb.goods_id){

                                                      switch (eea.status){
                                                          case 0:
                                                          case 1://退款处理中
                                                              r['has_rt'] = 1; //有部分退
                                                              goodslist[iii]['return_btn'] = 2; break;
                                                          case 2://退款完成
                                                              r['has_rt'] = 1; //有部分退
                                                              goodslist[iii]['return_btn'] = 4;rt_ok_num++; break;
                                                          case 3://已拒绝，重新退款
                                                              goodslist[iii]['return_btn'] = 3; break;
                                                          default:
                                                              if(r['order_status'] == 1 && r['pay_status'] == 1)
                                                                   goodslist[iii]['return_btn'] = 1; //申请退款
                                                      }
                                                      return;
                                                  }
                                              });
                                          });
                                      //}
                                  }
                              }

                              //--如果是全部退款，也就可以删除--
                              if(rt_ok_num==goodslist.length){
                                  r['is_all_return_status']=2;
                              }
                              r['order_goods'] = goodslist;
                              var g_num = 0;
                              goodslist.forEach(function (ee, ii) {
                                  if(ee.return_btn!=4)
                                     g_num += ee.goods_num;
                              });
                              r['g_num'] = g_num;
                          })


                      //--------获取门店-----------
                      rq.get("/api/weshop/pickup/get/" + os.stoid + "/" + r.pickup_id, {
                           success: function (ebb) {
                                r.pickname = ebb.data.data.pickup_name;
                                o.setData({
                                  order: r,
                                });
                           }
                      })


                    }
                })               
            }
        });
    },
    /*-----联系客户------*/
    contactService: function() {
        getApp().con_Service();
    },

    //--------取消订单---------
    cancelOrder: function(e) {
      var t = this,th=t, o = e.currentTarget.dataset.id,order=this.data.order;
      var is_skill=0;
      var order_goods=order.order_goods;
      var is_zsorder=order.is_zsorder;

      //--判断是不是秒杀--
      order_goods.forEach(function (val,ind) {
        if(val.prom_type==1){
          is_skill=1; return false;
        }
      })

        wx.showModal({
            title: "是否取消订单？",
            success: function(e) {
              if(!e.confirm) return false;
              //如果是秒杀和拼单的商品，取消订单要返回redis,并取消订单
              //if(is_skill==1 || is_zsorder>=2){
             getApp().request.post("/api/weshop/order/cancelOrder/"+os.stoid+"/"+o+"/"+getApp().globalData.user_id,{
               data:{},
               success: function(t) {
                 if(t.data.code==0)
                   th.requestOrderDetail(o), wx.setStorageSync("order:order_list:update", !0);
               },
             })
              /*----
              }else{
                  getApp().request.put("/api/weshop/order/updatebyId", {
                    data: {order_id: o, order_status: 3},
                    success: function(e) {
                      th.requestOrderDetail(o), wx.setStorageSync("order:order_list:update", !0);
                    }
                  });
              }--*/
            }
        });
    },
    
    //--------确认收货---------
    confirmOrder: function(e) {
        var th=this;
        var t = this, o = this.data.order.order_id,order=this.data.order;
        var is_zsorder=order.is_zsorder;
        wx.showModal({
            title: "是否确认收货?",
            success: function(t) {
                t.confirm && rq.post("/api/weshop/order/confirmOrder/"+os.stoid+"/"+o+"/"+getApp().globalData.user_id,{
                    success:function (e) {
                        if(e.data.code==0){
                            th.requestOrderDetail(o)
                        }
                    }
                })
            }
        });
    },

    //--------立即支付----------
    async jumpToCart4(e) {
        var th=this;

			// 幸运购检查库存量 api/weshop/activitylist/getActLen/{store_id}/{prom_type}/{prom_id}
			if (parseInt(this.data.order.order_goods['0']['prom_type']) == 9) {
				var aid = this.data.order.order_goods['0']['prom_id'];
				var knum = 0;
				await r.promiseGet('/api/weshop/activitylist/getActLen/' + os.stoid + '/9/' + aid, {
				}).then(res => {
					if (res.data.code == 0) {
						knum = res.data.data;
					}
					
				});

				if (knum <= 0) {
					getApp().confirmBox("库存为0，支付失败");
					return false;
				}

			}

            if(this.data.paying) return false;
            this.data.paying=0;

			var order=this.data.order;
			var order_goods=order.order_goods;
			var user_id=order.user_id;
			// 检测活动是否结束
			
		
        py.pay(this.data.order.order_sn, function() {
            th.data.paying=0;
            wx.showToast({title: '支付成功'})
			wx.navigateBack();
        },null,os.stoid,1);


		},

    checkTeam: function() {
        wx.navigateTo({
            url: "/pages/team/team_detail/team_detail?foundId=" + this.data.order.orderTeamFound.found_id
        });
    },

    //------图片失败，默认图片---------
    bind_bnerr: function (e) {
      var _errImg = e.target.dataset.errorimg;
      var _errObj = {};
      _errObj[_errImg] = "public/images/default_goods_image_240.gif";
      this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ;       
    },

    zfwk:function(){
      var url = "/packageE/pages/cart/cart_wk/cart_wk?order_id=" + this.data.order.order_id;
      wx.redirectTo({
          url:url,
      })
    },

  //--------跳转到退款详情-----------
  gotoreturn: function (t) {
    var e = t.currentTarget.dataset.recid;
    var oid = t.currentTarget.dataset.oid;
    var wh = "";
    if (e != undefined && e != null && e != "") {
      wh = "&goods_id=" + e;
    }
    wx.navigateTo({
      url: "/packageF/pages/user/return_goods_info/return_goods_info?order_id=" + oid + wh,
    });
  },

  //---判断是不是有退款-----
  checkReturnGoodsStatus: function (t) {
    var e = t.currentTarget.dataset.recid;
    var oid = t.currentTarget.dataset.oid;
    r.get("/api/weshop/order/returngoods/page", {
      data: {
        goods_id: e,
        order_id: oid,
        store_id: os.stoid
      },
      success: function (t) {
        if (t.data.code == 0) {
          var r = t.data.data.total;
          if (0 == r) return wx.navigateTo({
            url: "/packageF/pages/user/return_goods/return_goods?rec_id=" + e + "&order_id=" + oid,
          });
          //--如果拒绝，就重新申请退款--
          if (t.data.data.pageData[0].status == 3) {
            return wx.navigateTo({
              url: "/packageF/pages/user/return_goods/return_goods?rec_id=" + e + "&order_id=" + oid,
            });
          }

          wx.navigateTo({
            url: "/packageF/pages/user/return_goods_info/return_goods_info?id=" + r
          });
        }
      }
    });
  },

    //-----删除订单-----
    deleteOrderData: function(t) {
        var th=this;
        var order_id=t.currentTarget.dataset.order_id;		
	    var	up_data={
		  order_id: order_id,isdel:1
		};	
		if(th.data.order.order_status!=6){
			up_data.order_status=5;
		}		
        wx.showModal({
            title: "是否删除订单？",
            success: function(tt) {
                tt.confirm && rq.put("/api/weshop/order/updatebyId", {
                    data: up_data,
                    success: function (t) {
                        getApp().my_warnning("删除成功",1,th);
                        setTimeout(function () {
                             getApp().goto("/pages/user/order_list/order_list");
                        },1000);
                    }
                })
            }
        });
    },

    //--判断是不是可以单个商品退--
    check_for_return_btn:function (item) {
        if(item.coupon_no) return false;        //有用优惠券
        if(item.order_prom_id) return false;    //有订单优惠
        if(item.order_status>=2) return false;  //订单状态>2
        var istrue=true;
        //----判断是不是有优惠活动和赠送商品----
        for (var g in item.order_goods) {
            var g_item=item.order_goods[g];
            if ((g_item.prom_type == 3 && g_item.discount_amount> 0)
                || (g_item.prom_type== 3 && g_item.goods_price <= 0)
            ) {
                istrue=false; break
            }
            if (g_item.prom_type== 5) {
                istrue=false; break
            }
        }
        if(!istrue) return false;
        var conf=this.data.conf;
        //判断是不是原路退回
        if(conf.refund_type==1) return true;
        else{
            if(item.order_amount==0 || item.user_money==0) return true;
        }
        return false;
    },
	
	

	//---检验线下库存的数量的子函数---
	async check_down_line_next(gg,num,pick_id,func){
	 
	  var lock=0,pick_no,plist;
	  //先读取门店的lock
	  await getApp().request.promiseGet("/api/weshop/order/ware/lock/page",{
		  data:{store_id:os.stoid,wareId:gg.goods_id,storageId:pick_id}
	  }).then(res=>{
		  if(res.data.code==0 && res.data.data.total>0){
			  for(var i in res.data.data.pageData)
			     lock+=res.data.data.pageData[i].outQty;
		  }
	  })
	  //先获取门店的编号
	  await getApp().request.promiseGet("/api/weshop/pickup/get/"+os.stoid+"/"+pick_id,{
		  data:{storeId:os.stoid,goodsId:gg.goods_id,pickupId:pick_id}
	  }).then(res=>{
		  if(res.data.code==0){
			  pick_no=res.data.data.pickup_no;
		  }
	  })	   
	  //读取线下的门店库存 
	  await getApp().request.promiseGet("/api/weshop/goods/getWareStorages",{
		  data:{storageNos:pick_no,wareIds:encodeURIComponent(gg.erpwareid),storeId:os.stoid}
	  }).then(res=>{
		  if(res.data.code==0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length>0){
			  plist=res.data.data.pageData[0];		 
		  }
	  })	  
	  var ob={}; ob.code=1;	  
	  if(!plist){
	  	   ob.code=-1; ob.CanOutQty=0;  
	  	   func(ob);return false;    
	  }	
	 
	  if(num>plist.CanOutQty-lock){
		 ob.code=-1; 
		 ob.CanOutQty=plist.CanOutQty-lock
		 if(ob.CanOutQty<0) ob.CanOutQty=0;  
	  }
	  func(ob)  
	},
	
	
	//再来一单的功能的实现
	moreOrder:function(e){
		  var th=this;
		  var item=th.data.order;

          if(this.data.moring) return false;
          this.data.moring=1;

		  th.check_more_order(item);  
	},
	
	check_more_order:async function(item){
		  var pickup=null,th=this;
		  var user_id=getApp().globalData.userInfo.user_id;
		  if(!user_id) user_id=0;
          wx.showLoading();
		  //--------获取门店-----------
		  await getApp().request.promiseGet("/api/weshop/pickup/get/" + os.stoid + "/" + item.pickup_id, {
		       
		  }).then(res=>{		
			   pickup = res.data.data;
		  })
				
		  //--------获取商品----------
		  var goods_list=item.order_goods;	  
		  //--- 返回的内容 ---
		  var back_goods_arr=[];
		  var err_text="";	  
		  for(var i in goods_list){
			  var g_item=goods_list[i];
			   //--如果是赠品，不加入购物车--
			  if(g_item['is_gift']) continue;		  
			  if(g_item['prom_type']==4 ){
			       err_text+= g_item['goods_name']+"积分购商品不加入购物车\n";
			       continue;
			  }
			  if(g_item['prom_type']==5){
				  err_text+= g_item['goods_name']+"搭配购商品不加入购物车\n";
				  continue;
			  }
			  if(g_item['prom_type']==6 ){
				  err_text+= g_item['goods_name']+"拼团商品不加入购物车\n";
				  continue;
			  }	
			  
			  //--获取商品--		
			  var good=null;				
			  await getApp().request.promiseGet("/api/weshop/goods/get/" + os.stoid + "/" + g_item.goods_id, {
				  
			  }).then(res=>{			  
				  good=res.data.data;
			  })
		  
			  if(!good){
				  err_text+= g_item['goods_name']+"未找到商品\n";
				  continue;
			  }		    
			  if (good.is_on_sale != 1) {
				  err_text+= g_item['goods_name']+"已经下架\n";
				  continue;		    
			  }
								
			  var timestamp = ut.gettimestamp();		  
			  if (good.on_time > timestamp) {
			    err_text+= g_item['goods_name']+"还未上架\n";
			    continue;	
			  }		  		  
			  if (good.down_time > 0) {
			    if (good.down_time < timestamp) {
			        err_text+=g_item['goods_name']+"已经下架\n";
			        continue;
			    }
			  }
			  
			  //如果商品的配送方式和门店不匹配
		      if(good['distr_type']>0 && pickup['distr_type']>0 && good['distr_type']!=pickup['distr_type'] ){
			     err_text+= good['goods_name']+"配送方式不一致\n";
			     continue;
		      }
			  
			  var prom=null;
			  var b_item={}
			  b_item.goods_id=g_item.goods_id;
			  b_item.goods_name=g_item.goods_name;
			  b_item.goods_num=g_item.goods_num;
			  b_item.guide_id=g_item.guide_id;
			  b_item.guide_type=g_item.guide_type;
			  b_item.pickup_id=item.pickup_id;
			  b_item.price=good.shop_price;
			  b_item.goods_sn=good.goods_sn;
			  b_item.sku=good.sku;
			  b_item.is_integral_normal=g_item.is_integral_normal;
			  
			  //-- 如果会员是等级卡的时候,同时商品也有设置相应的卡价格 --
			  var card_field=th.data.card_field;
			  if(card_field && good[card_field]>0){
			  	 b_item.price=good[card_field]; 
			  }

              var url="/api/weshop/activitylist/getGoodActInfo";
              var req_data={
                  store_id:g_item.store_id,goodsidlist:g_item.goods_id,is_detail:1,user_id:user_id
              };
              await getApp().request.promiseGet(url, {data:req_data}).then(res=>{
                  if(res.data.code==0){
                      var list = res.data.data;
                      for(let i in list){
                          let item=list[i];
                          if(item.prom_type==1){ good.prom_type=1; good.prom_id=item.act_id; }
                      }
                  }
              })

              if(!prom) {
                  //--判断商品当前的活动情况--
                  switch (good.prom_type) {
                      case 1:
                          var flash = null;
                          await getApp().request.promiseGet("/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + good.prom_id, {}).then(res => {
                              if (res.data.code == 0) {
                                  flash = res.data.data;
                              }
                          })
                          //----已经结束-----
                          if (flash && flash.is_end == 0 && flash.end_time > timestamp && flash.start_time < timestamp) {
                              prom = flash;
                              prom.price = prom.user_price;
                              b_item.price = prom.price;
                              good.prom_type = 1;
                              good.prom_id = prom.id;
                          }
                          break;
					  case 2:
					      var group = null;
					      await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + good.goods_id + "/" + good.prom_id, {}).then(res => {
					          if (res.data.code == 0) {
					              group = res.data.data;
					          }
					      })
					      //----已经结束-----
					      if (group && group.is_end == 0 && group.end_time > timestamp && group.start_time < timestamp) {
					          prom = group;
					          prom.price = prom.price;
					          b_item.price = prom.price;
					      }
					      break;		  
                      case 6:
                          b_item.is_pd_normal = 1;
                          break;
                      case 7:
                          //如果有组合购
                          var url = "/api/weshop/prom/zhbuy/get/" + os.stoid + "/" + good.prom_id + "/" + getApp().globalData.userInfo.user_id;
                          await getApp().request.promiseGet(url, {}).then(res => {
                              if (res.data.code == 0 && res.data.data) {
                                  if (res.data.data.is_show == 1 && res.data.data.is_end == 0
                                      && ut.gettimestamp() < res.data.data.end_time
                                      && ut.gettimestamp() > res.data.data.start_time
                                  ) {
                                      b_item.prom_type = 7;
                                      b_item.prom_id = res.data.data.id;
                                      good.prom_type = 7;
                                      good.prom_id = res.data.data.id;
                                  }
                              }
                          })
                          break;
                  }
              }
			  
			  //如果有优惠促销的时候,要看下商品的优惠活动有没有过期
			  if(g_item.prom_type==3 || good.prom_type==3){
				  await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromList/" + os.stoid + "/" + good.goods_id + "/1", {}).then(res => {
					if (res.data.code == 0) {
						var r_data = res.data.data;
						if (r_data.promGoodsLists) {
							 b_item.prom_type=3;
							 b_item.prom_id=r_data.promGoodsLists[0].prom_id;
						}
					} 
				  })	
			  }
			  
			  			  
			  //判断是不是线下库存的购买，  是不是秒杀活动		  
			  if(th.data.sales_rules==2 && !prom){
				  
				  //-- 看一下购物车上有多少商品 --
				  var cart_num=0;				  
				  await getApp().request.promiseGet("/api/weshop/cart/page", {				  	
					 data: {
						store_id: os.stoid,
						user_id: getApp().globalData.user_id,
						state:0, is_gift:0,
						goods_id:good.goods_id,
						pick_id: b_item.pickup_id
					 }
				  }).then(res=>{
					  var num = 0;
					  if(res.data.code==0 && res.data.data && res.data.data.pageData) {
						  for (var i = 0; i < res.data.data.pageData.length; i++) {
							  num += res.data.data.pageData[i].goods_num;
						  }
					  }
					  cart_num=num;						 
				  })
				  		  
				  var lock=0,plist=null;

                  if(b_item.prom_type!=7) {
                      //先读取门店的lock,
                      await getApp().request.promiseGet("/api/weshop/order/ware/lock/page", {
                          data: {store_id: os.stoid, wareId: good.goods_id, storageId: b_item.pickup_id, pageSize: 1000}
                      }).then(res => {
                          if (res.data.code == 0 && res.data.data.total > 0) {
                              for (var i in res.data.data.pageData)
                                  lock += res.data.data.pageData[i].outQty
                          }
                      })

                      //---通过接口获取门店的线下库存信息--
                      await getApp().request.promiseGet("/api/weshop/goods/getWareStorages", {
                          data: {
                              storageNos: pickup.pickup_no,
                              wareIds: encodeURIComponent(good.erpwareid),
                              storeId: os.stoid
                          }
                      }).then(res => {
                          if (res.data.code == 0 && res.data.data.total > 0) {
                              plist = res.data.data.pageData[0];
                          }
                      })

                      if (!plist) {
                          err_text += good['goods_name'] + "库存不足\n";
                          continue;
                      }
                      if (plist.CanOutQty - lock <= 0) {
                          err_text += good['goods_name'] + "库存不足\n";
                          continue;
                      }
                      if (b_item.goods_num > (plist.CanOutQty - lock)) {
                          b_item.goods_num = plist.CanOutQty - lock;
                      }
                  }
				  var req_data={
				      store_id: os.stoid,
				      user_id: getApp().globalData.user_id,
				      goods_id: good.goods_id,
                      timetype:good.viplimited_timetype

				  };
                  if(b_item.prom_type==7){
                      req_data.prom_type=7;
                      req_data.prom_id=b_item.prom_id;
                  }
				  
				  var buynum=0;
                  var promnum=0;
				  //---要获得商品，该用户买了多少件,同步应用---
				  await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
				    data: req_data,
				  }).then(res => {					  
					  if(res.data.code==0){
						 var buy_num_data = res.data.data;
						 buynum = buy_num_data.goodsbuynum;
                          if(buy_num_data.promgoodsbuynum){
                              promnum=buy_num_data.promgoodsbuynum;
                          }
					  }					 				     
				  })
				  
				  //---- 要计算商品的限购 -----
				  if(good['viplimited']>0){ 				  												  
					  if(cart_num+buynum>good['viplimited']){
						   err_text+= good['goods_name']+"超出限购\n";
						   continue;
					  }				  
					  good['viplimited']-=(cart_num+buynum);
					  if(b_item.goods_num>good['viplimited']){
						  b_item.goods_num=good['viplimited'];
					  }			  				  		    				   
				  }
				  //不需要计算组合购的限购
				  
				  back_goods_arr.push(b_item);  //返回商品元素	
									
			  }else{
				  //-- 看一下购物车上有多少商品 --
				  var cart_num=0;				  
				  await getApp().request.promiseGet("/api/weshop/cart/page", {				  	
						 data: {
							store_id: os.stoid,
							user_id: getApp().globalData.user_id,
							state:0, is_gift:0,
							goods_id:good.goods_id			  					
						 }
				  }).then(res=>{
						  var num = 0;
						  if(res.data.code==0 && res.data.data && res.data.data.pageData) {
							  for (var i = 0; i < res.data.data.pageData.length; i++) {
								  num += res.data.data.pageData[i].goods_num;
							  }
						  }
						  cart_num=num;						 
				  })

				  if(good.store_count<=0){
					  err_text+= good['goods_name']+"库存不足\n";
					  continue; 
				  }
				  if(b_item.goods_num>good.store_count)
				      b_item.goods_num=good.store_count;
					  				  
			      var buynum=0;             //商品已经购买多少件
			      var promgoodsbuynum=0;	//活动已经购买多少件	
				  var redis_num = 0;        //redis库存
					
			      var req_data={
			          store_id: os.stoid,
			          user_id: getApp().globalData.user_id,
			          goods_id: good.goods_id,
                      timetype:good.viplimited_timetype
			      };
			      
			      if(prom){
			      		req_data.prom_type= good.prom_type;
			      		req_data.prom_id= good.prom_id;
						b_item.prom_type=good.prom_type;
						b_item.prom_id=good.prom_id;		
											
						//------判断活动是否抢光-----
						await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" +
						    os.stoid + "/" + good.prom_type + "/" + good.prom_id, {
						  1: 1
						}).then(res => {
						  redis_num = res.data.data;
						});										
						if(redis_num<=0){
							err_text+= good['goods_name']+"活动不足\n";
							continue; 
						}			
						
			      }
			      			 				  
			      //---要获得商品，该用户买了多少件,同步应用---
			      await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
			        data: req_data,
			      }).then(res => {					  
			      		if(res.data.code==0){
			      			var buy_num_data = res.data.data;
			      			if (buy_num_data.promgoodsbuynum) promgoodsbuynum = buy_num_data.promgoodsbuynum;
			      			buynum = buy_num_data.goodsbuynum;
			      		 }					 				     
			      })	
				  									  
				  //---- 要计算商品的限购 -----	  
				  if(good['viplimited']>0){ 				  												  
					  if(cart_num+buynum>good['viplimited']){
						   err_text+= good['goods_name']+"超出限购\n";
						   continue;
					  }				  
					  good['viplimited']-=(cart_num+buynum);
					  if(b_item.goods_num>good['viplimited']){
						  b_item.goods_num=good['viplimited'];
					  }
					  		    				   
				  }
				  
				  //-- 判断活动的库存 --
				  if(prom){				  
					   if(prom['goods_num']<=prom['buy_num']){
					      err_text+= good['goods_name']+"超出活动库存\n";continue;
					   }	
					
					   if(b_item.goods_num>prom['goods_num']-prom['buy_num']){
					      b_item['goods_num']= b_item['goods_num']-b_item['buy_num'];
					   }
														 
					   if(b_item.goods_num>redis_num){
						   b_item.goods_num=redis_num;
					   }

					   if(prom['buy_limit']>0){
                           if(cart_num+buynum>prom['buy_limit'] ){
                               err_text+= good['goods_name']+"超出活动限购\n";continue;
                           }
                           prom['buy_limit'] -= (cart_num+buynum);
                           if(b_item.goods_num>prom['buy_limit']){
                               b_item.goods_num=prom['buy_limit'];
                           }
                       }
													  												 												  

				  }
				  back_goods_arr.push(b_item);  //返回商品元素			  					  
			  }		  			
		  }
		  
		  //有重新购买的数据是时候，就要重新生成订单	  
		  if(back_goods_arr.length>0){
			  th.setData({back_goods_arr:back_goods_arr});
			  if(!err_text){
				  th.more_add_cart();
			  }else{
				  wx.hideLoading();	
				  // 如果没有获取用户信息
				  wx.showModal({
				  	title:'确定',
				  	content: err_text+',确定要买其他商品码？',
				  	success(res) {
				  		if (res.confirm) {
				  			//跳转到登录页
				  			 th.more_add_cart();
				  		}else{
                            th.data.moring=0;
                            wx.hideLoading();
                        }
				  	},fail(){
                          th.data.moring=0;
                          wx.hideLoading();
					}
				  });
				  
			  }		  
		  }else{
              th.data.moring=0;
			  wx.hideLoading();	
			  getApp().confirmBox(err_text);  
		  }	  
	},
	
	more_add_cart:async function(){	 
		  var back_goods_arr=this.data.back_goods_arr;     
		  var err_text="";		
		  var ok_num=0;
						  				  
		  for(var i in back_goods_arr){
			  //商品ID
			  var g_item=back_goods_arr[i];		  
			  var newd = {
			    goods_id: g_item.goods_id,
			    goods_num: g_item.goods_num,
			    pick_id: g_item.pickup_id,
			    user_id: oo.user_id,
			    store_id: os.stoid,
			    goods_price: g_item.price,
			    member_goods_price: g_item.price,
			    goods_name: g_item.goods_name,
			    goods_sn: g_item.goods_sn,
			    sku: g_item.sku,
			  };
			  
			  if(g_item.guide_id){
				  newd['guide_id']=g_item.guide_id;
				  newd['guide_type']=g_item.guide_type;
			  }
			  
			  if(g_item.is_integral_normal){
			  	   newd['is_integral_normal']=g_item.is_integral_normal;
			  }  
			  if(g_item.is_pd_normal){
			  	   newd['is_pd_normal']=g_item.is_pd_normal;	  
			  }
			  if(g_item.prom_type){
			  		newd['prom_type']=g_item.prom_type;	  
			  		newd['prom_id']=g_item.prom_id;	  
			  }
			  
			  
			 
			  var b_cart_goods=null; 
			  await getApp().request.promiseGet("/api/weshop/cart/page", {
			    data: {
			      store_id: os.stoid,
			      user_id: oo.user_id,
			      goods_id: g_item.goods_id,
			      pick_id: g_item.pickup_id,
			    },
			  }).then(res=>{
				  //-------如果购物车中有相关的数据-------
				  if (res.data.data.total > 0) {		  
				     b_cart_goods= res.data.data.pageData[0];
				  }			  
			  })	
			 
			  //-- 如果就加入过购物车 --
			  if(b_cart_goods){		  
				  var updata = {
				     id: b_cart_goods.id,
				     goods_num: newd.goods_num + b_cart_goods.goods_num,
				     goods_price: newd.goods_price,
				     member_goods_price:newd.goods_price,
				     store_id: os.stoid,
				  };
				  if(newd.guide_id){
					 updata.guide_id=newd.guide_id;
					 updata.guide_type=newd.guide_type;
				  }	  
				  await getApp().request.promisePut("/api/weshop/cart/update", {
				     data: updata
				  }).then(res=>{
					  if(res.data.code==0) {
						  ok_num++;
					  }else{
						  err_text+=newd.goods_name+"加入购物车失败\n"; 
					  }
				  })	 
				  			  
			  }else{
				  await getApp().request.promisePost("/api/weshop/cart/save", {
				     data: newd
				  }).then(res=>{
					  if(res.data.code==0) {
					  	 ok_num++;
					  }else{
					  	err_text+=newd.goods_name+"加入购物车失败\n"; 
					  }			  				  
				  })				  
			  }		 			  
		  }		
								
		  wx.hideLoading();
          this.data.moring=0;
		  if(ok_num==0){
			  //-- 如果没有获取用户信息 --
			  wx.showModal({
			  	title:'提示',
			  	content: err_text,
			  	success(res) {}
			  });
		  }else{
			  if(err_text==""){
				  getApp().goto("/pages/cart/cart/cart");
			  }else{
				  // 如果没有获取用户信息
				  wx.showModal({
				  	title:'提示',
				  	content: err_text,
				  	success(res) {
				  		if (res.confirm) {
				  			//跳转到登录页
				  			getApp().goto("/pages/cart/cart/cart");
				  		}
				  	}
				  });
				  
			  }
			  
		  }
	},

	toast(msg){
		wx.showToast({
			title: msg,
			icon: 'none',
			duration: 3000
		})
	},

    con_weixin:function () {
       getApp().con_wx(this);
    },

    //跳转到商品
    go_gd:function (e) {
			// console.log(e);
        var gd= e.currentTarget.dataset.gd;
				var prom_type = this.data.order.order_goods[0].prom_type;
				// var good_url='';
				// if(prom_type == 9) {
				// 	good_url = '';
				// } else {
				// 	good_url="/pages/goods/goodsInfo/goodsInfo?goods_id=" + gd;
				// };
				
        var good_url="/packageC/pages/luckyGo/luckyGo_goodsInfo/luckyGo_goodsInfo?goods_id=" + gd + '&group_id=' + this.data.group_id;
				getApp().goto(good_url);
				
        // var url="/api/weshop/activitylist/getGoodActInfo";
        // var req_data={
        //     store_id:os.stoid,goodsidlist:gd,is_detail:1
        // };
        //获取秒杀的多规格
        // getApp().request.promiseGet(url, {data:req_data}).then(res=>{
        //     if(res.data.code==0 && res.data.data){
        //         if(res.data.data.length==1){
        //             good_url+="&prom_type="+res.data.data[0].prom_type+"&prom_id="+res.data.data[0].act_id;
        //         }
        //         getApp().goto(good_url);

        //     }else{
        //         getApp().goto(good_url);
        //     }
        // })
    },


    click_contact:function () {
        getApp().globalData.no_clear=1;
    },

    //-- 查看物流 --
    go_wuliu:function (e) {
        getApp().go_wuliu(e);
    }









});