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) {

        if(e.transfer){
            let obj=getApp().globalData.ts_trans_data;
            e= JSON.parse(JSON.stringify(obj));
            getApp().globalData.ts_trans_data=null;
       }
 
        //定义第一次进入
        this.data.fir_in=1;

        var th=this;
        var r = void 0 !== e.isGoup && e.isGoup;

        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,appoint_pick_keyid:s_list.appoint_pick_keyid});
					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({
            optionIsGoup: r
        }), this.requestOrderDetail(e.order_id), wx.removeStorageSync("order:order_detail:update");
    },
    onShow: function() {

        var th=this;
        this.setData({paying:0});

        //判断是不是第一次进入
        if(this.data.fir_in){
            this.data.fir_in=0;
        }else{
            //富友支付
            ut.fy_back('',0)
            py.set_fir();

            //通联第三方
            //-- 通联的第三方支付的返回优化 --
            ut.is_pay_ok(th.data.ok_order_sn,"back","none",function (){
                getApp().request.promiseGet("/api/weshop/order/page",
                    {data:{store_id:os.stoid,order_sn:th.data.ok_order_sn}}).then(res=>{
                    if(ut.ajax_ok(res)){
                        var item=res.data.data.pageData[0];
                        if(item.pay_status==1){
                            //支付支付，返回首页
                            ut.m_toast('支付成功');
                            setTimeout(()=>{
                                wx.navigateBack();
                            },1000)

                        }else{
                            //支付支付，返回首页
                            ut.m_toast('支付失败');
                            setTimeout(()=>{
                                wx.navigateBack();
                            },1000)
                        }
                    }
                })
            });
        }

        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: async 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.shipping_status == 3)){
                  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;

               var discount_price=r['discount_amount'];
               var dis_json=r['prom_pt_json'];

               if(dis_json && discount_price){
                   var prom_pt_json=JSON.parse(dis_json);
                   var ladder_amount=0;
                   for (var ll_item of prom_pt_json) {
                       if(ll_item['ladder_prom_id']){
                           ladder_amount += ll_item['dis'];
                       }
                   }
                   r['ladder_amount']=ladder_amount;
                   r['discount_amount']=Math.floor((discount_price-ladder_amount)*100)/100;
               }


                r.use_commission=0;
                //-- 如果有数据的话 --
                await getApp().request.promiseGet("/api/weshop/orderMore/get/"+os.stoid + "/"+r.order_sn, {

                }).then(res=>{
                    if(res.data.code == 0 && res.data.data){
                        r.use_commission=res.data.data.use_commission;
                        r.pre_cut=res.data.data.pre_cut; //预存款
                        r.pre_json=res.data.data.pre_json; //预存款
                        r.is_user_no_yhcx = res.data.data.is_user_no_yhcx;  //判断订单是不是优惠促销不参与
                    }
                })


               //------获取订单商品-------
               rq.get("/api/weshop/ordergoods/list",{
                    data: { store_id: os.stoid, order_id: oid,pageSize:600},
                    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().confirmBox(t.data.msg);
                 }

               },
             })
              /*----
              }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 vipadvancesum(keyid,pre_cut,pre_json){
        let pre=JSON.parse(pre_json)
        let listform=[]
        pre.map(item=>{
            let obj={
                advancesum: item.advancesum,
                advanceitemid: item.advanceitemid
            }
            listform.push(obj)
        })
        let res = await getApp().request.promisePost(`/api/weshop/delphiapi/saveErpApi`, {
            data: {
                accdb: getApp().globalData.config.erpid,
                ApiName: 'api.pos.shop.vipadvancesum.list',
                // usercode: "admin",
                vipid: getApp().globalData.userInfo.erpvipid,
                // oddsum: "0",
                // advancesum: cartList.order_amount,
                storageid: keyid,
                listform
            },
            is_json: 1
        })
        return res.data
    },

    //--------立即支付----------
    async jumpToCart4(e) {

        if(this.data.paying) return false;
        this.setData({paying:1});

        var th=this;
        if(this.data.optionIsGoup) 
		     wx.navigateTo({
                 url: "/pages/team/team_confirm/team_confirm?orderSn=" + this.data.order.order_sn + "&orderPay=true"
             }) 		   
		var order=this.data.order;

		var order_goods=order.order_goods;
		var user_id=order.user_id;



        var wlist = "";
        var the_yh_map={}; //判断那种商品的prom_type为0，正在做的活动是优惠促销


        var _pick=null;
        //获取商品信息，包含线下商品ID，指定门店销售的信息
        var rh=await getApp().request.promiseGet("/api/weshop/pickup/get/"+os.stoid+"/"+order.pickup_id, {});
        if(rh && rh.data.code==0){
            _pick=rh.data.data;
        }
        
        for (var i in order_goods) {
            var good = order_goods[i];


            //线下取价功能已经关闭或者过期
            if (!th.data.is_open_offline && good.offline_cut > 0) {
                wx.showModal({
                    title: '提示',
                    content: '线下取价功能已经关闭或者过期！'
                });
                th.setData({ paying: 0 });
                return false;
            }

            //要每件每件的商品进行检查，看有么有超出库存，超出限购
            var good = order_goods[i], goodsbuynum = 0, promgoodsbuynum = 0, gg = null, presellList = null;

            //获取单品的现在的活动状态
            await getApp().request.promiseGet("/api/weshop/goods/get/" + os.stoid + "/" + good.goods_id, {}).then(res => {
                gg = res.data.data;
            })

            //-- 判断门店配送是不是匹配 --
            if(_pick && _pick.distr_type!=0 && gg.distr_type!=0 && _pick.distr_type!= gg.distr_type){
                getApp().confirmBox(gg.goods_name + "配送方式和门店不一致");
                th.setData({ paying: 0 });
                return false;
            }

            //-- 要进行判断指定门店的判断优化,先做普通商品 --
            if([0,3,5,7,10].indexOf(parseInt(good.prom_type))>-1 && gg.pick_group_ids && !good.is_gift){
                var idx0=gg.pick_up_lists.findIndex(function (e){
                    return e.pickup_id==order.pickup_id;
                })
                if(idx0<0){
                    getApp().confirmBox(gg.goods_name + "的门店不可售");
                    th.setData({ paying: 0 });
                    return false;
                }
            }

            var limit = gg.viplimited;
            var store_count = gg.store_count;
            good.erpwareid = gg.erpwareid;

            //---要获得商品，该用户买了多少件,同步应用---
            await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
                data: {
                    store_id: os.stoid,
                    user_id: user_id,
                    goods_id: good.goods_id,
                    prom_type: good.prom_type,
                    prom_id: good.prom_id,
                    timetype:gg.viplimited_timetype
                },
            }).then(res => {
                var buy_num_data = res.data.data;
                if (buy_num_data.promgoodsbuynum) promgoodsbuynum = buy_num_data.promgoodsbuynum;
                goodsbuynum = buy_num_data.goodsbuynum;
            })

            var buyed_mum2 = goodsbuynum + good.goods_num;
            if (buyed_mum2 > limit && limit > 0 && !good.is_gift) {
                var content = gg.goods_name + '购买数量超出商品限购,请取消订单';
                th.toast(content);
                th.setData({ paying: 0 });
                return false;
            }

            //当是组合优惠的时候
            if (good.prom_type == 7) {
                //如果有组合购
                var isok = 1;
                var url = "/api/weshop/prom/zhbuy/get/" + os.stoid + "/" + good.prom_id + "/" + getApp().globalData.userInfo.user_id;
                let zh_buy_info=null
                await getApp().request.promiseGet(url, {}).then(res => {
                    if (res.data.code == 0 && res.data.data) {
                        zh_buy_info = res.data.data
                        if (res.data.data.is_show != 1) {
                            isok = 0;
                        }
                        //如果活动已经结束
                        if (res.data.data.is_end == 1) {
                            isok = 0;
                        }
                        //已经结束
                        if (ut.gettimestamp() > res.data.data.end_time) {
                            isok = 0;
                        }
                        //还未开始
                        if (ut.gettimestamp() < res.data.data.start_time) {
                            isok = 0;
                        }


                    } else {
                        //未找到商品的活动
                        isok = 0;
                    }

                })
                if (!isok) {
                    var content = gg.goods_name + '活动已经结束,请取消订单';
                    th.toast(content);
                    th.setData({ paying: 0 });
                    return false;
                }

                //增加组合购次数判断
                let userbuynum = await th.getUserBuyPromNum(good.prom_id,1)

                if (zh_buy_info.buy_limit !=0 && zh_buy_info && userbuynum >= zh_buy_info.buy_limit) {
                    var content = gg.goods_name + '超出组合购限购次数,请取消订单';
                    th.toast(content);
                    th.setData({ paying: 0 });
                    return false;
                }

                var url1 = "/api/weshop/prom/zhbuyGoods/page";
                var req_data = {
                    page: 1,
                    pageSize: 1,
                    store_id: os.stoid,
                    zh_id: good.prom_id,
                    goods_id: good.goods_id
                }
                await getApp().request.promiseGet(url1, {
                    data: req_data
                }).then(res => {
                    if (ut.ajax_ok(res)) {
                        var gdlist = res.data.data.pageData[0];
                        good.buyqty = gdlist.buyqty;
                    }
                })

                var num = good['buyqty'];
                //---- 要计算商品的限购 -----
                if (good['buyqty'] > 0) {
                    if (good.goods_num + promgoodsbuynum > good['buyqty']) {
                        var content = good['goods_name'] + "超出活动限购\n";
                        th.toast(content);
                        th.setData({ paying: 0 });
                        return false;
                    }
                }
            }
            //如果是预售的时候，
            if (good.prom_type == 8) {
                await getApp().request.promiseGet("/api/weshop/order/orderPresell/countBuyGoodsSum", {
                    data: { store_id: os.stoid, user_id: user_id, goods_id: good.goods_id, prom_id: good.prom_id },
                }).then(e => {
                    if (e.data.code == 0) {
                        promgoodsbuynum = e.data.data.sumgoodsnum;
                    }
                })

                var presell_id = good.prom_id;
                var url = "/api/weshop/marketing/marketingPresellList/list"
                var rd = {
                    store_id: os.stoid,
                    presell_id: presell_id,
                    goods_id: good.goods_id
                }
                //------获取预售从表----------
                await getApp().request.promiseGet(url, {
                    data: rd
                }).then(res => {
                    if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
                        var arr = res.data.data[0];
                        presellList = arr
                    }
                })

                if(!presellList){
                    var content = good.goods_name + '未找到预售活动,请取消订单';
                    th.toast(content);
                    th.setData({ paying: 0 });
                    return false;
                }

                if (presellList) {
                    if (good.goods_num > presellList.presell_sumqty - presellList.buy_goodnum) {
                        var content = good.goods_name + '购买数量超出商品库存,请取消订单';
                        th.toast(content);
                        th.setData({ paying: 0 });
                        return false;
                    }
                    var buyed_mum3 = promgoodsbuynum + good.goods_num;
                    if (buyed_mum3 > presellList.vip_butyqty && presellList.vip_butyqty > 0) {
                        var content = good.goods_name + '购买数量超出商品限购,请取消订单';
                        th.toast(content);
                        th.setData({ paying: 0 });
                        return false;
                    }

                    var fres=await getApp().request.promiseGet("/api/weshop/marketing/marketingPresellForm/get/"+os.stoid+"/"+presell_id, {});
                    //接口调用成功的时候
                    if(fres && fres.data.code==0 && fres.data.data){
                        //如果有指定门店的时候
                        if(fres.data.data.pick_up_lists){
                            var idx0=fres.data.data.pick_up_lists.findIndex(function (e){
                                return e.pickup_id==order.pickup_id;
                            })
                            if(idx0<0){
                                getApp().confirmBox(good.goods_name+"预售活动的门店不可售");
                                th.setData({ paying: 0 });
                                return false;
                            }
                        }

                    }else{
                        var content = good.goods_name  + '未找到预售活动,请取消订单';
                        th.toast(content);
                        th.setData({ paying: 0 });
                        return false;
                    }

                }
            }

            //如果优惠促销和搭配购的时候
            if ((good.prom_type == 3 || good.prom_type == 5 || good.prom_type == 10) && good.is_gift != 1 && good.is_collocation != 1) {
                var p_ok = 1, is_g_prom = 0;
                //只读优化促销和阶梯促销
                await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromListNew1/" + os.stoid + "/" + good.goods_id+"/0/"+user_id, {}).then(res => {
                    if (res.data.code == 0) {
                        var r_data = res.data.data;
                        if (!r_data.collocationPromList && good.prom_type == 5) {
                            var content = good.goods_name + '未找到活动,请取消订单重新购买';
                            th.toast(content)
                            p_ok = 0;
                        }
                        if (!r_data.promGoodsLists && good.prom_type == 3) {
                            var content = good.goods_name + '未找到活动,请取消订单重新购买';
                            th.toast(content);
                            p_ok = 0;
                        }else if(r_data.promGoodsLists && good.prom_type == 3){
                            var fir_act = r_data.promGoodsLists[0];
                            //如果是有限购的时候
                            if (fir_act.gd_limit_num>0){
                                if(promgoodsbuynum+good.goods_num > fir_act.gd_limit_num){
                                    var content = good.goods_name + '超出优惠促销活动商品限购,请取消订单重新购买';
                                    th.toast(content)
                                    p_ok = 0;
                                }
                            }

                        }

                        if (!r_data.ladderLists && good.prom_type == 10) {
                            var content = good.goods_name + '未找到活动,请取消订单重新购买';
                            th.toast(content);
                            p_ok = 0;
                        }
                    } else {

                        var content = good.goods_name + '未找到活动,请取消订单重新购买'
                        th.toast(content);
                        p_ok = 0;
                    }
                })
                if (!p_ok) {
                    th.setData({ paying: 0 });
                    return false;
                }
            }

            //-- 商品的普通购买 ，不要进行判断 --
            if ((good.prom_type == 1 || good.prom_type == 2 || good.prom_type == 6 || good.prom_type == 4 || good.prom_type == 8 || good.prom_type == 9)
                && !good.is_gift && !good.is_collocation && !good.is_integral_normal && !good.is_pd_normal) {

            } else {


                if(good.is_pd_normal || good.is_integral_normal){
                    gg.prom_type=good.prom_type;
                    gg.prom_id=good.prom_id;
                }else {

                    //因为商品的prom_type=0,所以商品的实际活动要重新获取
                    var url = '/api/weshop/activitylist/listGoodActInfo2New';
                    var req_d = {
                        "store_id": os.stoid,
                        "goods_id": good.goods_id,
                        "user_id": user_id,
                    }
                    await getApp().request.promiseGet(url, {
                        data: req_d
                    }).then(res => {
                        if (res.data.code == 0 && res.data.data) {
                            var arr = res.data.data;
                            //-- 预热也要计算 --
                            var arr2 = arr.filter(function (e) {
                                return e.s_time < ut.gettimestamp() || (e.warm_uptime && e.warm_uptime < ut.gettimestamp())
                            })
                            if (arr2.length == 1) {
                                gg.prom_type = arr2[0].prom_type;
                                gg.prom_id = arr2[0].act_id;
                            } else if (arr2.length > 1) {
                                //如果是多活动的时候，要看good参与的活动有没有结束，是不是有效
                                var fd = arr2.find(function (e) {
                                    return e.prom_type == good.prom_type && e.act_id == good.prom_id
                                })
                                if (fd) {
                                    gg.prom_type = good.prom_type;
                                    gg.prom_id = good.prom_id;
                                }
                            }
                        }
                    })
                }

                if(gg.prom_type==3){
                    var prom_pc=null;
                    await getApp().request.promiseGet("/api/weshop/promgoods/get/" + os.stoid + "/" + gg.prom_id, {}).then(res => {
                        if (res.data.code == 0) { prom_pc = res.data.data; }
                    })

                    if(prom_pc){
                        gg.discount_field=prom_pc.discount_field;
                    }
                }

                //阶梯促销获取取价规则
                if(gg.prom_type==10){
                    var prom_ld=null;
                    //-- 获取阶梯规则 --
                    var url1 = "/api/weshop/prom/ladderList/list";
                    var req_data = {
                        store_id: os.stoid,
                        form_id: gg.prom_id,
                    }
                    await getApp().request.promiseGet(url1, {
                        data: req_data
                    }).then(rs1 => {
                        if (rs1.data.code == 0 && rs1.data.data && rs1.data.data.length ) {
                            prom_ld = rs1.data.data[0];
                        }
                    })

                    if(prom_ld){
                        gg.discount_field=prom_ld.discount_field;
                    }
                }

                if ((gg.prom_type == 1 || gg.prom_type == 2 || gg.prom_type == 4 || gg.prom_type == 6 || gg.prom_type == 8 || gg.prom_type == 9)
                    && !good.is_collocation && !good.is_gift && !good.is_integral_normal && !good.is_pd_normal) {
                    var prom = null;
                    //---如果是活动的时候---
                    var prom = null, th = this;
                    if (gg.prom_type == 1) {
                        await getApp().request.promiseGet("/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + gg.prom_id, {}).then(res => {
                            if (res.data.code == 0) {
                                prom = res.data.data;
                                prom.price = prom.user_price;
                            }
                        })
                    }
                    if (gg.prom_type == 2) {
                        await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + gg.goods_id + "/" + gg.prom_id, {}).then(res => {
                            if (res.data.code == 0) {
                                prom = res.data.data;
                                prom.price = prom.price;
                            }
                        })
                    }
                    if (gg.prom_type == 6) {
                        await getApp().request.promiseGet("/api/weshop/teamlist/get/" + os.stoid + "/" + gg.prom_id, {}).then(res => {
                            if (res.data.code == 0) {
                                prom = res.data.data;
                            }
                        })
                    }
                    if (gg.prom_type == 4) {
                        await getApp().request.promiseGet("/api/weshop/integralbuy/pageIntegralBuyGoodsList?stype=1&stypeup=1&timetype=2", {
                            data: { store_id: os.stoid, goods_id: gg.goods_id,user_id: getApp().globalData.user_id, }
                        }).then(res => {
                            if (res.data.code == 0 && res.data.data && res.data.data.pageData) {
                                prom = res.data.data.pageData[0];
                            }
                        })
                    }
                    if (prom) {
                        var t_now = ut.gettimestamp();
                        if (prom.is_end == 0 && prom.start_time < t_now && prom.end_time > t_now) {

                            var content = gg.goods_name + '商品的活动发生了变化,请取消订单重新购买';
                            th.toast(content);
                            th.setData({ paying: 0 });
                            return false;
                        }
                    }

                    //-- 幸运购的时候 --
                    if(gg.prom_type==8 || gg.prom_type==9){
                        var content = gg.goods_name + '商品的活动发生了变化,请取消订单重新购买';
                        th.toast(content);
                        th.setData({ paying: 0 });
                        return false;
                    }

                }
                else {
                    var t_ok = 1;
                    //-- 如果是普通购买的时候，此时计算的一定是商品的prom_type==0了,  （组合购在普通购买的时候，就不判断了，因为组合购本身就可以普通购买）---
                    if(!good.is_collocation && !good.is_gift && good.is_pd_normal!=2 && gg.prom_type!=7 ){

                        var promgoodsbuynum0=0;
                        //---要获得商品，该用户买了多少件,同步应用---
                        await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
                            data: {
                                store_id: os.stoid,
                                user_id: user_id,
                                goods_id: good.goods_id,
                                prom_type: gg.prom_type,
                                prom_id: gg.prom_id
                            },
                        }).then(res => {
                            var buy_num_data = res.data.data;
                            if (buy_num_data.promgoodsbuynum) promgoodsbuynum = buy_num_data.promgoodsbuynum;
                        })


                        //商品的订单列表的活动类型，和gg参与的类型不一致
                        if(good.prom_type != gg.prom_type && good.prom_id != gg.prom_id){
                            //如果商品有单独的活动的是偶
                            switch (gg.prom_type){
                                case 10:
                                    var content = gg.goods_name + '商品的活动发生了变化,请取消订单重新购买';
                                    th.toast(content);
                                    t_ok = 0;
                                    break;
                                //-- 优惠促销是有限购的 --
                                case 3:
                                    var prom=null;
                                    var yh_check=1;


                                    //如果有优惠促销的普通购买的时候
                                    if(order.is_user_no_yhcx && good.prom_type==0 && order.is_user_no_yhcx!='0' && order.is_user_no_yhcx!='null' ){
                                        let obj=JSON.parse(order.is_user_no_yhcx);
                                        //obj数组使用find函数快速查找
                                        if(obj.find((item)=>{return item.prom_id==gg.prom_id && item.prom_type==3})){
                                            yh_check=0;
                                        }
                                    }

                                    //判断优惠促销活动的限购
                                    if(yh_check){
                                        await getApp().request.promiseGet("/api/weshop/promgoods/get/" + os.stoid + "/" + gg.prom_id, {}).then(res => {
                                            if (res.data.code == 0) { prom = res.data.data; }
                                        })
                                        if (prom && prom.limit_num) {
                                            var limit_num = prom.limit_num;
                                            var user_pre_buynum = await this.getUserBuyPromNum_pre(prom.id)
                                            if (limit_num>0 && user_pre_buynum >= limit_num) {
                                                yh_check=0;
                                            }
                                        }
                                    }

                                    //--- 要判断一下优惠促销的商品的限购 ---
                                    if(yh_check){
                                        var pro_gd_limit_num=0;
                                        var p_limit_rs= await getApp().request.promisePost('/api/weshop/promgoods/getPromGoodsLimitNum',{
                                            data:{
                                                store_id:os.stoid,goods_id:gg.goods_id,prom_id:gg.prom_id,prom_type:3
                                            }
                                        })
                                        if(p_limit_rs && p_limit_rs.data.code==0){
                                            pro_gd_limit_num=p_limit_rs.data.data
                                        }
                                        //-- 如果有商品限购的时候 --
                                        if(pro_gd_limit_num>0){
                                            var pro_by_num=0;
                                            var lrs= {
                                                store_id: os.stoid,user_id: getApp().globalData.user_id,
                                                goods_id: gg.goods_id, prom_type: 3,
                                                prom_id: gg.prom_id, isnew:1
                                            };
                                            var gd_limit_rs=await getApp().promiseGet('/api/weshop/ordergoods/getUserBuyGoodsNum',{data:lrs});
                                            if(gd_limit_rs && gd_limit_rs.data.code==0){
                                                pro_by_num=gd_limit_rs.data.data.promgoodsbuynum
                                            }
                                            if(pro_gd_limit_num<pro_by_num+good.goods_num){
                                                yh_check=0;
                                            }
                                        }
                                    }

                                    //-- 优惠促销活动没有超出限购的话 --
                                    if(yh_check){
                                        if(!the_yh_map[gg.prom_id]) the_yh_map[gg.prom_id]=[];
                                        if(prom)  good.discount_field=prom.discount_field;
                                        good.r_shop_price=gg.shop_price;
                                        good.r_market_price=gg.market_price;
                                        the_yh_map[gg.prom_id].push(good);
                                    }

                                    break
                                case 7:
                                    //获取组合购活动
                                    var url = "/api/weshop/prom/zhbuy/get/" + os.stoid + "/" + gg.prom_id + "/" + getApp().globalData.userInfo.user_id;
                                    let zh_buy_info=null
                                    await getApp().request.promiseGet(url, {}).then(res => {
                                        if (res.data.code == 0 && res.data.data) {
                                            zh_buy_info = res.data.data
                                        }
                                    })
                                    //判断活动超出限购
                                    var is_act_ok=1;
                                    let userbuynum = await th.getUserBuyPromNum(gg.prom_id)
                                    if (zh_buy_info.buy_limit !=0 && zh_buy_info && userbuynum >= zh_buy_info.buy_limit) {
                                        is_act_ok=0;
                                    }

                                    //判断活动商品超出限购，在从表
                                    var url1 = "/api/weshop/prom/zhbuyGoods/page";
                                    var req_data = {
                                        page: 1,
                                        pageSize: 1,
                                        store_id: os.stoid,
                                        zh_id: gg.prom_id,
                                        goods_id: gg.goods_id
                                    }
                                    await getApp().request.promiseGet(url1, {
                                        data: req_data
                                    }).then(res => {
                                        if (ut.ajax_ok(res)) {
                                            var gdlist = res.data.data.pageData[0];
                                            gg.buyqty = gdlist.buyqty;
                                        }
                                    })
                                    var num = gg['buyqty'];
                                    //---- 要计算商品的限购 -----
                                    if (gg['buyqty'] > 0) {
                                        if (gg.goods_num + promgoodsbuynum0 > gg['buyqty']) {
                                            is_act_ok=0;
                                        }
                                    }
                                    if(is_act_ok){
                                        var content = gg.goods_name + '商品的活动发生了变化,请取消订单重新购买';
                                        th.toast(content);
                                        t_ok = 0;
                                        break;
                                    }
                            }
                        }
                    }

                    //如果有普通商品要判断能不到达到优惠促销的条件
                    if(Object.keys(the_yh_map).length){
                        for (let rkey in the_yh_map) {
                            var all_price=0;
                            var all_num=0;

                            for(var ij=0;ij<the_yh_map[rkey].length;ij++){
                                var t_price=the_yh_map[rkey][ij].goods_price;
                                switch (the_yh_map[rkey][ij].discount_field){
                                    case 1:
                                        t_price=the_yh_map[rkey][ij].r_shop_price;
                                        break;
                                    case 2:
                                        t_price=the_yh_map[rkey][ij].r_market_price;
                                        break;
                                }

                                all_price+=t_price * the_yh_map[rkey][ij].goods_num;
                                all_num+= the_yh_map[rkey][ij].goods_num;
                            }

                            //-- 只有在单赠品的时候，才要进行计算 --
                            var res= await getApp().request.promiseGet("/api/weshop/goods/getDiscount", {
                                data: {
                                    price: parseFloat(all_price).toFixed(2),
                                    prom_id: rkey,
                                    goods_num: all_num,
                                    user_id: getApp().globalData.user_id,
                                    is_bz: prom.is_bz
                                }
                            })
                            if (res.data.code == 0 && res.data.data && res.data.data.condition){
                                var content = '商品的活动发生了变化,请取消订单重新购买';
                                th.toast(content);
                                t_ok = 0;
                                break;
                            }
                        }

                    }
                    //-- 判断活动是不是OK --
                    if (!t_ok) {
                        th.setData({ paying: 0 }); return false;
                    }

                    // if (!good.is_gift && good.prom_type != 3) {
                    //   var t_ok = 1;
                    //   await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromList/" + os.stoid + "/" + good.goods_id + "/0" + "/" + getApp().globalData.user_id, {}).then(res => {
                    //     if (res.data.code == 0) {
                    //       var r_data = res.data.data;
                    //       //-- 参加了全局的优惠活动 --
                    //       if (r_data.promGoodsLists) {
                    //         var content = gg.goods_name + '商品的活动发生了变化,请取消订单重新购买';
                    //         th.toast(content);
                    //         t_ok = 0;
                    //       }
                    //     }
                    //   })
                    //   if (!t_ok) {
                    //     th.setData({ paying: 0 }); return false;
                    //   }
                    // }
                    //-- 如果有参加线下取价 --
                    if (good.offline_cut > 0) wlist += encodeURIComponent(gg.erpwareid) + ",";
                }
                //赠品和搭配购不判断商品金额
                var isok = 1;
                var card_field = th.data.card_field;

                //-- 如果会员是等级会员,商品有等级价,且不是活动商品，同时线下取价的要放在最后来判断 --
                if (!good.is_gift && !good.is_collocation && gg.prom_type != 9) {

                    //-- 优惠促销的时候控制取价规则 --
                    // gg.prom_type!=3 && gg.prom_type!=10 同时商品不是普通购买的时候，又参与优惠促销，阶梯促销
                    if((gg.prom_type!=3 && gg.prom_type!=10)  || gg.discount_field==undefined || gg.discount_field==0  ) {


                        //判断一下活动是不是有参与订单促销,并且订单促销的活动是不是实收取价,2024-2-23
                        let ordprom_price_type=0;
                        if(order.order_prom_id && good.prom_type==0){
                            let p_rs= await getApp().request.promiseGet("/api/weshop/promorder/get/"+os.stoid+"/"+order.order_prom_id, {});
                            if(p_rs && p_rs.data.code==0 && p_rs.data.data){
                                let ord_p=p_rs.data.data;
                                if(ord_p && ord_p.discount_field>0){
                                    ordprom_price_type=ord_p.discount_field
                                }
                            }
                        }
                        if(ordprom_price_type>0){
                            //-- 看一下订单促销的取价规则 --
                            switch (ordprom_price_type){
                                case 1:
                                    if (good.goods_price != gg.shop_price) isok = 0;
                                    break;
                                case 2:
                                    if (good.goods_price != gg.market_price) isok = 0;
                                    break;
                            }

                        }else {
                            if (card_field && gg[card_field] > 0) {
                                if (good.goods_price != gg[card_field] && good.offline_cut <= 0) isok = 0;
                                if (good.goods_price > gg[card_field] && good.offline_cut > 0) isok = 0;  //如果线下价格比较贵，则不通过

                            } else {
                                if (good.goods_price != gg.shop_price && good.offline_cut <= 0) isok = 0;
                                if (good.goods_price > gg.shop_price && good.offline_cut > 0) isok = 0; //如果线下价格比较贵，则不通过
                            }
                        }
                    }else{
                        if(good.prom_type==3 && good.prom_type==10){
                            switch (gg.discount_field){
                                case 1:
                                    if (good.goods_price != gg.shop_price) isok = 0;
                                    break;
                                case 2:
                                    if (good.goods_price != gg.market_price) isok = 0;
                                    break;
                            }
                       }
                    }

                    var is_h = 0;
                    if (!isok) {
                        var content = gg.goods_name + '商品的价格发生了变化,请取消订单重新购买1'
                        th.toast(content);
                        th.setData({ paying: 0 });
                        return false;
                    }
                }

                //--如果是线下库存的时候--
                if (th.data.conf.sales_rules >= 2 && !gg.whsle_id && !good.is_gift) {
                    var ob = {};
                    await th.check_down_line_next(gg, good.goods_num, order.pickup_id, function (obj) {
                        ob = obj;
                    })
                    if (ob.code == -1) {
                        var content = gg.goods_name + '门店库存不足,请取消订单';
                        th.toast(content);
                        th.setData({ paying: 0 });
                        return false;
                    }

                } else {
                    if (!good.is_gift && good.goods_num > store_count) {

                        var content = gg.goods_name + '商品的库存不足,请取消订单';
                        th.toast(content);
                        th.setData({ paying: 0 });
                        return false;
                    }

                }
            }

            //---如果是活动的时候---
            var prom = null, goodsinfo = good, th = this;

            goodsinfo.prom_type=parseInt(goodsinfo.prom_type+'');
            if (goodsinfo.prom_type == 1) {
                await getApp().request.promiseGet("/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + goodsinfo.prom_id, {}).then(res => {
                    if (res.data.code == 0) {
                        prom = res.data.data;
                        prom.price = prom.user_price;
                    }
                })
            }
            if (goodsinfo.prom_type == 2) {
                await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + good.goods_id + "/" + goodsinfo.prom_id, {}).then(res => {
                    if (res.data.code == 0) {
                        prom = res.data.data;
                        prom.price = prom.price;
                    }
                })
            }

            if (goodsinfo.prom_type == 6 && !good.is_pd_normal) {
                await getApp().request.promiseGet("/api/weshop/teamlist/get/" + os.stoid + "/" + goodsinfo.prom_id, {}).then(res => {
                    if (res.data.code == 0) {
                        prom = res.data.data;
                    }
                })
            }

            if (goodsinfo.prom_type == 4 && !good.is_integral_normal) {
                await getApp().request.promiseGet("/api/weshop/integralbuy/pageIntegralBuyGoodsList?stype=1&stypeup=1&timetype=2", {
                    data: { store_id: os.stoid, goods_id: goodsinfo.goods_id,user_id: getApp().globalData.user_id, }
                }).then(res => {
                    if (res.data.code == 0 && res.data.data && res.data.data.pageData) {
                        prom = res.data.data.pageData[0];
                    }
                })
            }

            if(!prom && [1,2,4,6].includes(goodsinfo.prom_type)){
                wx.showToast({ title: "未找到活动", icon: 'none', duration: 3000 });
                th.setData({ paying: 0 });
                return false;
            }

            //----------如果有活动，并且在进行中，就不计算线下库存---------------
            if (prom) {

                let c_type=parseInt(goodsinfo.prom_type+'');
                var act_type='';
                switch (c_type){
                    case 1:act_type='秒杀';break;
                    case 2:act_type='团购';break;
                    case 6:act_type='拼团';break;
                }
                //指定门店的控制
                if ([1,2,6].indexOf(c_type)>-1 && prom.pick_up_lists) {
                    var idx0=prom.pick_up_lists.findIndex(function (e){
                        return e.pickup_id==order.pickup_id;
                    })
                    if(idx0<0){
                        getApp().confirmBox(goodsinfo.goods_name +act_type+"活动的门店不可售");
                        th.setData({ paying: 0 });
                        return false;
                    }
                }

                var now = ut.gettimestamp();
                if (prom.is_end == 1 || prom.end_time < now) {
                    var content = goodsinfo.goods_name + '商品的活动已经结束,请取消订单'
                    th.toast(content);
                    th.setData({ paying: 0 });
                    return false;
                }

                if(prom.is_show==0){
                    wx.showToast({ title: "活动未启用", icon: 'none', duration: 3000 });
                    th.setData({ paying: 0 });
                    return false;
                }


                buyed_mum2 = promgoodsbuynum + good.goods_num;
                if (buyed_mum2 > prom.buy_limit && prom.buy_limit > 0) {

                    var content = goodsinfo.goods_name + '购买数量超出商品活动限购,请取消订单'
                    th.toast(content);
                    th.setData({ paying: 0 });
                    return false;
                }

                // --看一下会员的秒杀价格是不是发生了变化，因为会员的身份发生了变化
                if (goodsinfo.prom_type == 1 && goodsinfo.goods_price != prom.price) {
                    var content = goodsinfo.goods_name + '秒杀活动的价格发生了变化';
                    th.toast(content);
                    th.setData({ paying: 0 });
                    return false;
                }

                // --看一下会员的团购价格是不是发生了变化
                if (goodsinfo.prom_type == 2 && goodsinfo.goods_price != prom.price) {
                    var content = goodsinfo.goods_name + '秒杀活动的价格发生了变化';
                    th.toast(content);
                    th.setData({ paying: 0 });
                    return false;
                }

                if (goodsinfo.prom_type == 4) {
                    if (good.goods_num > prom.limitqty - prom.buy_num) {

                        var content = goodsinfo.goods_name + '购买数量超出商品活动库存,请取消订单'
                        th.toast(content);
                        th.setData({ paying: 0 });
                        return false;
                    }
                } else if (goodsinfo.prom_type == 1 || goodsinfo.prom_type == 2 || goodsinfo.prom_type == 6) {
                    if (order.add_time + 5 * 60 < ut.gettimestamp()) {
                        var content = gg.goods_name + '该订单已经超时无法支付,请取消订单';
                        th.toast(content);
                        th.setData({ paying: 0 });
                        return false;
                    }
                }

            }

            //-- 预售和幸运购要单独计算 --
            if (goodsinfo.prom_type == 8) {
                var presell_id= goodsinfo.prom_id;
                //------获取预售主表,判断预售活动是不是到期不可以使用了----------
                var res= await getApp().request.promiseGet(`/api/weshop/marketing/marketingPresellForm/get/${os.stoid}/${presell_id}`, {})
                if (res.data.code == 0 && res.data.data) {
                    var act_data = res.data.data;
                    if (act_data.is_end) {
                        wx.showToast({ title: "活动已经结束", icon: 'none', duration: 3000 });
                        return false;
                    }
                    if (act_data.isuse == 0) {
                        wx.showToast({ title: "活动未启用", icon: 'none', duration: 3000 });
                        return false;
                    }

                    var err_txt = "活动定金时间已经结束";
                    var end_time = act_data.end_time;
                    if (act_data.presell_type == 1) {
                        err_txt = "活动时间已经结束";
                    }
                    if (end_time < ut.gettimestamp()) {
                        wx.showToast({ title: err_txt, icon: 'none', duration: 3000 });
                        return false;
                    }

                    if (act_data.presell_type == 0) {
                        end_time = act_data.pay_enddate;
                        err_txt = "活动尾款时间已经结束";
                    }
                    if (end_time < ut.gettimestamp()) {
                        wx.showToast({ title: err_txt, icon: 'none', duration: 3000 });
                        return false;
                    }
                }

                var all_pre_goods=null;
                var userInfo = getApp().globalData.userInfo;
                var pre_data = { store_id: os.stoid, is_end: 0, timetype: 1, isuse: 1, goods_id: goodsinfo.goods_id };
                if (userInfo) {
                    pre_data.user_id = userInfo.user_id;
                }
                var rs_pre= await getApp().request.promiseGet("/api/weshop/marketing/marketingPresellList/page", {
                    data: pre_data,
                })
                if (rs_pre.data.code == 0 && rs_pre.data.data.pageData && rs_pre.data.data.pageData.length > 0) {
                    all_pre_goods = rs_pre.data.data.pageData;
                }

                if(!all_pre_goods){
                    wx.showToast({ title: "未找到活动商品", icon: 'none', duration: 3000 });
                    return false;
                }
                var idx = all_pre_goods.findIndex(function (ele) {
                    return ele.goods_id == goodsinfo.goods_id;
                })

                if(idx==-1){
                    wx.showToast({ title: "未找到活动商品", icon: 'none', duration: 3000 });
                    return false;
                }
                var pre_arr = all_pre_goods[idx];
                var prom_buy_limit = pre_arr.vip_butyqty;

                if (goodsinfo.goods_num > pre_arr.presell_sumqty - pre_arr.buy_goodnum) {
                    wx.showToast({ title: "超出活动商品库存", icon: 'none', duration: 3000 });
                    return false;
                }
                //--判断商品是否超出活动限购--
                if (promgoodsbuynum0 && prom_buy_limit > 0) {
                    wx.showToast({ title: "超出活动商品库存", icon: 'none', duration: 3000 });
                    return false;
                }

            }
            //幸运购的时候
            if (goodsinfo.prom_type == 9 && !good.is_pt_normal) {

                var lk_act=null;
                //获取单个活动成团信息
                var lk_rs= await getApp().request.promiseGet('/api/weshop/prom/luckyActivity/page', {
                    data: {
                        store_id: os.stoid,
                        is_end: 0,
                        timetype: 1,
                        id: goodsinfo.prom_id,
                    }
                });

                if(lk_rs && ut.ajax_ok(lk_rs)){
                    lk_act= lk_rs.data.data.pageData[0];
                }
                if(!lk_act){
                    wx.showToast({ title: "未找到活动，或者活动已结束", icon: 'none', duration: 3000 });
                    th.setData({ paying: 0 });
                    return false;
                }
                // 检查幸运购活动商品库存
                var lk_redis=await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/9/" + goodsinfo.prom_id,{});
                if(!lk_redis || lk_redis<goodsinfo.goods_num ){
                    wx.showToast({ title: "活动商品库存不足", icon: 'none', duration: 3000 });
                    th.setData({ paying: 0 });
                    return false;
                }
            }

        }

        //-- 要判断一下线下取价价格是不是发生改变 --
        if (wlist != "" && th.data.is_open_offline && th.data.is_open_offline > 0) {
            wlist = ut.sub_last(wlist);
            var keyid = order.pickup_id;
            var user_info = getApp().globalData.userInfo;
            if (!keyid) {
                th.setData({ paying: 0 }); return false;
            }
            var offarr = null;
            await getApp().request.promiseGet("/api/weshop/goods/listWarePrice", {
                    data: {
                        VIPId: encodeURIComponent(user_info.erpvipid),
                        store_id: os.stoid,
                        PickupId: keyid,
                        WareIds: wlist
                    },
                },
            ).then(res => {
                if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
                    offarr = res.data.data;
                }
            })
            if (!offarr && offarr.length <= 0) {
                th.toast('获取线下取价失败');
            }
            var newarr = ut.convert_arr_key(offarr, 'WareId');
            //-- 循环判断线下的价格 --
            for (var k in order_goods) {
                var good = order_goods[k];
                //判断线下取价是不是一样
                if (newarr[good.erpwareid] &&
                    parseFloat(newarr[good.erpwareid].WarePrice) != parseFloat(good.goods_price)) {

                    var content = good.goods_name + '商品的价格发生了变化,请取消订单重新购买';
                    th.toast(content);
                    th.setData({ paying: 0 });
                    return false;
                }
            }
        }


        th.data.ok_order_sn=this.data.order.order_sn;
        py.pay(this.data.order.order_sn, function() {
            th.setData({paying:0});
            wx.showToast({title: '支付成功'})
			wx.navigateBack();
        },function () {
            th.setData({paying:0});
        },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){
      //如果默认是商品
      if(getApp().is_virtual(gg)){
        return func(100000);
      }


      var lock=0,pick_no,plist;
      var lock_rq={store_id:os.stoid,wareId:gg.goods_id,storageId:pick_id};
      if(this.data.sales_rules==3){
          log_rq.appoint_pick_keyid=this.data.appoint_pick_keyid;
          delete  log_rq.storageId
      }

	  //先读取门店的lock
	  await getApp().request.promiseGet("/api/weshop/order/ware/lock/page",{
		  data:lock_rq
	  }).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;
		  }
	  })

     if(this.data.sales_rules==2) {
            //先获取门店的编号
            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;
                }
            })
     }

     var sto_rq={storageNos:pick_no,wareIds:encodeURIComponent(gg.erpwareid),storeId:os.stoid};
     if(this.data.sales_rules==3){
         sto_rq.storageIds=this.data.appoint_pick_keyid;
         delete sto_rq.storageNos
     }
     

	  //读取线下的门店库存 
	  await getApp().request.promiseGet("/api/weshop/goods/getWareStorages",{
		  data:sto_rq
	  }).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)  
	},
	  //获取用户参与组合购的次数
  async getUserBuyPromNum(prom_id){
    var userInfo = getApp().globalData.userInfo;
    var url = `/api/weshop/ordergoods/getUserBuyPromNum?store_id=${os.stoid}&user_id=${userInfo.user_id}&prom_type=7&prom_id=${prom_id}`;
    let res = await getApp().request.promiseGet(url, {
      data:{}
    });
    let userbuynum=0
    if(res.data.code==0 && res.data.data){
      userbuynum=res.data.data.userbuynum
    }
    return userbuynum
  },
	
	//再来一单的功能的实现
	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;
          wx.showLoading();
		  //--------获取门店-----------
		  await getApp().request.promiseGet("/api/weshop/pickup/get/" + os.stoid + "/" + item.pickup_id, {
		       
		  }).then(res=>{		
			   pickup = res.data.data;
		  })
          if(!pickup){
                wx.hideLoading();
                getApp().confirmBox("找不到门店");
                this.data.moring=0;
                return false;
          }

            if(pickup.isstop){
                wx.hideLoading();
                getApp().confirmBox("门店已停用");
                this.data.moring=0;
                return false;
            }

          if(!pickup.is_pos){
                wx.hideLoading();
                getApp().confirmBox("门店不允许销售");
                this.data.moring=0;
                return false;
          }
				
		  //--------获取商品----------
		  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];
				var b_item={};
			   //--如果是赠品，不加入购物车--
			  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;
				})
				
				//调用接口判断订单优惠，
				const res = await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromList/" + os.stoid + "/" + g_item.goods_id + "/0"+"/"+getApp().globalData.user_id, {})
				if (res.data.code == 0 && res.data.data) {
						var r_data = res.data.data;
						if (r_data.ladderLists) {
								var act_id = r_data.ladderLists[0].form_id;
								//-- 判断会员能不能参与阶梯促销 --
								const data = await getApp().request.promiseGet("/api/weshop/prom/ladderForm/getNew/" + os.stoid + "/" + user_id + "/" + act_id, {})
								if (data.data.code == 0 && data.data.data && data.data.data.isuse && data.data.data.is_end == 0) {
										b_item.prom_type = 10;
										b_item.prom_id = data.data.data.id;
								}
						}
				}
		  
			  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;
              let user_id = getApp().globalData.userInfo.user_id;
			 
			  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/listGoodActInfo2New";
              var req_data = {
                  store_id: g_item.store_id, goods_id: g_item.goods_id, user_id: user_id
              };
              await getApp().request.promiseGet(url, { data: req_data }).then(res => {
                  if (res.data.code == 0) {

                      var arr = res.data.data;
                      //-- 预热也要计算 --
                      var arr2 = arr.filter(function (e) {
                          return e.s_time < ut.gettimestamp();
                      })

                      if (arr2.length == 1) {
                        good.prom_type = arr2[0].prom_type;
                        good.prom_id = arr2[0].act_id;
                      }
                      else if (arr2.length > 1) {
                          good.prom_type = g_item.prom_type; good.prom_id = g_item.prom_id;
                      }

                      var arr3 = arr.filter(function (e) {
                          return e.s_time < ut.gettimestamp() && e.prom_type == 7;
                      })

                      if (arr3 && arr3.length > 0) {
                          b_item.zh_prom_id= arr3[0].act_id;
                      }

                  }
              })

              //--判断商品当前的活动情况--
              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) {

                          if( 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;
                          }else{
                              if(g_item.prom_type==0 && !flash.is_shop_buy ){
                                  err_text+=g_item['goods_name']+"秒杀活动不允许普通价\n";
                                  continue;
                              }
                          }

                      }
                      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) {

                                var t_act=res.data.data;
                                if(!t_act.zh_num || t_act.zh_num>t_act.zh_buy_num) {

                                    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;
                    case 10:

                        var url = `/api/weshop/prom/ladderForm/getNew/${os.stoid}/${user_id}/${good.prom_id}`;
                        await getApp().request.promiseGet(url, {}).then(res => {
                                if (res.data.code == 0 && res.data.data && res.data.data.isuse && res.data.data.is_end == 0) {
                                        b_item.prom_type = 10;
                                        b_item.prom_id = res.data.data.id;
                                }
                            })
                        break;
                  }

			  
			  //如果有优惠促销的时候,要看下商品的优惠活动有没有过期
			  if((g_item.prom_type==3 || good.prom_type==3) && good.whsle_id<=0){
                  var is_g_prom=0;
                  //因为有全场优惠活动，商品参加的活动还未开始
                  var url="/api/weshop/activitylist/getGoodActInfo";
                  var req_data={
                      store_id:os.stoid,goodsidlist:good.goods_id,is_detail:1,user_id:user_id
                  };
                  await getApp().request.promiseGet(url, {data:req_data}).then(async function (res) {
                      if(res.data.code==0 && res.data.data && res.data.data.length){
                          for(let i in res.data.data){
                              let item=res.data.data[i];
                              if(item.prom_type==3) {
                                  is_g_prom=1; break;
                              }
                          }
                      }
                  })
                  if(is_g_prom) {
                      await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromList/" + os.stoid + "/" + good.goods_id + "/1"+"/"+getApp().globalData.user_id, {}).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;
                              }
                          }
                      })
                  }else{
                      await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromNormal/" + os.stoid + "/" + good.goods_id, {}).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 && !good.whsle_id){
				  
				  //-- 看一下购物车上有多少商品 --
				  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) {


                      var lock_rq={store_id: os.stoid, wareId: good.goods_id, storageId: b_item.pickup_id, pageSize: 1000};
                      if(th.data.sales_rules==3){
                          lock_rq.appoint_pick_keyid=th.data.appoint_pick_keyid;
                          delete lock_rq.storageId;
                      }

                      //先读取门店的lock,
                      await getApp().request.promiseGet("/api/weshop/order/ware/lock/page", {
                          data:lock_rq
                      }).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
                          }
                      })

                      var sto_rq={storageNos: pickup.pickup_no,wareIds: encodeURIComponent(good.erpwareid),storeId: os.stoid };
                      if(th.data.sales_rules==3){
                          sto_rq.storageIds=th.data.appoint_pick_keyid;
                          delete sto_rq.storageNos;
                      }



                      //---通过接口获取门店的线下库存信息--
                      await getApp().request.promiseGet("/api/weshop/goods/getWareStorages", {
                          data: sto_rq
                      }).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,
                      isnew:1,
				  };
                  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,
                      isnew:1,
			      };
			      
			      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){
                            //不允许商品普通价格修改
                            if(!prom.is_shop_buy && prom.is_shop_buy!=undefined) {
                                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+promgoodsbuynum>=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 th=this;
		  var back_goods_arr=this.data.back_goods_arr;     
		  var err_text="";		
		  var ok_num=0;

          var zh_prom_id_err=[];
          var zh_prom_id_err_goods=[];
						  				  
		  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){
                  //3，5，7，10加入购物车，统一prom_type为0
                  if([3,5,7,10].indexOf(g_item.prom_type)>-1){
                      g_item.prom_type=0;
                      g_item.prom_id=0;
                  }
			  	  newd['prom_type']=g_item.prom_type;
			  	  newd['prom_id']=g_item.prom_id;
			  }


              newd['zh_prom_id']=0;

              if(g_item.zh_prom_id){
                  newd['zh_prom_id'] = g_item.zh_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;
				  }			  
			  })


              //-- 判断购物车是不是有重复 --
              var is_has=0;
              if(b_cart_goods) {
                  for (let jr = 0; jr < b_cart_goods.length; jr++) {
                      var b_cart_item = b_cart_goods[jr];
                      if (!g_item.prom_type || g_item.prom_type == 0) {
                          if ([0, 3, 5, 7, 10].indexOf(b_cart_item.prom_type) > -1) {
                              is_has = b_cart_item;
                              break
                          }
                      } else {
                          if (b_cart_goods.prom_type == g_item.prom_type && b_cart_goods.prom_id == g_item.prom_id) {
                              is_has = b_cart_item;
                              break
                          }
                      }
                  }
              }

			 
			  //-- 如果就加入过购物车 --
			  if(is_has){
				  var updata = {
				     id: is_has.id,
				     goods_num: newd.goods_num + is_has.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;
				  }

                  if (newd.prom_type) {
                      updata.prom_type = newd.prom_type;
                      updata.prom_id = newd.prom_id;
                  }

                  if(newd['zh_prom_id']){
                    updata.zh_prom_id=newd['zh_prom_id'];
                  }

                  //如果购物车中商品zh_prom_id不一致的话，要进行提示
                  if(is_has.zh_prom_id>0 && is_has.zh_prom_id!= newd['zh_prom_id'] ){
                      zh_prom_id_err.push(newd.goods_name+ '已在购物车\n');
                      zh_prom_id_err_goods.push(updata);
                      continue;
                  }

				  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(zh_prom_id_err_goods && zh_prom_id_err_goods.length){
            if(err_text){
                err_text+="同时有以下商品：\n";
            }
            err_text+=zh_prom_id_err.join('');
            err_text+="是否替换参与该活动？"

            // 如果没有获取用户信息
            wx.showModal({
                title: '提示',
                content: err_text,
                success(res) {
                    if (res.confirm) {
                        //进行对有zh_prom_id 不一样的商品进行替换
                        th.zhbuy_add_cart(zh_prom_id_err_goods)
                    }
                }
            });


        }else {

            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");
                            }
                        }
                    });

                }

            }
        }
	},

    //-- 组合购的商品重新购买 --
    zhbuy_add_cart: async function (zh_prom_id_err_goods) {
        var err_text = "";
        for (var i in zh_prom_id_err_goods) {
            var updata=zh_prom_id_err_goods[i];
            await getApp().request.promisePut("/api/weshop/cart/update", {
                data: updata
            }).then(res => {
                if (res.data.code != 0) {
                    err_text += newd.goods_name + "加入购物车失败\n";
                }
            })
        }

        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) {
	    var user_id=getApp().globalData.user_id;
	    if(!user_id) user_id=0;

        var gd_item= e.currentTarget.dataset.gd;
        var gd=gd_item.goods_id;

        if(gd_item.prom_type>0){
            good_url = "/pages/goods/goodsInfo/goodsInfo?goods_id=" + gd + "&prom_id=" + gd_item.prom_id + "&prom_type="+gd_item.prom_type;
            getApp().goto(good_url);
            return false;
        }

        var good_url="/pages/goods/goodsInfo/goodsInfo?goods_id=" + gd;
        var url="/api/weshop/activitylist/getGoodActInfo";
        var req_data={
            store_id:os.stoid,goodsidlist:gd,is_detail:1,user_id:user_id
        };
        //获取秒杀的多规格
        getApp().request.promiseGet(url, {data:req_data}).then(res=>{
            if(res.data.code==0 && res.data.data){
                if(res.data.data.length==1){
                    var item=res.data.data[0];
                    switch (item.prom_type){
                     	case 9:
                            good_url= '/packageC/pages/luckyGo/luckyGo_goodsInfo/luckyGo_goodsInfo?goods_id=' + gd + '&group_id=' + item.act_id;
                     		break;
                     	case 8:
                            good_url="/packageC/pages/presell/goodsInfo/goodsInfo?goods_id="+gd+"&prom_id="+item.act_id
                     		break;
                     	default:
                            good_url="/pages/goods/goodsInfo/goodsInfo?goods_id="+gd+"&prom_id="+item.act_id+"&prom_type="+item.prom_type;
                     	 	break
                     }
                }
                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);
    },

    //优惠促销用户参与次数,is_buy=1，表示只获取支付了的
    async getUserBuyPromNum_pre(prom_id,is_buy) {
        var userInfo = getApp().globalData.userInfo;
        var url = `/api/weshop/ordergoods/getUserBuyPromNum?is_all=1&store_id=${os.stoid}&user_id=${userInfo.user_id}&prom_type=3&prom_id=${prom_id}`;
        if(is_buy){
            url = `/api/weshop/ordergoods/getUserBuyPromNum?store_id=${os.stoid}&user_id=${userInfo.user_id}&prom_type=3&prom_id=${prom_id}`;
        }
        let res = await getApp().request.promiseGet(url, {
            data: {}
        });
        let user_pre_buynum = 0
        if (res.data.code == 0 && res.data.data) {
            user_pre_buynum = res.data.data.userbuynum
        }
        return user_pre_buynum
    }





});