var t = getApp(),
  a = t.request,
  oo = t.globalData.setting,
  os = oo,
  app = getApp(),
  rq = t.request,
  ut = require("../../../utils/util.js"),
  zh_calc = require("zh_calculate.js"),
  ladder_calc = require("ladder_calculate.js");
var regeneratorRuntime = require('../../../utils/runtime.js');
const e = require("../../../utils/common.js");
//公共的函数合并在一起
const m_cx = require("../../../utils/more_cx.js");

Page({
  data: {
    url: t.globalData.setting.url,
    resourceUrl: t.globalData.setting.resourceUrl,
    iurl: t.globalData.setting.imghost,
    requestData: null,
    checkAllToggle: 0,
    total_fee: 0, //结算金额
    total_num: 0, //结算数量
    all_num: 0, //购物车中所有商品数量
    allsto: null,
    imgUrl: t.globalData.setting.imghost,
    is_has_flash: 0, //是否又秒杀活动
    is_edit: 0, //是否编辑
    is_load: 0, //是否已加载
    up_dating: 0, //更新中
    isreduce: 0, //商品数量是否可减
    isadd: 0, //是否可以加商品数量
    invalidList: [], //失效商品列表

    card_field: "",
    bconf: null,
    btn_click: 1,

    service_data: null,
    max_sw_height: 200,

    zhhe_prom: [], //组合活动需要显示差多少件
    zuhe_map: {},
    zuhe_map_good: {},

    in_zhact_gdmap: {}, //不同门店参与同一活动的限购
    in_zhact: {}, //组合购活动在列表中的显示
    in_yhact: {}, //优惠活动在列表中的显示
    in_zh_gd_buy_map: {}, //就是商品在组合购中的

    ladder_map: {}, //阶梯促销需要的map

    promgoods_map: {},
    promgoods_list: {},

    in_zhact_gdmap_new: {}, //不同门店参与同一活动的限购，这些都是map表，是多促销互动专用，不能和in_zhact_gdmap重叠
    in_zhact_new: {}, //组合购活动在列表中的显示 是多促销互动专用，不能和in_zhact重叠
    in_yhact_new: {}, //组合购活动在列表中的显示 是多促销互动专用，不能和in_yhact重叠

    is_cart:1, //标记是购物车计算的时候

    //送赠品的优化
    cart_zp:{},
    //-- dp_cart深拷贝的缓存 --
    dp_cart:null,

    //优惠促销活动的集合
    yhcx_act_map: {},
    //-- 活动的购买数量的map --
    act_buy_map:{}
  },


  onLoad: function () {
    var a = this,
      ee = a;

    wx.setNavigationBarTitle({
      title: "购物车",
    })

    //判断是否有登录
    t.auth.hadAuth() && t.getUserInfo(function () {
      //a.getCardList();
    });

  },
  onShow: function () {

    //-- 清空 checkouting 结算的标记 --
    this.data.checkouting=0;

    if(getApp().globalData.from_act_link){
        this.data.from_act_link= ut.deep_cp(getApp().globalData.from_act_link);
        getApp().globalData.from_act_link=null;
    }

    //-- 看一下隐私政策要不要显示 --
    var privacy_pop = this.selectComponent("#privacy_pop"); //组件的id
    if (privacy_pop) {
      privacy_pop.check_pri_show();
    }

    //每次显示都清空
    this.data.in_zhact_gdmap = {};
    this.setData({
      invalidList: [],
      cart_zp:{}  //-- 赠品也要清理显示 --
    });

    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      var index = getApp().getPageIndex(this);
      this.getTabBar().setData({
        active: index //数字是当前页面在tabbar的索引
      })
      getApp().requestCardNum(this);
    }

    var th = this;
    this.setData({
      requestData: null,
      is_load: 0
    });
    //调用底部导航
    //t.editTabBar(th,getApp().globalData.setting.stoid,getApp().globalData.url);
    //----获取系统参数-----
    getApp().getConfig2(function (e) {
      var json_d = JSON.parse(e.switch_list);
      var is_open_offline = json_d.is_pricing_open;
      th.setData({
        bconfig: e,
        json_d: json_d,
        freight_free: e.freight_free,
        weight_free: e.weight_free,
        sales_rules: e.sales_rules,
        appoint_pick_keyid: json_d.appoint_pick_keyid
      });
      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;
        th.getCardList();
      });

    }, 1)

    //-- 判断有没有自定义的广告图片 --
    getApp().request.promiseGet("/api/weshop/ad/page?pid=1101&store_id=" + os.stoid, {
      data: {
        enabled: 1
      }
    }).then(res => {
      if (ut.ajax_ok(res)) {
        var a = res.data.data.pageData;
        var narr = [];
        for (var i in a) {
          var tt = {
            'ad_code': os.imghost + a[i].ad_code,
            'media_link': '',
            'ad_weapplink': a[i].ad_weapplink
          };
          narr.push(tt);
        }
        th.setData({
          ad_data: narr
        });
      } else {

        var user_id = getApp().globalData.user_id;
        if (!user_id) user_id = 0;
        var req_d = {
          store_id: oo.stoid,
          timetype: 2,
          is_end: 0,
          is_show: 1,
          pageSize: 1,
          user_id: user_id
        }
        //--获取是否又秒杀活动--
        getApp().request.promiseGet("/api/ms/flash_sale/spikepage", {
          data: req_d,
        }).then(res => {
          if (ut.ajax_ok(res)) {
            th.setData({
              is_has_flash: 1
            })
          }
        });
      }
    })


  },

  onHide() {
    this.data.zuhe_map = {};
    this.data.promgoods_map = {};
    this.data.promgoods_list = {};
  },
  onUnLoad() {
    getApp().globalData.cart_zh_act = null;
  },

  //失效商品处理
  // invType 表示失效的原因，classType 表示类别 0 表示商品，1表示服务
  disInvalid(item, invType = 0, classType = 0) {
    let invalidList = this.data.invalidList;
    let off = true;
    console.log('失效商品-----1')
    console.log(item)
    console.log('失效商品-----2')
    invalidList.map(ite => {
      if (classType == 0 && ite.goods_id == item.goods_id) { //判断该商品是否存在于失效列表中
        off = false;
      }
      if (classType == 1 && ite.service_id == item.service_id) { //判断该商品是否存在于失效列表中
        off = false;
      }
    });
    if (off) {
      if (invType == 0) {
        item.invalid = '商品活动变动';
      } else if (invType == 1) {
        item.invalid = '商品已下架';
      } else {
        item.invalid = "商品超出限购"
      }
      item.classType = classType
      invalidList.push(item);
      this.setData({
        invalidList
      });
    }
  },
  //-------------获取购物车列表,要安装门店进行分类订单-----------
  getCardList: function () {
    this.setData({
      invalidList: []
    }); //重置失效商品
    var th = this;

    //要获取会员是不是等级会员
    getApp().getConfig2(function (conf) {
      //--- 看后台是不是有开通等级卡 ---
      if (conf.switch_list) {
        var s_list = JSON.parse(conf.switch_list);
        var user = getApp().globalData.userInfo;
        //如果后台有开启等级价的功能
        if (user && 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
            })
          }
        }

        //如果门店还未读出来的时候
        if (th.data.allsto == null) {
          //读取门店
          app.get_allsto(function (e) {
            th.setData({
              allsto: e
            });
            th.get_cart();
            th.get_ser_cart();
          })
        } else {
          th.get_cart();
          th.get_ser_cart();
        }


      }
    })
    if ((!this.data.requestData || this.data.requestData.length == 0) && (!this.data.service_data || this.data.service_data.length == 0)) {
      setTimeout(function () {
        var goods_list = th.selectComponent("#goods_list"); //组件的id
        if (goods_list) {
          goods_list.init();
          goods_list.get_list();
        }
      }, 800)
    }
  },

  //失效单选
  inCheck_th_item: async function (e) {
    console.log('失效单选');
    console.log(e);
    let i = e.currentTarget.dataset.item;
    let invalidList = this.data.invalidList;
    console.log(i)
    console.log(invalidList[i])
    invalidList[i].selected = invalidList[i].selected == 1 ? 0 : 1;
    console.log(invalidList);
    this.setData({
      invalidList
    });
    console.log(this.data.invalidList);
    // this.doCheckAll();

  },


  //清空失效宝贝
  delInva_all(obj = null) {

    var th = this;
    wx.showModal({
      title: '提示',
      content: '确认要清空全部失效商品吗?',
      success(res) {
        if (res.confirm) {
          th.delInva(obj);
        }
      }
    })
  },


  delInva(obj) {
    var th = this;
    let ainvalid = '';
    let binvalid = '';
    var user_id = getApp().globalData.user_id;

    let ab = 0; //选中
    let abc = 0; //
    let arr = obj.id ? [obj] : th.data.invalidList
    console.log('失效-----')
    console.log(arr);
    arr.map(item => {
      if (item.classType == 0) {
        ainvalid += item.id + ',';
        ab = 1;
      }
      if (item.classType == 1) {
        binvalid += item.id + ',';
        abc = 1;
      }
    });


    if (ab == 0 && abc == 0) {
      t.my_warnning('没有需要清空的失效宝贝', 0, th);
      return false;
    }
    if (ab) {
      ainvalid = ainvalid.substring(0, ainvalid.length - 1);
      //要删除购物车中的商品
      var url = '/api/weshop/cart/delIds/' + oo.stoid + '/' + user_id + '/' + ainvalid;
      getApp().request.delete(url, {
        success: function (t) {
          th.getCardList();
          getApp().requestCardNum(th);
        }
      });
    }
    if (abc) {
      binvalid = binvalid.substring(0, binvalid.length - 1);
      //要删除购物车中的商品
      var url = '/api/weshop/cartService/delIds/' + oo.stoid + '/' + user_id + '/' + binvalid;
      getApp().request.delete(url, {
        success: function (t) {
          th.getCardList();
          getApp().requestCardNum(th);
        }
      });
    }
  },


  //---------点击收藏------------
  collectGoods: async function () {

    let t = this
    let timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    let d = {
      // goods_id: t.data.data.goods_id,
      user_id: app.globalData.user_id,
      store_id: oo.stoid,
      add_time: timestamp,
    };
    //加入收藏夹就是导购的ID
    if (getApp().globalData.guide_id) {
      d.guide_id = getApp().globalData.guide_id;
      d.guide_type = 2;
    }
    let off = false
    let errOff = false
    var invalidList = [...this.data.invalidList]
    var arr = []
    invalidList.map(async (item, index) => {
      if (item.selected) {
        off = true
        if (item.classType == 1) {
          d.goods_id = item.service_id
          d.type = 1
        } else {
          d.goods_id = item.goods_id
          d.type = 0
        }
        let is_collect = 0
        //------是否收藏----------
        await getApp().request.promiseGet("/api/weshop/goodscollect/page", {
          data: {
            store_id: oo.stoid,
            goods_id: d.goods_id,
            user_id: app.globalData.user_id,
          }
        }).then(res => {
          let t = res;
          let data = t.data.data.pageData;
          if (data && data.length > 0) {
            is_collect = 1
          }
        })
        if (is_collect) {
          t.delInva(item)
          return
        }
        await getApp().request.post("/api/weshop/goodscollect/save", { //添加收藏
          data: d,
          success: function (e) {
            t.data.is_collect_load = 0;
            if (e.data.code == 0) {
              t.delInva(item)
            } else {
              errOff = true
              arr.push(item)
            }
          }
        });
      } else {
        arr.push(item)
      }
    });
    if (off) {
      t.setData({
        invalidList: arr
      })
      if (errOff) {
        getApp().my_warnning('移到收藏夹错误', 0, t);
      } else {
        wx.showToast({
          title: "收藏成功",
          icon: 'none',
          duration: 2000
        })
      }
      console.log('移动成功')
    } else {
      getApp().my_warnning('请先选择失效宝贝', 0, t);
    }
  },

  //-----真的获取购物车--------
  get_cart: function () {
    var th = this;
    th.data.in_zhact_gdmap = {};
    th.data.ladder_map = {};
    th.data.zuhe_map = {};
    th.data.zuhe_map_good = {};

    var rd = Math.random().toString(36).substr(2, 15);
    var user_id = getApp().globalData.user_id;

    wx.showLoading();

    //一次性把购物车selected状态变成0
    var url = '/api/weshop/cart/updateUserCart';
    getApp().request.put(url, {
      data: {
        user_id: app.globalData.user_id,
        store_id: oo.stoid,
        selected: 0,
        state:0
      }
    });

    if(!app.globalData.user_id){

      th.setData({
        requestData: [],
        all_num: 0,
        is_edit: 0,
        checkAllToggle:0
      }),wx.stopPullDownRefresh();

      wx.hideLoading();

      return false;
    }

    getApp().request.get("/api/weshop/cart/listNew1", {
      data: {
        user_id: app.globalData.user_id,
        rd: rd,
        store_id: oo.stoid,
        pageSize: 600,
        state: 0
      },
      success: async function (su) {
        console.log(su, 10000);
        //按门店分类的数组
        var arr = new Array();
        var carr=[];

        if(ut.ajax_ok(su))
           carr = su.data.data.pageData;
        var all_num = 0;

        if (carr && carr.length > 0) {
          var g_arr = [];
          var by_map = null;

          for (var i = 0; i < carr.length; i++) {
            //填充一下已经买了多少件，只有在商品是有限购条件的时候才进行计算good.viplimited>0
            if(carr[i].viplimited>0){
              if(!by_map) by_map={};
              by_map[carr[i].goods_id] = carr[i].goodsbuynum?carr[i].goodsbuynum:0;
            }

            //如果不是活动的时候,不是代发商品的时候,不是赠品的时候
            if([1, 2, 4, 6, 8, 9].indexOf(carr[i].prom_type)== -1 && !carr[i].whsle_id && !carr[i].is_gift ){

              //快速查找
              let f_idx=g_arr.findIndex(function (ele) {
                return ele.goods_id == carr[i].goods_id
              });
              if(f_idx>-1) continue;

              let gd_ite={
                goods_id:carr[i].goods_id,
                goods_num:1,
                is_limit_show:0,
                is_state:0,
                zh_prom_id:carr[i].zh_prom_id
              }
              g_arr.push(gd_ite);
            }
          }

          //获取商品参与的促销活，优惠促，搭配促，组合促，阶梯促销
          let cx_rs= await getApp().request.promisePost("/api/weshop/cart/listGoodsPromInfo",{
            is_json:1,
            data:{
              user_id:app.globalData.user_id,
              store_id:oo.stoid,
              goods:g_arr,
            }
          });
          //-- 判断返回结果有没有正确,有促销活动就要进行赋值 --
          if(cx_rs && cx_rs.data.code==0 && cx_rs.data.data && cx_rs.data.data.goods) {
            let g_list=cx_rs.data.data.goods;
            for (var ia = 0; ia < carr.length; ia++) {
              if (carr[ia].whsle_id) continue; //代发商品不进行赋值
              if (carr[ia].is_gift) continue;  //赠品不进行赋值
              //有参与秒，团购之类的活动不进行赋值
              if([1, 2, 4, 6, 8, 9].indexOf(carr[ia].prom_type)> -1 ) continue;
              //再g_list中快速查找
              let i_fd=g_list.find(function (ele) {
                return ele.goods_id == carr[ia].goods_id
              });
              if(i_fd.goodsPromInfoRespDto){
                //-- 多促销活动的优化 --
                i_fd=i_fd.goodsPromInfoRespDto;
                //-- 赋值多促销活动的优化--
                carr[ia].more_cx=i_fd.more_cx;
                //商品优惠促销的缓存
                if (i_fd.yhcx_pro) {
                  th.data.yhcx_act_map[i_fd.yhcx_pro.id] = i_fd.yhcx_pro;
                }
                //商品组合促销的缓存
                if (i_fd.zh_pro) {
                  th.data.zuhe_map[i_fd.zh_pro.id] = i_fd.zh_pro;
                }
                //商品阶梯促销的缓存
                if (i_fd.ladder_pro) {
                  var ladder_pro = i_fd.ladder_pro;
                  th.data.ladder_map[ladder_pro.id] = ladder_pro;
                  var fd_ite = i_fd.more_cx.find(function (e) {
                    return e.prom_type == 10;
                  })
                  if (fd_ite) {
                    th.data.ladder_map[ladder_pro.id].ladder_list = fd_ite.ladder_list;
                  }
                }
              }

            }
          }



          let cart_up_data=[];
          for (var i = 0; i < carr.length; i++) {
            var item = carr[i];
            var good = item;

            if (item.is_gift) {
              var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
              getApp().request.delete(url, {
                success: function (t) {}
              });
              //商品已经下架
              continue;
            }


            var tt = ut.gettimestamp();
            //如果商品下架了，或者商品是赠品，一开始都要清除
            if ((good.down_time > 0 && good.down_time < tt) || good.is_on_sale == 0) {
              // var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
              // getApp().request.delete(url, {
              //     success: function (t) {}
              // });
              th.disInvalid(item, 1);
              //商品已经下架
              continue;
            }
            var goodsbuynum = 0,
              promgoodsbuynum = 0,
              limit = 0;
            if (by_map && by_map[good.goods_id]) {
              goodsbuynum = by_map[good.goods_id];
              //promgoodsbuynum = by_map[good.goods_id].promgoodsbuynum;
            }

            limit = good.viplimited;
            //判断商品的限购
            if (item.goods_num + goodsbuynum > limit && limit > 0) {
              var cbuy = limit - goodsbuynum;
              if (cbuy <= 0) {
                // var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
                // a.delete(url, {});
                th.disInvalid(item, 2);
                continue;
              }
              //-- 购物车更新 --
              var updata1 = {
                id: item.id,
                goods_num: cbuy,
                store_id: os.stoid,
                user_id: getApp().globalData.userInfo.user_id
              };
              getApp().request.put("/api/weshop/cart/update", {
                data: updata1,
              })
              item.goods_num = cbuy;
            }

            //-- 如果有优惠促销，和阶梯促销，要看下有没有组合购，搭配购，看一下优惠促销和阶梯促销谁是指定商品参与的 --
            if (item.prom_type == 0 || item.prom_type == 3 || item.prom_type == 5 || item.prom_type == 7 || item.prom_type == 10) {
              var c_prom_type = 0;
              var c_prom_id = 0;

              item.prom_type = c_prom_type;
              item.prom_id = c_prom_id;

              if (th.data.card_field && good[th.data.card_field]) {
                item.goods_price = good[th.data.card_field]; //要同步下线商品的id
              } else {
                item.goods_price = good.shop_price;
              }
              //-- 购物车更新 --
              var updata1 = {
                  id: item.id,
                  prom_type: c_prom_type,
                  prom_id: c_prom_id,
                  store_id: os.stoid,
                  user_id: getApp().globalData.userInfo.user_id,
                  goods_price:item.goods_price
              };
              // getApp().request.put("/api/weshop/cart/update", {
              //   data: updata1,
              // })
              cart_up_data.push(updata1);
            }

            //判断如果是普通商品，后面参加活动了，变成失效商品
            if (item.prom_type == 0) {

              var prom = null;
              var now = ut.gettimestamp();
              let prom_arr = item.goodsActinfo;
              if(prom_arr && prom_arr.length){
                for (var im = 0; im <prom_arr.length; im++) {
                  var a_item = prom_arr[im];
                  if (a_item.s_time < now) {
                    if (!prom) prom = [];
                    prom.push(a_item);
                  }
                }
              }

              //只有一种活动，但是又是秒杀之类是互动，就要失效。不能是普通购买
              if (prom && prom.length == 1 && [1, 2, 4, 6, 8, 9].indexOf(prom[0].prom_type) > -1 && !item.is_integral_normal && !item.is_pd_normal) {
                th.disInvalid(item);
                continue;
              }

              //只有秒杀和积分购的时候，不能是普通购买
              if (prom && prom.length == 2 && !item.is_integral_normal && !item.is_pd_normal) {
                var idx=prom.findIndex(function (e){
                  return e.prom_type==1;
                })
                var idx2=prom.findIndex(function (e){
                  return e.prom_type==4;
                })
                //--如果是有秒杀和积分的时候--
                if(idx>-1 && idx2>-1){
                  th.disInvalid(item);
                  continue;
                }
              }

            }

            //优化获取商品的活动购买了几件
            if (item.prom_type == 1 || item.prom_type == 2) {
              if(item.promgoodsbuynum){
                promgoodsbuynum=item.promgoodsbuynum;
              }
            }
            //如果秒杀活动都去掉了，或者结束了，那么这个商品也没有必要留着
            if (item.prom_type == 1) {
              var prom = item.cartActinfo;
              var now = ut.gettimestamp();
              if(prom){
                prom.price = prom.user_price;
              }
              //---如果互动都已经过期，或者还未开始，或者无活动
              if (!prom || prom.is_end == 1 || prom.end_time < now || prom.start_time > now) {
                // var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
                // a.delete(url, {
                //     success: function (t) {}
                // });
                th.disInvalid(item);
                //商品已经下架
                continue;
              }
              //把活动写入
              item.prom=prom;

              //判断秒杀的限购
              if (item.goods_num + promgoodsbuynum > prom.buy_limit && prom.buy_limit > 0) {
                var cbuy = prom.buy_limit - promgoodsbuynum;
                if (cbuy <= 0) {
                  // var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
                  // a.delete(url, {});
                  th.disInvalid(item, 2);
                  continue;
                }
                //-- 购物车更新 --
                var updata1 = {
                  id: item.id,
                  goods_num: cbuy,
                  store_id: os.stoid,
                  user_id: getApp().globalData.userInfo.user_id
                };
                getApp().request.put("/api/weshop/cart/update", {
                  data: updata1,
                })
                item.goods_num = cbuy;
              }

              //价格不对，就要更新一下
              if (good.goods_price != prom.price) {
                good.goods_price = prom.price;
                //-- 购物车更新秒杀价格 --
                var updata1 = {
                  id: item.id,
                  goods_price: prom.price,
                  store_id: os.stoid,
                  user_id: getApp().globalData.userInfo.user_id
                };
                getApp().request.put("/api/weshop/cart/update", {
                  data: updata1,
                })
              }
            }
            // 判断团购活动都去掉了，或者结束了，那么这个商品也没有必要留着
            else if (item.prom_type == 2) {
              var prom = item.cartActinfo;
              var now = ut.gettimestamp();
              if(prom){
                prom.price = prom.user_price;
              }

              //---如果互动都已经过期，或者还未开始，或者无活动
              if (!prom || prom.is_end == 1 || prom.end_time < now || prom.start_time > now) {
                // var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
                // a.delete(url, {
                //     success: function (t) {}
                // });
                console.log('团购活动-----');
                th.disInvalid(item);
                //商品已经下架
                continue;
              }

              //把活动写入
              item.prom=prom;

              //判断团购的限购
              if (item.goods_num + promgoodsbuynum > prom.buy_limit && prom.buy_limit > 0) {
                var cbuy = prom.buy_limit - promgoodsbuynum;
                if (cbuy <= 0) {
                  // var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
                  // a.delete(url, {});
                  th.disInvalid(item, 2);
                  continue;
                }
                //-- 购物车更新 --
                var updata1 = {
                  id: item.id,
                  goods_num: cbuy,
                  store_id: os.stoid,
                  user_id: getApp().globalData.userInfo.user_id
                };
                getApp().request.put("/api/weshop/cart/update", {
                  data: updata1,
                })
                item.goods_num = cbuy;
              }

            }


            all_num += item.goods_num;
            item.original_img = oo.imghost + item.original_img;
            item.selected = 0;
            item.erpwareid = good.erpwareid; //要同步下线商品的id
            item.shop_price = good.shop_price; //要同步下线商品的id
            item.init_goods_price=good.goods_price;

            //-- 读出每一种商品的所有的活动,方便后面的活动切换使用 --
            //if (item.prom_type == 0) th.buy_pro_group(item, 0);

            var pcid = item.pick_id;
            var find = 0;
            //---------循环查找门店---
            if (arr.length > 0) {
              for (var j = 0; j < arr.length; j++) {
                if (arr[j].pid == pcid) {
                  arr[j].goods.push(item);
                  find = 1;
                  break;
                }
              }
            }

            //------如果没有找到-----
            if (find == 0) {
              var pikname = '';
              //找到门店名称
              for (var k = 0; k < th.data.allsto.length; k++) {
                if (pcid == th.data.allsto[k].pickup_id) {
                  pikname = th.data.allsto[k].pickup_name;
                  break;
                }
              }
              var narr = new Array();
              narr.push(item);
              var ie = {
                pid: pcid,
                pname: pikname,
                goods: narr,
                selected: 0
              };
              arr.push(ie);
            }
          }

          //更新一下购物车商品的活动信息
          if(cart_up_data.length>0){
               getApp().request.promisePost('/api/weshop/cart/updateCartPromInfo',{
                   is_json:1,
                   data:cart_up_data
               })
          }
        }
        if (th.data.is_open_offline && th.data.is_open_offline > 0 && th.data.sales_rules == 2) {
          //-- 此时要实时更新线下取价价格 --
          for (var i = 0; i < arr.length; i++) {
            //每个门店都去看下线下取价
            var list = arr[i];
            await th.set_offline(list);
          }
        } else {
          //-- 此时要实时更新线下取价价格 --
          for (var ij in arr) {
            //每个门店都去看下线下取价
            var list = arr[ij];
            for (var i in list.goods) {
              list.goods[i].offline_price = 0
            }
          }
        }

        //-- 2024-2-3 深拷贝数据缓存 --
        th.data.dp_car=ut.deep_cp(arr);
        th.setData({
            requestData: arr,
            all_num: all_num,
            is_load: 1,
            is_edit: 0,
            checkAllToggle:0
          }),
          th.doCheckAll(), wx.stopPullDownRefresh();

          wx.hideLoading();

      }
    });
  },
  //商品购物车修改
  cartUpFn(item) {
    let updata1 = {
      id: item.id,
      prom_type: 0,
      prom_id: 0,
      store_id: os.stoid,
      user_id: getApp().globalData.userInfo.user_id
    };
    getApp().request.put("/api/weshop/cart/update", {
      data: updata1,
    })
  },
  //-----真的获取购物车--------
  get_ser_cart: function () {
    var th = this;
    var user_id = getApp().globalData.user_id;
    var rd = Math.random().toString(36).substr(2, 15);
    getApp().request.get("/api/weshop/cartService/page", {
      data: {
        user_id: app.globalData.user_id,
        rd: rd,
        store_id: oo.stoid,
        pageSize: 600,
      },
      success: async function (su) {
        //按门店分类的数组
        var arr = new Array(),
          carr = su.data.data.pageData;
        var all_num = 0;

        if (carr && carr.length > 0) {
          for (var i = 0; i < carr.length; i++) {
            var item = carr[i];
            var good = null;

            //-- 全部清除不选中 --
            rq.promisePut("/api/weshop/cartService/update", {
                data: {
                  id: item.id,
                  selected: 0,
                  store_id: oo.stoid
                }
            });

            await getApp().request.promiseGet("/api/weshop/serviceCard/get/" + oo.stoid + "/" + item.service_id, {}).then(res => {
              if(res.data.code==0 && res.data.data){
                 good = res.data.data;
              }
            })
            if (!good) {
              //-- 找不到就要删除 --
              var url = '/api/weshop/cartService/del/' + oo.stoid + '/' + item.id;
              getApp().request.delete(url, {
                  success: function (t) {}
              });
              continue;
            }

            //如果商品下架了，或者商品是赠品，一开始都要清除
            if (good.is_show == 0) {
              // var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
              // getApp().request.delete(url, {
              //     success: function (t) {}
              // });
              th.disInvalid({
                ...item,
                original_img: good.imgUrl
              }, 1, 1);
              //商品已经下架
              continue;
            }

            carr[i].sto_list=good.storageId;

            if (item.prom_type == 0 && !item.is_integral_normal && !item.is_pd_normal ) {
              var prom = null;
              var now = ut.gettimestamp();
              await getApp().request.promiseGet(`/api/weshop/activitylist/listGoodActInfo2`, {
                data: {
                  store_id: oo.stoid,
                  goods_id: item.service_id,
                  user_id: user_id,
                  goods_type: 1,
                }
              }).then(res => {
                console.log('服务卡活动信息')
                console.log(res)
                console.log('服务卡活动信息-------------')
                if (res.data.code == 0) {
                  prom = res.data.data
                }
              })
              if (prom) {
                th.disInvalid({
                  ...item,
                  original_img: good.imgUrl
                }, 2, 1)
                continue;
              }
            }


            //秒杀和团购都能加入购物车
            if( [1,2].indexOf(item.prom_type)>-1) {
              var prom = null;
              var now = ut.gettimestamp();

              //获取秒杀
              if(item.prom_type==1) {
                await getApp().request.promiseGet('/api/ms/flash_sale/getNew/' + os.stoid + '/' + user_id + '/' + item.prom_id, {}).then(res => {
                  if (res.data.code == 0 && res.data.data) {
                    prom = res.data.data;
                    prom.price = prom.user_price;
                  }
                });
              }

              //获取团购
              if(item.prom_type==2) {
                await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + item.service_id + "/" + item.prom_id, {}).then(res => {
                  if (res.data.code == 0) {
                    prom = res.data.data;
                  }
                });
              }



              console.log('服务的秒杀信息')
              console.log(prom)
              //---如果互动都已经过期，或者还未开始，或者无活动
              if (!prom || prom.is_end == 1 || prom.end_time < now || prom.start_time > now) {
                th.disInvalid({
                  ...item,
                  original_img: good.imgUrl
                }, 0, 1);
                continue;
              }

              item.prom=prom;
              //判断秒杀的限购
              var msNum = 0
              await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum", {
                data: {
                  store_id: os.stoid,
                  user_id: user_id,
                  card_id: prom.goods_id,
                  prom_type: item.prom_type,
                  prom_id: item.prom_id
                }
              }).then(res => {
                if (res.data.code == 0) {
                  msNum = res.data.data.promcardbuynum,
                  console.log('秒杀限购：' + msNum)
                }
              })
            }
            if (msNum && (msNum >= prom.buy_limit && prom.buy_limit>0)) {
              console.log('秒杀限购')
              th.disInvalid({
                ...item,
                original_img: good.imgUrl
              }, 2, 1)
              continue;
            }

            all_num += item.goods_num;
            item.img_url = oo.imghost + good.imgUrl;
            item.selected = 0;


            var pcid = item.pick_id;
            var find = 0;
            //---------循环查找门店---
            if (arr.length > 0) {
              for (var j = 0; j < arr.length; j++) {
                if (arr[j].pid == pcid) {
                  arr[j].goods.push(item);
                  find = 1;
                  break;
                }
              }
            }

            //------如果没有找到-----
            if (find == 0) {
              var pikname = '';
              var keyid='';
              //找到门店名称
              for (var k = 0; k < th.data.allsto.length; k++) {
                if (pcid == th.data.allsto[k].pickup_id) {
                  pikname = th.data.allsto[k].pickup_name;
                  keyid = th.data.allsto[k].keyid;
                  break;
                }
              }
              var narr = new Array();
              narr.push(item);
              var ie = {
                pid: pcid,
                pname: pikname,
                goods: narr,
                selected: 0,
                keyid: keyid,
              };
              arr.push(ie);
            }
          }
        }

        // console.log('BBBBBB', all_num);
        th.setData({
            service_data: arr,
            all_num2: all_num,
            is_edit: 0
          }),
          th.doCheckAll(), wx.stopPullDownRefresh();

      }
    });
  },

  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
  },

  //设置莫个门店的所有线下价格
  async set_offline(list) {
    var th = this;
    var userInfo = getApp().globalData.userInfo;
    //组织一下商品，然后进行线下价格的赋值
    var wlist = "";
    for (var i in list.goods) {
      //如果商品有促销活动
      if (list.goods[i].prom_type > 0 && list.goods[i].prom_type != 7) continue;
      wlist += encodeURIComponent(list.goods[i].erpwareid) + ",";
    }
    wlist = ut.sub_last(wlist);
    //调用接口进行赋值
    await getApp().request.promiseGet("/api/weshop/goods/listWarePrice", {
      data: {
        store_id: os.stoid,
        PickupId: list.pid,
        WareIds: wlist,
        VIPId: encodeURIComponent(userInfo.erpvipid)
      }
    }).then(res => {
      if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
        for (var e in res.data.data) {
          th.set_cart_offline_price(res.data.data[e], list.goods);
        }
      }
    })
  },

  //-- 设置购物车线下 --
  set_cart_offline_price: function (data, glist) {
    for (var i in glist) {
      if (glist[i].erpwareid == data.WareId && (glist[i].prom_type == 0 || glist[i].prom_type == 7)) {
        if (glist[i].goods_price >= data.WarePrice) {
          glist[i].is_offline = 1;
          glist[i].offline_price = data.WarePrice;
          glist[i].pricing_type = data.PriceType;
        }
      }
    }
  },

  //删除商品
  delete_th_item: function (t) {
    var e = this;
    var a = rq;
    console.log(a);
    wx.showModal({
      title: "确定删除？",
      success: function (s) {
        if (s.confirm) {
          var r = t.currentTarget.dataset.cartid;
          var url = '/api/weshop/cart/del/' + oo.stoid + '/' + r;
          a.delete(url, {
            success: function (t) {
              e.getCardList();
            }
          });
        }
      }
    });
  },

  //-----------------点击输入修改商品数量---------------
  valueToNum: function (t) {
    if (!this.data.is_load) return false;
    //控制住，避免事件响应冲突，只有input有输入的时候，才刷新
    // if (this.data.btn_click) {
    //   return false;
    // }

    setTimeout(() => {
      if (this.data.up_dating == 1) return false;
      this.data.up_dating=1
      this.data.btn_click = 1;
      var a = t.currentTarget.dataset.item;
      var b = t.currentTarget.dataset.pitems;
      a = this.data.requestData[b].goods[a];
      var e = a;
      var th = this;

      if (a = isNaN(t.detail.value) || t.detail.value < 1 ? 1 : parseInt(t.detail.value)) {
        //this.clear_req();
        var s = {
          goods_num: a,
          goods_id: e.goods_id,
          id: e.id,
          store_id: oo.stoid
        };
        th.postCardList(s, t.currentTarget.dataset.item, t.currentTarget.dataset.pitems);
      }
    },200)
  },

  //-------------加减数量的时候，要把show_can_cx清理掉，
  // 同时应该记录一下当前是什么活动那个，如果切换后的活动有跟切换前的活动一样是，就要让切换后的活动的值匹配选中-------------
  clear_req: function () {
    var carr = this.data.requestData;
    for (var i = 0; i < carr.length; i++) {
       var txt = 'requestData[' + i + '].show_can_cx1'
       this.setData({
         [txt]: null
       });
       this.data.requestData[i].show_can_cx=null;
    }
  },

  //-------------加数量-------------
  addNum: async function (t) {

    if (!this.data.is_load) return false;
    if (this.data.up_dating == 1) return false;
    this.data.up_dating = 1;

    var a = t.currentTarget.dataset.item;
    var b = t.currentTarget.dataset.pitems;
    a = this.data.requestData[b].goods[a];

    console.log('add+');

    if (this.data.sales_rules < 2 || a.whsle_id || [1, 2, 4, 6, 8, 9].indexOf(a.prom_type) > -1) {
      if (a.goods_num > a.store_count) {
        console.log('购买的数量不能-----');
        // wx.showModal({
        //     title: '提示',
        //     content: '购买的数量不能超出库存数量',
        // });
        wx.showToast({
          title: '购买的数量不能超出库存数量',
          icon: 'none',
        });
        // getApp().my_warnning('购买的数量不能超出库存数量', 0, this);
        this.data.up_dating = 0;

        return false;
      }
    }

    var add_num = 1;
    //调用接口判断是不是促销活动的商品
    if ([0, 3, 5, 7, 10].indexOf(a.prom_type) > -1) {
      var cx_arr = getApp().get_has_cx_act2(a.goodsActinfo);
      var steep = getApp().get_limit_qty(a, cx_arr.length, 1);
      if (steep > 1) {
        add_num = steep;
      }
    }

    //this.clear_req();

    var e = {
      goods_num: a.goods_num + add_num,
      id: a.id,
      goods_id: a.goods_id,
      store_id: oo.stoid
    };
    // console.log('goods_num', e.goods_num);
    this.postCardList(e, t.currentTarget.dataset.item, t.currentTarget.dataset.pitems, cx_arr);

  },
  //-------------减数量---------------------
  subNum: async function (t) {
    if (!this.data.is_load) return false;
    if (this.data.up_dating == 1) return false;
    this.data.up_dating = 1;

    var a = t.currentTarget.dataset.item;
    var b = t.currentTarget.dataset.pitems;
    a = this.data.requestData[b].goods[a];
    this.data.btn_click = 1;

    if (a.goods_num - 1 < 0) {
      this.data.up_dating = 0;
      return false;
    }

    if (1 != a.goods_num) {
      //this.clear_req();
      var add_num = 1;
      if ([0, 3, 5, 7, 10].indexOf(a.prom_type) > -1) {
        var cx_arr = getApp().get_has_cx_act2(a.goodsActinfo);
        var steep = getApp().get_limit_qty(a, cx_arr.length, 1);
        if (steep > 1) {
          add_num = steep;
        }
      }

      var e = {
        goods_num: a.goods_num - add_num,
        id: a.id,
        goods_id: a.goods_id,
        store_id: oo.stoid
      };

      if (e.goods_num <= 0) {
        this.data.up_dating = 0;
        return false;
      }

      this.postCardList(e, t.currentTarget.dataset.item, t.currentTarget.dataset.pitems);
    }

  },


  //-----------------点击输入修改商品数量---------------
  valueToNum_ser: function (t) {
    if (!this.data.is_load) return false;
    //控制住，避免事件响应冲突，只有input有输入的时候，才刷新
    if (this.data.btn_click) {
      return false;
    }
    this.data.btn_click = 1;

    var a = t.currentTarget.dataset.item;
    var b = t.currentTarget.dataset.pitems;
    a = this.data.service_data[b].goods[a];
    var e = a;
    var th = this;

    if (a = isNaN(t.detail.value) || t.detail.value < 1 ? 1 : parseInt(t.detail.value)) {
      var s = {
        goods_num: a,
        goods_id: e.service_id,
        id: e.id,
        store_id: oo.stoid,
        is_pd_normal: e.is_pd_normal
      };
      if (e.prom_type) {
        s.prom_type = e.prom_type;
      };
      if (e.prom_id) {
        s.prom_id = e.prom_id;
      };
      if (e.is_pd_normal) {
        s.is_pd_normal = e.is_pd_normal;
      };
      if (e.service_id) {
        s.card_id = e.service_id;
      };
      th.postCardList_ser(s, t.currentTarget.dataset.item, t.currentTarget.dataset.pitems);
    }
  },
  //-------------加数量---------------------
  addNum_ser: function (t) {
    if (!this.data.is_load) return false;
    if (this.data.up_dating == 1) return false;
    // this.data.up_dating = 1;

    var a = t.currentTarget.dataset.item;
    var b = t.currentTarget.dataset.pitems;
    a = this.data.service_data[b].goods[a];

    var e = {
      goods_num: a.goods_num + 1,
      id: a.id,
      goods_id: a.service_id,
      store_id: oo.stoid,
      is_pd_normal: a.is_pd_normal
    };
    if (a.prom_type) {
      e.prom_type = a.prom_type;
    };
    if (a.prom_id) {
      e.prom_id = a.prom_id;
    };
    if (a.is_pd_normal) {
      e.is_pd_normal = a.is_pd_normal;
    };
    if (a.service_id) {
      e.card_id = a.service_id;
    };
    this.postCardList_ser(e, t.currentTarget.dataset.item, t.currentTarget.dataset.pitems);

  },
  //-------------减数量---------------------
  subNum_ser: function (t) {

    if (!this.data.is_load) return false;
    if (this.data.up_dating == 1) return false;
    // this.data.up_dating = 1;

    var a = t.currentTarget.dataset.item;
    var b = t.currentTarget.dataset.pitems;
    a = this.data.service_data[b].goods[a];
    this.data.btn_click = 1;

    if (a.goods_num - 1 <= 0) {
      this.data.up_dating = 0;
      return false;
    }

    if (1 != a.goods_num) {
      var e = {
        goods_num: a.goods_num - 1,
        id: a.id,
        goods_id: a.service_id,
        store_id: oo.stoid,
        is_pd_normal: a.is_pd_normal
      };

      this.postCardList_ser(e, t.currentTarget.dataset.item, t.currentTarget.dataset.pitems);
    }
  },


  click_set_limit(gd_info, pitems, item, act) {
    var th = this;
    var mo_num = getApp().get_limit_qty(gd_info, act.length);
    var steep = getApp().get_limit_qty(gd_info, act.length, 1);
    if (gd_info.is_integral_normal || gd_info.is_pd_normal || [0, 3, 5, 7, 10].indexOf(gd_info.prom_type) > -1) {

      var ue = {
        goods_num: gd_info.goods_num,
        store_id: oo.stoid,
        id: gd_info.id,
        goods_id: gd_info.goods_id
      };
      var up_num = 0;
      if (mo_num > gd_info.goods_num) {
        up_num = mo_num;
      }
      if (gd_info.goods_num > mo_num && (gd_info.goods_num - mo_num) % steep != 0 && steep > 1) {
        up_num = mo_num + parseInt((gd_info.goods_num - mo_num) / steep) * steep + steep;
      }
      if (up_num) {
        ue.goods_num = up_num;
        th.update_cart(ue, pitems, item);
        var txt1 = "requestData[" + pitems + "].goods[" + item + "].goods_num";
        th.setData({
          [txt1]: up_num
        })
      }
    }
  },

  //---------------全选,全选的时候要判断是否门店的匹配方式一致--------------
  checkAll: async function () {

    console.log('1111');
    console.log(this.data.clicking);

    //防止重复点击,弹出加载动画，转圈圈
    if(this.data.clicking) return false;
    this.data.clicking=1;
    this.set_clicking();

    var e = this,
        th = this,
        dda = e.data.requestData,
        sdda = e.data.service_data,
        tfeel = 0,
        t_num = 0,
        text_arr = "";


    if(this.data.is_edit){
      let val=!e.data.checkAllToggle;
      if (dda && dda.length > 0) {
        for (var i = 0; i < dda.length; i++) {
          var item = dda[i].goods;

          var txt0 = "requestData[" + i + "].selected";
          this.setData({
            [txt0]: val,
          });

          for (var j = 0; j < item.length; j++) {
            let txt = "requestData[" + i + "].goods[" + j + "].selected";
            e.setData({
              [txt]: val,
            });
          }
        }
      }
      if (sdda && sdda.length > 0) {
        for (i = 0; i < sdda.length; i++) {
          var item1 = sdda[i].goods;

          var txt00 = "service_data[" + i + "].selected";
          this.setData({
            [txt00]: val,
          });

          for (j = 0; j < item1.length; j++) {
            let txt1 = "service_data[" + i + "].goods[" + j + "].selected";
            e.setData({
              [txt1]: val,
            });
          }
        }
      }

      e.setData({
        checkAllToggle: val,
      })

      th.clear_clicking();
      return false;
    }

    if (e.data.requestData && e.data.requestData.length > 0 &&
        e.data.service_data && e.data.service_data.length > 0) {
      wx.showModal({
        title: '提示',
        content: '服务卡项目不能和商品一起选择'
      });
      th.clear_clicking();
      return false;
    }

    this.data.btn_click = 1;

    var offline_price = 0;
    var offline_num = 0;
    th.data.in_zhact_gdmap = {};
    var pro_off = false;
    if (dda && dda.length > 0) {
      for (var i = 0; i < dda.length; i++) {
        var item = dda[i].goods;
        var txt0 = "requestData[" + i + "].show_can_cx1";
        e.setData({
          [txt0]: {},
        });
        th.data.requestData[i].show_can_cx=null;  //清空需要的

        if (e.data.checkAllToggle) {
          var txt = "requestData[" + i + "].selected";
          e.setData({
            [txt]: 0,
          });
        }

        var fir = 0;
        for (var j = 0; j < item.length; j++) {
          if (item[j].is_gift) continue;

          //把价格还原
          item[j].goods_price=item[j].init_goods_price;

          var obj = JSON.parse(JSON.stringify(item[j]));
          var gd_info=obj;

          if (!gd_info.whsle_id && [1, 2, 4, 6, 8, 9].indexOf(gd_info.prom_type) == -1 && !gd_info.selected && th.data.sales_rules >= 2) {
            var ob = {};
            await th.check_down_line_next(gd_info, i, j, gd_info.erpwareid, function (res) {
              ob = res;
            });

            if (ob.code == -1) {
              wx.showToast({
                title: gd_info.goods_name+'购买数量超出商品库存',
                icon: 'none',
              });

              th.clear_clicking();
              return false;
            }

            if (th.data.sales_rules == 3) {
              var goods_id = gd_info.goods_id;
              var num = 0;

              for (let ii = 0; ii< th.data.requestData.length; ii++) {
                if (i == ii) continue;
                var it = th.data.requestData[ii].goods.find((e) => {
                  return e.goods_id == goods_id;
                })
                if (it && it.selected) num += it.goods_num
              }

              if (num > ob.CanOutQty) {
                wx.showToast({
                  title:  gd_info.goods_name+'购买数量超出商品库存',
                  icon: 'none',
                });
                th.clear_clicking();
                return false;
              }
            }

          }


          //-- 判断起购数量 --
          if (!e.data.checkAllToggle) {
            //判断是不是有促销活动
            var act = getApp().get_has_cx_act2(obj.goodsActinfo);
            th.click_set_limit(obj, i, j, act);
          }

          //计算之前先移除组合购的计算
          if (obj.prom_type == 7)
            zh_calc.remove_zhprom(dda, i, obj);
          //计算之前先移除阶梯购的计算
          if (obj.prom_type == 10)
            ladder_calc.remove_ladder_prom(dda, i, obj);
          // //计算之前先移除组合购的计算
          // if (obj.prom_type == 7)
          //   zh_calc.remove_zhprom(dda, i, obj);
          // //计算之前先移除阶梯购的计算
          // if (obj.prom_type == 10)
          //   ladder_calc.remove_ladder_prom(dda, i, obj);


          if (fir == 0) {
            fir = item[j].distr_type;
          } else {
            //如果同一门店有不同门店的商品，不能同一配送
            if (fir != item[j].distr_type && !e.data.checkAllToggle && item[j].distr_type != 0) {
              text_arr += item[j].goods_name + " ";
              break;
            }
          }
          var txt = "requestData[" + i + "].goods[" + j + "].selected";

          if (e.data.checkAllToggle) obj.goods_num = 0;

          // //加入组合购计算
          // if (obj.prom_type == 7) zh_calc.add_zhprom(dda, i, obj);
          // //加入阶梯促销计算
          // if (obj.prom_type == 10) ladder_calc.add_ladder_prom(dda, i, obj);

          //多门店，多优惠次数控制
          // let pro_off1 = false
          // if (!e.data.checkAllToggle) {
          //   //判断多店优惠促销次数控制
          //   if (th.data.requestData.length > 1) {
          //     if (obj.prom_type == 3) {
          //       pro_off1 = await th.multiple_stores_pro(i, j)
          //     }
          //   }
          // }
          // if (pro_off1) {
          //   pro_off = true
          //   let txt1 = "requestData[" + i + "].pro_off";
          //   e.setData({
          //     [txt1]: true,
          //     [txt]: 0,
          //   });
          //
          //   wx.showToast({
          //     title: '已超出优惠促销次数',
          //     icon: 'none',
          //   });

          // } else {

            if (!e.data.checkAllToggle) {
              //组合购的金额要另外算
              if (item[j].prom_type != 7 && item[j].prom_type != 10)
                tfeel += item[j].goods_num * item[j].goods_price;
              t_num += item[j].goods_num;
            }

            //-- 如果这个商品是线下取价的时候 --
            if (item[j].is_offline && item[j].prom_type != 7) {
              offline_price += (item[j].goods_price - item[j].offline_price) * item[j].goods_num;
              offline_num += item[j].goods_num;
            }

            e.setData({
              [txt]: !e.data.checkAllToggle,
            })

          //}




          // if (!e.data.checkAllToggle) {
          //   //组合购的金额要另外算
          //   if (item[j].prom_type != 7 && item[j].prom_type != 10)
          //     tfeel += item[j].goods_num * item[j].goods_price;
          //   t_num += item[j].goods_num;
          // }
          //
          // //-- 如果这个商品是线下取价的时候 --
          // if (item[j].is_offline && item[j].prom_type != 7) {
          //   offline_price += (item[j].goods_price - item[j].offline_price) * item[j].goods_num;
          //   offline_num += item[j].goods_num;
          // }


        }
      }


      if (text_arr != "") {
        wx.showModal({
          title: '提示',
          content: text_arr + '不能与门店中其他商品一起结算，配送方式不一致'
        });
        th.clear_clicking();
        return false;
      }


      for (var i = 0; i < dda.length; i++) {

        // if (!e.data.checkAllToggle) {
        //多门店优惠促销次数控制
        if (dda[i].pro_off || e.data.checkAllToggle) {
          var txt = "requestData[" + i + "].selected";
          e.setData({
            [txt]: 0,
          });
        } else {
          var txt = "requestData[" + i + "].selected";
          e.setData({
            [txt]: 1,
          });
        }
        // }

        //总的价格,把组合商品的价格拿出来
        // var zh_calc_res = zh_calc.calculate_zh(dda, i, this);
        // tfeel += zh_calc_res.tfeel;
        // offline_price += zh_calc_res.offline_price;
        // offline_num += zh_calc_res.offline_num;
        //
        // //总的价格,把阶梯促销的商品的价格拿出来
        // var ladder_calc_res = ladder_calc.calculate_ladder(dda, i, this);
        // tfeel += ladder_calc_res.tfeel;
        // offline_price += ladder_calc_res.offline_price;
        // offline_num += ladder_calc_res.offline_num;
        //
        // //当有线下取价的时候
        // if (offline_price) {
        //   var txt1 = "requestData[" + i + "].offline_price";
        //   var txt2 = "requestData[" + i + "].offline_num";
        //   th.setData({
        //     [txt1]: offline_price.toFixed(2),
        //     [txt2]: offline_num,
        //   });
        // } else {
        //   if (dda[i].offline_price > 0) {
        //     var txt1 = "requestData[" + i + "].offline_price";
        //     var txt2 = "requestData[" + i + "].offline_num";
        //     th.setData({
        //       [txt1]: 0,
        //       [txt2]: 0
        //     });
        //   }
        // }
      }

      //e.setData({
      //checkAllToggle: !e.data.checkAllToggle,
      // total_fee: tfeel.toFixed(2),
      // total_num: t_num,
      //});

      this.doCheckAll(async function () {
        await e.all_check_prom_activity();

        //多门店优惠次数控制
        if (pro_off) {
          e.setData({
            checkAllToggle: false,
          });
        }
        th.clear_clicking();

      });

    }

    if (sdda && sdda.length > 0) {
      for (var i = 0; i < sdda.length; i++) {
        var item = sdda[i].goods;
        if (e.data.checkAllToggle) {
          var txt = "service_data[" + i + "].selected";
          e.setData({
            [txt]: 0,
          });
        }
        var fir = 0;
        for (var j = 0; j < item.length; j++) {
          var txt = "service_data[" + i + "].goods[" + j + "].selected"
          e.setData({
            [txt]: !e.data.checkAllToggle ? 1 : 0,
          })

          if (!e.data.checkAllToggle) {
            tfeel += item[j].goods_num * item[j].money;
            t_num += item[j].goods_num;
          }
        }
      }
      e.setData({
        checkAllToggle: !e.data.checkAllToggle,
        total_fee: tfeel.toFixed(2),
        total_num: t_num,
      });

      th.clear_clicking();

    }
  },


  //------门店全选按钮，要判断是否门店的匹配方式一致---------
  check_th_all_item: async function (ele) {

    //防止重复点击
    if(this.data.clicking) return false;
    this.data.clicking=1;
    //加载动画
    this.set_clicking();

    var e = this,
        th = this,
        pitems = ele.currentTarget.dataset.pitems,
        item = this.data.requestData[pitems].goods,
        sele = this.data.requestData[pitems].selected;
    this.data.btn_click = 1;
    var garr = e.data.service_data;

    var isok = 1,
        fir = 0,
        iarr = item;

    //清空-- 多个促销的切换 --
    var txt0 = "requestData[" + pitems + "].show_can_cx1";
    e.setData({
      [txt0]: {},
    });
    th.data.requestData[pitems].show_can_cx=null;  //清空需要的

    if (!sele) {

      //编辑不管判断了
      if(this.data.is_edit){
        for (var im = 0; im < item.length; im++) {
          let pro_off1 = false
          var txt = "requestData[" + pitems + "].goods[" + im + "].selected";
          this.setData({[txt]:1})
        }

        var txt0 = "requestData[" + pitems + "].selected";
        this.setData({[txt0]:1})

        th.clear_clicking();
        return false;
      }

      var check_is_service_selected = 0;
      for (var ii in garr) {
        for (var ij in garr[ii].goods) {
          if (garr[ii].goods[ij].selected) {
            check_is_service_selected = 1;
            break;
          }
        }
      }

      if (check_is_service_selected) {
        wx.showModal({
          title: '提示',
          content: '服务卡项目不能和商品一起选择'
        });
        th.clear_clicking();
        return false;
      }
    }

    if (!sele && item.length > 0) {
      for (var i = 0; i < iarr.length; i++) {
        if (iarr[i].is_gift == 1) continue;
        if (iarr[i].distr_type != 0) {
          if (fir == 0) {
            fir = iarr[i].distr_type;
          } else {
            if (fir != iarr[i].distr_type && iarr[i].distr_type != 0) {
              isok = 0;
              break;
            }
          }
        }
      }
    }

    if (!isok) {
      wx.showModal({
        title: '提示',
        content: '同一门店自提和物流的商品不能同时结算'
      });
      th.clear_clicking();
      return false;
    }

    let pro_off = false
    for (var i = 0; i < item.length; i++) {
      let pro_off1 = false
      var txt = "requestData[" + pitems + "].goods[" + i + "].selected";
      var gd_info = item[i];

      if (!sele) {
        var act =getApp().get_has_cx_act2(gd_info.goodsActinfo);
        th.click_set_limit(gd_info, pitems, i, act)
      }

      if (!gd_info.whsle_id && [1, 2, 4, 6, 8, 9].indexOf(gd_info.prom_type) == -1 && !gd_info.selected && th.data.sales_rules >= 2) {
        var ob = {};
        await th.check_down_line_next(gd_info, pitems, i, gd_info.erpwareid, function (res) {
          ob = res;
        });

        if (ob.code == -1) {

          wx.showToast({
            title:  gd_info.goods_name+'购买数量超出商品库存',
            icon: 'none',
          });

          th.clear_clicking();
          return false;
        }

        if (th.data.sales_rules == 3) {
          var goods_id = gd_info.goods_id;
          var num = 0;

          for (let i = 0; i < th.data.requestData.length; i++) {
            if (pitems == i) continue;
            var it = th.data.requestData[i].goods.find((e) => {
              return e.goods_id == goods_id;
            })
            if (it && it.selected) num += it.goods_num
          }

          if (num > ob.CanOutQty) {
            wx.showToast({
              title:  gd_info.goods_name+'购买数量超出商品库存',
              icon: 'none',
            });
            th.clear_clicking();
            return false;
          }
        }

      }

      //判断多店优惠促销次数控制
      // if (th.data.requestData.length > 1) {
      //   if (gd_info.prom_type == 3) {
      //     pro_off1 = await th.multiple_stores_pro(pitems, i)
      //   }
      // }
      // if (pro_off1) {
      //   pro_off = true
      //   e.setData({
      //     [txt]: 0,
      //   });
      // } else {
      //   e.setData({
      //     [txt]: Number(!sele),
      //   });
      // }
      e.setData({
        [txt]: Number(!sele),
      });

    }
    var txt = "requestData[" + pitems + "].selected";
    // if (pro_off) {
    //   wx.showToast({
    //     title: '已超出优惠促销次数',
    //     icon: 'none',
    //   });
    //   e.setData({
    //     [txt]: 0,
    //   });
    // } else {
    //   e.setData({
    //     [txt]: Number(!sele),
    //   });
    // }

    e.setData({
      [txt]: Number(!sele),
    });

    //-- 选择了什么商品，就用什么商品来判断 --
    var sele_arr = {};
    for (var i = 0; i < item.length; i++) {
      sele_arr[i] = !sele;
    }

    th.data.pitems=-1;
    if (!sele) {
      th.data.pitems=pitems;
    }


    //-- 回调判断活动有没有冲突 --
    this.cx_check_ok(pitems, sele_arr, function (the_res) {
      if (the_res.code == 0) {
        //-- 门店是所有的商品都要选择 --
        for (var i = 0; i < item.length; i++) {
          var txt0 = "requestData[" + pitems + "].goods[" + i + "].selected";
          e.setData({
            [txt0]: Number(!sele),
          });
        }

        //-- 门店按钮的选择 --
        var txt = "requestData[" + pitems + "].selected";
        e.setData({
          [txt]: Number(!sele),
        });

        th.doCheckAll(async function () {

          e.data.duo_zp_num_arr = {};
          if (sele) {
            await e.check_prom_activity(pitems);
          }
          for (var i in e.data.requestData) {
            if (sele && i == pitems) continue;
            await e.check_prom_activity(i);
          }

          th.clear_clicking();

        });
      } else {
        th.clear_clicking();
        wx.showToast({
          title: the_res.msg,
          icon: 'none',
        });

      }
    })

  },

  //判断多门店，优惠促销次数的控制
  async multiple_stores_pro(pitems, item) {

    if(!this.data.requestData || !this.data.requestData[pitems] || !this.data.requestData[pitems].goods)  return false

    let a = this.data.requestData[pitems].goods[item];
    let th = this
    let arr_pro = []
    th.data.requestData.map((item, i) => {
      if (i != pitems) {
        arr_pro.push(item)
      }
    })
    let prom = null
    //使用缓存，不在调用接口
    if(!prom && th.data.yhcx_act_map && th.data.yhcx_act_map[a.prom_id] ){
      prom=th.data.yhcx_act_map[a.prom_id];
    }
    if(!prom) {
        await getApp().request.promiseGet("/api/weshop/promgoods/get/" + os.stoid + "/" + a.prom_id, {}).then(res => {
          if (res.data.code == 0) {
            prom = res.data.data;
          }
        })
    }

    let user_pre_buynum = await this.getUserBuyPromNum_pre(a.prom_id);
    if (user_pre_buynum >= prom.limit_num) {
      return false
    } else {

      let action_num = user_pre_buynum + 1;
      arr_pro.map(item => {
        let found = false;
        item.goods.map(ite => {
          if(found) return;
          if (ite.prom_type == 3 && ite.prom_id == a.prom_id && !ite.is_gift && ite.selected) {
            action_num += 1;
            found=true;
          }
        })
      })
      if (prom && action_num > prom.limit_num) {
        return true
      } else {
        return false
      }
    }


  },


  //清理防止重复点击的状态函数---2024-2-1
  set_clicking(){
    wx.showLoading({
      mark:true
    });
  },
  //清理防止重复点击的状态函数---2024-2-1
  clear_clicking(){
    var th=this;
    wx.hideLoading({
      complete:function (){
        th.data.clicking=0;
      }
    });
  },
  //---------------单选，也要判断门店的配送方式是否一致--------------
  check_th_item: async function (t) {

    //防止重复点击
    if(this.data.clicking) return false;
    this.data.clicking=1;

    var e = this,
        th = this,
        item = t.currentTarget.dataset.item,
        pitems = t.currentTarget.dataset.pitems;
    a = this.data.requestData[pitems].goods[item];
    var isok = 1,
        fir = 0;
    var iarr = e.data.requestData[pitems].goods;
    this.data.btn_click = 1;
    var garr = e.data.service_data;

    //之前没有选中，代表现在要选中
    if (!a.selected) {

      //如果是标记的时候
      if(this.data.is_edit){
        var txt = "requestData[" + pitems + "].goods[" + item + "].selected";
        this.setData({[txt]:1});
        th.clear_clicking();
        return false;
      }


      var check_is_service_selected = 0;
      for (var ii in garr) {
        for (var ij in garr[ii].goods) {
          if (garr[ii].goods[ij].selected) {
            check_is_service_selected = 1;
            break;
          }
        }
      }
      if (check_is_service_selected) {
        wx.showModal({
          title: '提示',
          content: '服务卡项目不能和商品一起选择'
        });
        th.clear_clicking();
        return false;
      }
    }

    th.data.pitems=-1;
    //当数量大于1，且是选择的时候
    if (iarr.length > 1 && !a.selected) {

      for (var i = 0; i < iarr.length; i++) {
        if (iarr[i].is_gift == 1) continue;
        //---当不是本身选择项目----
        var sel = iarr[i].selected;
        if (iarr[i].distr_type != 0 && (sel || iarr[i].id == a.id)) {
          if (fir == 0) {
            fir = iarr[i].distr_type;
          } else {
            if (fir != iarr[i].distr_type && iarr[i].distr_type != 0) {
              isok = 0;
              break;
            }
          }
        }
      }
    }
    if (!isok) {
      wx.showModal({
        title: '提示',
        content: '同一门店自提和物流的商品不能同时结算'
      });
      th.clear_clicking();
      return false;
    }


    var txt = "requestData[" + pitems + "].goods[" + item + "].selected";
    var gd_info = a;

    var erpwareid = gd_info.erpwareid;

    //-- 如果是选中的时候 --
    if (!a.selected) {

      th.data.pitems=pitems;

      //判断是不是有促销活动
      var act = getApp().get_has_cx_act2(gd_info.goodsActinfo);
      //-- 专门来设置商品订购数量 --
      th.click_set_limit(gd_info, pitems, item, act)
      if (th.data.sales_rules >= 2 && !gd_info.whsle_id && [1, 2, 4, 6, 8, 9].indexOf(gd_info.prom_type) == -1) {

        var ob = {};
        await th.check_down_line_next(gd_info, pitems, item, erpwareid, function (res) {
          ob = res;
        });
        if (ob.code == -1) {
          wx.showToast({
            title: '购买数量超出商品库存',
            icon: 'none',
          });
          th.clear_clicking();
          return false;
        }

        if (th.data.sales_rules == 3) {
          var goods_id = gd_info.goods_id;
          var num = 0;

          for (let i = 0; i < th.data.requestData.length; i++) {
            if (pitems == i) continue;
            var it = th.data.requestData[i].goods.find((e) => {
              return e.goods_id == goods_id;
            })
            if (it && it.selected) num += it.goods_num
          }

          if (num > ob.CanOutQty) {
            wx.showToast({
              title: '购买数量超出商品库存',
              icon: 'none',
            });
            th.clear_clicking();
            return false;
          }
        }

      }
    }

    // let pro_off = false
    // //判断多店优惠促销次数控制
    // if (th.data.requestData.length > 1) {
    //   if (a.prom_type == 3 && !a.selected) {
    //     pro_off = await th.multiple_stores_pro(pitems, item)
    //   }
    // }
    //
    // if (pro_off) {
    //   wx.showToast({
    //     title: '已超出优惠促销次数',
    //     icon: 'none',
    //   });
    //   th.clear_clicking();
    //   return false;
    // }

    var txt0 = "requestData[" + pitems + "].show_can_cx1";
    e.setData({
      [txt0]: {},
    });
    th.data.requestData[pitems].show_can_cx=null;

    //-- 选择了什么商品，就用什么商品来判断 --
    var sele_arr = {};
    sele_arr[item] = !a.selected;
    //回调判断活动有没有冲突
    this.cx_check_ok(pitems, sele_arr, function (the_res) {
      if (the_res.code == 0) {
        th.setData({
          [txt]: Number(!a.selected),
        });
        //要先处理了，再来判断要不要显示凑单
        th.doCheckAll(async function () {
          th.data.duo_zp_num_arr={};
          //判断商品是不是优惠活动
          for (var i in e.data.requestData) {
            await e.check_prom_activity(i);
          }
          //清理一下点击防止重复点击
          th.clear_clicking();

        });
      } else {
        wx.showToast({
          title: the_res.msg,
          icon: 'none',
        });
        th.clear_clicking();
      }
    })

  },



  //------门店全选按钮，要判断是否门店的匹配方式一致---------
  check_th_all_item_ser: async function (ele) {
    var e = this,
      pitems = ele.currentTarget.dataset.pitems,
      item = this.data.service_data[pitems].goods,
      sele = this.data.service_data[pitems].selected;
    this.data.btn_click = 1;
    var garr = e.data.requestData;

    var isok = 1,
      fir = 0,
      iarr = item;

    if (!sele) {

      //编辑不管判断了
      if(this.data.is_edit){
        for (var im = 0; im < item.length; im++) {
          let pro_off1 = false
          var txt = "service_data[" + pitems + "].goods[" + im + "].selected";
          this.setData({[txt]:1})
        }
        return false;
      }

      var check_is_goods_selected = 0;
      for (var ii in garr) {
        for (var ij in garr[ii].goods) {
          if (garr[ii].goods[ij].selected) {
            check_is_goods_selected = 1;
            break;
          }
        }
      }
      if (check_is_goods_selected) {
        wx.showModal({
          title: '提示',
          content: '服务卡项目不能和商品一起选择'
        });
        return false;
      }
    }

    for (var i = 0; i < item.length; i++) {
      var txt = "service_data[" + pitems + "].goods[" + i + "].selected";
      e.setData({
        [txt]: Number(!sele),
      });
    }
    var txt = "service_data[" + pitems + "].selected";
    e.setData({
      [txt]: Number(!sele),
    });
    this.doCheckAll();
  },
  //---------------单选，也要判断门店的配送方式是否一致--------------
  check_th_item_ser: async function (t) {
    var e = this,
      item = t.currentTarget.dataset.item,
      pitems = t.currentTarget.dataset.pitems;
    a = this.data.service_data[pitems].goods[item]; // 选中的商品

    var isok = 1,
      fir = 0;
    var iarr = e.data.service_data[pitems].goods;
    this.data.btn_click = 1;

    var garr = e.data.requestData;

    if (!a.selected) {

      if(this.data.is_edit){
        var txt = "service_data[" + pitems + "].goods[" + item + "].selected";
        e.setData({
          [txt]: 1,
        });
        return false;
      }


      var check_is_goods_selected = 0;
      for (var ii in garr) {
        for (var ij in garr[ii].goods) {
          if (garr[ii].goods[ij].selected) {
            check_is_goods_selected = 1;
            break;
          }
        }
      }

      if (check_is_goods_selected) {
        wx.showModal({
          title: '提示',
          content: '服务卡项目不能和商品一起选择'
        });
        return false;
      }
    }

    var txt = "service_data[" + pitems + "].goods[" + item + "].selected";
    e.setData({
      [txt]: Number(!a.selected),
    });

    this.doCheckAll();
  },

  //----------检查是否全选，同时检验各种活动---------
  doCheckAll: async function (func, n_ok) {
    var th = this,
      tfeel = 0,
      t_num = 0,
      ischeck = 1,
      car = this.data.requestData,
      car2 = this.data.service_data,
      all_num = 0;


    //-- 如果是全部的时候，就要把它清理掉 --
    this.data.in_zhact_gdmap_new = {};
    this.data.in_zhact_new = {};
    this.data.in_yhact_new = {};

    //-- 购物车 --
    if (car && car.length > 0) {
      th.data.in_zhact_gdmap = {};

      //-- show_can_cx的还要遍历一遍，确保数据的正确性 --
      var rd_arr = [];

      //确保选择的放在最后一次判断
      var c_ind=-1;
      if(th.data.pitems>-1){
        c_ind=th.data.pitems;
        th.data.pitems=-1;
      }



      var cur_car_cp=ut.deep_cp(car);
      for (var a = 0; a < car.length; a++) {
        var ite1 = car[a].goods;
        if(car.length>1 && c_ind>-1 && a==c_ind ){
          rd_arr.push({});
          continue;
        }

        //不需要修改价格
        await m_cx.cart_cx_group(th, ite1, car[a], 0, n_ok, (show_can_cx) => {
          rd_arr.push(show_can_cx)
        })
      }

      if(car.length>1 && c_ind>-1){
          var ite2 = car[c_ind].goods;
          //检验和设置商品的最终是以 取用什么活动，因为多促销
          await m_cx.cart_cx_group(th, ite2, car[c_ind], 0, n_ok, (show_can_cx) => {
            rd_arr[c_ind]=show_can_cx;
          })
      }

      for (var a = 0; a < car.length; a++) {
        //-- 把活动组装进去 ---
        var show_can_cx = rd_arr[a];
        //-- 把活动组装进去 ---
        let show_can_cx1 = ut.deep_cp(rd_arr[a]);
        //前端处理渲染的时，要处理一些不需要的字段属性
        if(show_can_cx1){
          for (const key in show_can_cx1) {
            let element = show_can_cx1[key];
            if(element.cur_act ){
              delete element.cur_act;
            }
            if(element.ch_map){
              delete element.ch_map;
            }
            if(element.act_arr && element.act_arr.length>0){
              for (var ij = 0; ij < element.act_arr.length; ij++) {
                var act_ite = element.act_arr[ij];
                delete act_ite.goods;
                delete act_ite.act;
                delete act_ite.key;
              }
            }
          }
        }


        car[a].zh_map = null;
        car[a].ladder_map = null;

        //-- 这里是清理了组合购的去凑单 --
        var txt = "requestData[" + a + "].need_list";
        //car[a].need_list = [];
        th.setData({[txt]:[]});
        //-- 这里清理赠品 --
        var txt2 = "requestData[" + a + "].send_gift_arr";
        //car[a].need_list = [];
        th.setData({[txt2]:[]});
        //-- 这里是清理了优惠的去凑单 --
        var rq_text2 = "requestData[" + a + "].make_up_arr";
        this.setData({
          [rq_text2]: null,
        })

        var item = car[a].goods,is_s_sele = 1;

        //-- 先批量判断一下活动的类型，同时要同步跟新 --
        var offline_price = 0;
        var offline_num = 0;

        //-- 优惠促销活动限购次数的优化 --
        var ch_yc_map={};
        for (var c = 0; c < item.length; c++) {
          //清理一下赠品
          if (item[c].is_gift) {
            var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item[c].id;
            //getApp().request.delete(url, {});
            await getApp().request.promiseDelete(url, {}) // 要用同步让赠品删除
            item.splice(c, 1);
            //索引要回退一下
            --c;
            continue;
          }

          let pro_off1 = false;
          //-- 判断活动超出限购,要有选中的情况 --
          if (item[c].prom_type == 3 && item[c].selected && !ch_yc_map[a.prom_id]) {
            //一个门店一个优惠促销就判断一次
            ch_yc_map[a.prom_id]=1;
            pro_off1 = await th.multiple_stores_pro(a, c)
          }
          if (pro_off1) {
            wx.showToast({
              title: '已超出优惠促销次数',
              icon: 'none',
            });
          }

          all_num += item[c].goods_num;

          if (item[c].prom_type == 7) {
              item[c].act = th.data.zuhe_map[item[c].prom_id];
              if(item[c].zh_b_num===undefined || item[c].zh_b_num===null ){
                  var prom_goodsbuynum = 0;
                  //--要获得商品，该用户买了多少件,同步应用，用于限购的计算--
                  await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
                    data: {
                      store_id: oo.stoid,
                      user_id: getApp().globalData.user_id,
                      goods_id: item[c].goods_id,
                      prom_type: item[c].prom_type,
                      prom_id: item[c].prom_id,
                      isnew:1
                    },
                  }).then(res => {
                    if(res.data.code==0 && res.data.data)
              
                    if (res.data.data.promgoodsbuynum) {
                      prom_goodsbuynum = res.data.data.promgoodsbuynum;
                    }
                   
                  })

                  var txt = "requestData[" + a + "].goods[" + c + "].zh_b_num";
                  th.setData({
                    [txt]: prom_goodsbuynum
                  });
                  
              }
          }
          if (item[c].prom_type == 10) {
            item[c].act = th.data.ladder_map[item[c].prom_id];
          }

          //不管怎么样都要移出去
          var obj = JSON.parse(JSON.stringify(item[c]));
          zh_calc.remove_zhprom(car, a, obj);
          ladder_calc.remove_ladder_prom(car, a, obj);

          //-- 如果是未选中的时候 --
          if (item[c].selected == 0) {
            ischeck = 0;
            is_s_sele = 0;
            if (item[c].prom_type == 7) {
              obj.goods_num = 0;
              zh_calc.add_zhprom(car, a, obj);
            }

            if (item[c].prom_type == 10) {
              obj.goods_num = 0;
              ladder_calc.add_ladder_prom(car, a, obj);
            }

            if( cur_car_cp[a].goods[c].goods_price!=th.data.dp_car[a].goods[c].goods_price) {
              //-- 如果价格有发生变动,要更新界面中的价格显示,还原价格 --
              let txt = 'requestData[' + a + '].goods[' + c + '].goods_price';
              th.setData({
                [txt]: th.data.dp_car[a].goods[c].goods_price
              })
            }


          } else {

            //-- 如果是选中的时候 --
            if (item[c].prom_type == 7) {
              //先把商品放入组合计算的专用的区域
              console.log('是组合商品---')
              console.log(car);
              console.log(a)
              console.log(obj)
              console.log('......................')
              zh_calc.add_zhprom(car, a, obj);
            } else if (item[c].prom_type == 10) {
              ladder_calc.add_ladder_prom(car, a, obj);
            } else {
              //console.log("索引:"+c+",数量:"+item[c].goods_num+",单价:"+item[c].goods_price+",合计："+item[c].goods_num * item[c].goods_price+",商品:"+item[c].goods_name);
              tfeel += item[c].goods_num * item[c].goods_price;
              //console.log("累计:"+tfeel);

              //-- 如果价格有发生变动,要更新界面中的价格显示 --
              if(th.data.dp_car && th.data.dp_car[a] && th.data.dp_car[a].goods) {
                  if (item[c].goods_price != th.data.dp_car[a].goods[c].goods_price) {
                    let txt = 'requestData[' + a + '].goods[' + c + '].goods_price';
                    th.setData({
                      [txt]: item[c].goods_price
                    })
                  }
              }

            }
            t_num += item[c].goods_num;
          }



          //-- 如果这个商品是线下取价的时候 --
          if (item[c].is_offline && item[c].prom_type != 7) {
            offline_price += (item[c].goods_price - item[c].offline_price) * item[c].goods_num;
            offline_num += item[c].goods_num;
          }
        }



        //总的价格,把组合商品的价格拿出来
        var zh_calc_res = zh_calc.calculate_zh(car, a, th);
        console.log('.组合价-----------')
        console.log(zh_calc_res)
        //总的价格,把阶梯促销商品的价格拿出来
        var ladder_calc_res = ladder_calc.calculate_ladder(car, a, th);

        tfeel += zh_calc_res.tfeel;
        offline_price += zh_calc_res.offline_price;
        offline_num += zh_calc_res.offline_num;

        tfeel += ladder_calc_res.tfeel;
        offline_price += ladder_calc_res.offline_price;
        offline_num += ladder_calc_res.offline_num;

        var txt = "requestData[" + a + "].selected";
        th.setData({
          [txt]: Number(is_s_sele)
        });

        var txt1 = "requestData[" + a + "].show_can_cx1";
        //-- 赋值不渲染 ，只后台计算 --
        th.data.requestData[a].show_can_cx=show_can_cx;
        th.setData({
          [txt1]: show_can_cx1,
        });

        //-- var et={show_can_cx:show_can_cx};
        //-- rd_arr.push(et);

        //当有线下取价的时候
        if (offline_price) {
          var txt1 = "requestData[" + a + "].offline_price";
          var txt2 = "requestData[" + a + "].offline_num";
          th.setData({
            [txt1]: offline_price.toFixed(2),
            [txt2]: offline_num,
          });
        } else {
          if (car[a].offline_price > 0) {
            var txt1 = "requestData[" + a + "].offline_price";
            var txt2 = "requestData[" + a + "].offline_num";
            th.setData({
              [txt1]: 0,
              [txt2]: 0
            });
          }
        }
      }


      //-- 切换活动的按钮要把他返回 --
      this.data.change_act = 0;
      if (func) func();
    }

    //-- 服务卡 --
    if (car2 && car2.length > 0) {
      for (var a = 0; a < car2.length; a++) {
        var c_item = car2[a];
        var item = car2[a].goods,
          is_s_sele = 1;

        for (var c = 0; c < item.length; c++) {
          if (item[c].is_gift) continue;
          all_num += item[c].goods_num;
          if (item[c].selected == 0) {
            ischeck = 0;
            is_s_sele = 0;
          } else {
            tfeel += item[c].goods_num * item[c].money;
            t_num += item[c].goods_num;
          }

        }
        var txt = "service_data[" + a + "].selected";
        th.setData({
          [txt]: Number(is_s_sele)
        });
      }
    }

    this.setData({
      checkAllToggle: ischeck,
      total_fee: tfeel.toFixed(2),
      all_num: all_num,
      total_num: t_num
    });
  },


  //----------------------更新购物数量，加减,调用接口---------------------
  postCardList: function (t, item, pitem) {
    var e = this,
      th = e,
      user_id = getApp().globalData.user_id;

    // console.log('update');
    // console.log('9995959595959',t);
    var e = this,
      th = e;
    var user_id = getApp().globalData.user_id;
    rq.get("/api/weshop/goods/get/" + oo.stoid + "/" + t.goods_id, {
      isShowLoading: 0,
      async success(d) {
        var limit = d.data.data.viplimited;
        var store_count = d.data.data.store_count;
        var wareIds = d.data.data.erpwareid;

        var goodsinfo = e.data.requestData[pitem].goods[item];
        var promgoodsbuynum = 0;
        var goodsbuynum = 0;

        var is_showing = 0;
        //--要获得商品，该用户买了多少件,同步应用，用于限购的计算--
        await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
          data: {
            store_id: oo.stoid,
            user_id: user_id,
            goods_id: goodsinfo.goods_id,
            prom_type: goodsinfo.prom_type,
            prom_id: goodsinfo.prom_id,
            isnew:1,
            timetype:goodsinfo.viplimited_timetype
          },
        }).then(res => {
          var buy_num_data = res.data.data;
          if (buy_num_data.promgoodsbuynum) {
            promgoodsbuynum = buy_num_data.promgoodsbuynum;
            var txt = "requestData[" + pitem + "].goods[" + item + "].zh_b_num";
            th.setData({
              [txt]: promgoodsbuynum
            });
          }
          goodsbuynum = buy_num_data.goodsbuynum;

        })

        //--> by ty
        // var buyed_mum2 = t.goods_num + goodsbuynum;
        var buyed_mum2 = t.goods_num;
        //<--
        // 判断当前预购买的数量是否超过可购买的数量，限购还要考虑到商品的库存
        if (limit > 0) {

          //getApp().my_warnning('购买数量超出商品限购', 0, th);
          var txt = "requestData[" + pitem + "].goods[" + item + "].goods_num";
          limit = limit - goodsbuynum;
          if (limit < 0) limit = 0;

          if (buyed_mum2 > limit) {
            wx.showToast({
              title: '购买数量超出商品限购',
              icon: 'none',
            });
            is_showing = 1;
          }

          // e.setData({
          //   // [txt]: cbuy > 0 ? cbuy : 0,
          //   [txt]: cbuy > 0 ? cbuy : limit,
          // });
          //e.doCheckAll();
          // t.goods_num = cbuy > 0 ? cbuy : limit;
          //
          // if([0,3,5,7,10].indexOf(goodsinfo.prom_type)>-1){
          //
          //     //-- 判断商品是不是 --
          //     var cx_arr=await getApp().get_has_cx_act(goodsinfo.goods_id);
          //     var mo_num=getApp().get_limit_qty(goodsinfo,cx_arr.length);
          //     var steep=getApp().get_limit_qty(goodsinfo,cx_arr.length,1);
          //
          //     if(mo_num>1 && t.goods_num<mo_num){
          //       wx.showToast({
          //         title: '购买数量小于商品的起订量',
          //         icon: 'none',
          //       });
          //       t.goods_num=0;
          //     }
          //
          //     if(steep>1 && t.goods_num>mo_num && (t.goods_num-mo_num)%steep!=0 ){
          //
          //       wx.showToast({
          //         title: '购买数量必须是起订量的倍数',
          //         icon: 'none',
          //       });
          //
          //       t.goods_num=mo_num+parseInt((t.goods_num-mo_num)/steep+'')*steep
          //     }
          // }
          //   // t.goods_num = cbuy > 0 ? cbuy : 0,
          // e.update_cart(t, pitem, item);
          // return false;
        } else limit = 100000;

        switch (goodsinfo.prom_type) {
          case 1:
            //-- 读取秒杀 --
            var res_d = await getApp().promiseGet("/api/ms/flash_sale/getFlashSaleOne/" + oo.stoid + "/" + goodsinfo.prom_id, {});
            if (res_d.data.code == 0 && res_d.data.data) {

              var cbuy = limit;
              if (t.goods_num > store_count && !is_showing) {
                wx.showToast({
                  title: '购买数量超出商品库存',
                  icon: 'none',
                });
                is_showing = 1;
              }
              //一直都要给一个最小值，和库存比较
              if (cbuy > store_count) cbuy = store_count;

              var false_data = res_d.data.data;
              //--判断库存--
              if (t.goods_num > false_data.goods_num - false_data.buy_num && !is_showing) {
                wx.showToast({
                  title: '购买数量超出活动库存',
                  icon: 'none',
                });
                is_showing = 1;
              }

              //一直都要给一个最小值，和活动库存比较
              if (cbuy > false_data.goods_num - false_data.buy_num)
                cbuy = false_data.goods_num - false_data.buy_num;

              //--判断redis数量是否已经超出--
              if (t.goods_num > false_data.redisnum && !is_showing) {
                wx.showToast({
                  title: '购买数量超出商品库存',
                  icon: 'none',
                });
                is_showing = 1;
              }

              //一直都要给一个最小值，和活动库存比较
              if (cbuy > false_data.redisnum) cbuy = false_data.redisnum;

              //--活动的限购是不是要判断--
              if (false_data.buy_limit > 0) {
                if (t.goods_num + promgoodsbuynum > false_data.buy_limit && !is_showing) {
                  wx.showToast({
                    title: '购买数量超出秒杀限购',
                    icon: 'none',
                  });
                }
                var act_limit = false_data.buy_limit - promgoodsbuynum;
                if (!act_limit) act_limit = 0;
                if (cbuy > act_limit) cbuy = act_limit;

              }

              if (t.goods_num > cbuy) t.goods_num = cbuy;

              e.update_cart(t, pitem, item);

            } else {
              e.normal_check(t, item, pitem, store_count, limit, goodsinfo, wareIds); //普通商品的调用和计算
            }
            break;
          case 2:

            //-- 读取团购 --
            var res = await getApp().promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + goodsinfo.goods_id + "/" + goodsinfo.prom_id, {});
            if (res.data.code == 0 && res.data.data) {

              var cbuy = limit;
              if (t.goods_num > store_count && !is_showing) {
                wx.showToast({
                  title: '购买数量超出商品库存',
                  icon: 'none',
                });
                is_showing = 1;
              }
              //一直都要给一个最小值，和库存比较
              if (cbuy > store_count) cbuy = store_count;

              var gr_data = res.data.data;
              //--判断库存--
              if (t.goods_num > gr_data.goods_num - gr_data.buy_num && !is_showing) {
                wx.showToast({
                  title: '购买数量超出活动库存',
                  icon: 'none',
                });
                is_showing = 1;
              }
              //一直都要给一个最小值，和库存比较
              if (cbuy > gr_data.goods_num - gr_data.buy_num) cbuy = gr_data.goods_num - gr_data.buy_num;

              //--判断redis数量是否已经超出--
              if (t.goods_num > gr_data.redisnum && !is_showing) {
                wx.showToast({
                  title: '购买数量超出商品库存',
                  icon: 'none',
                });
                is_showing = 1;
              }
              if (cbuy > gr_data.redisnum) cbuy = gr_data.redisnum;

              //--活动的限购是不是要判断--
              if (gr_data.buy_limit > 0) {
                if (t.goods_num + promgoodsbuynum > gr_data.buy_limit && !is_showing) {
                  wx.showToast({
                    title: '购买数量超出团购限购',
                    icon: 'none',
                  });
                  is_showing = 1;
                }

                var act_limit = gr_data.buy_limit - promgoodsbuynum;
                if (!act_limit) act_limit = 0;

                if (cbuy > act_limit) cbuy = act_limit;
              }

              if (t.goods_num > cbuy) t.goods_num = cbuy;

              e.update_cart(t, pitem, item);

            } else {
              e.normal_check(t, item, pitem, store_count, limit, goodsinfo, wareIds); //普通商品的调用和计算
            }
            break;
          default:
            e.normal_check(t, item, pitem, store_count, limit, goodsinfo, wareIds); //普通商品的调用和计算
            break
        }
      }
    });
  },

  //-- 这个函数在计算的时候,要包含限购的那一部分 --
  async normal_check(t, item, pitem, store_count, limit, goodsinfo, wareIds) {

    var cx_arr = getApp().get_has_cx_act2(goodsinfo.goodsActinfo);

    var th = this;
    // getApp().my_warnning('购买数量超出商品库存', 0, th);
    var txt = "requestData[" + pitem + "].goods[" + item + "].goods_num";


    var cQty = store_count;
    //--- 看一下是不是线下库存 ---
    if (th.data.sales_rules >= 2 && !goodsinfo.whsle_id) {
      //th.check_down_line(t, pitem, item, wareIds,limit);
      var ob = {};
      await th.check_down_line_next(t, pitem, item, wareIds, function (res) {
        ob = res;
      });
      cQty = ob.CanOutQty;
    }

    var is_showing = 0;
    var cbuy = limit;
    if (t.goods_num > limit) {
      wx.showToast({
        title: '购买数量超出商品限购',
        icon: 'none',
      });
      is_showing = 1;
    }

    if (t.goods_num > cQty) {
      if (!is_showing) {
        wx.showToast({
          title: '购买数量超出商品库存',
          icon: 'none',
        });
        is_showing = 1;
      }
    }
    if (cbuy > cQty) cbuy = cQty;

    if (t.goods_num > cbuy) t.goods_num = cbuy;

    if ([0, 3, 5, 7, 10].indexOf(goodsinfo.prom_type) > -1) {
      var mo_num = getApp().get_limit_qty(goodsinfo, cx_arr.length);
      var steep = getApp().get_limit_qty(goodsinfo, cx_arr.length, 1);

      if (mo_num > 1 && t.goods_num < mo_num) {
        if (!is_showing) {
          wx.showToast({
            title: '购买数量小于商品的起订量',
            icon: 'none',
          });
        }
        t.goods_num = mo_num;
      }

      if (steep > 1 && t.goods_num > mo_num && (t.goods_num - mo_num) % steep != 0) {
        if (!is_showing) {
          wx.showToast({
            title: '购买数量必须是起订量的倍数',
            icon: 'none',
          });
        }
        if (t.goods_num < mo_num) t.goods_num = mo_num;
        else {
          t.goods_num = mo_num + parseInt((t.goods_num - mo_num) / steep + '') * steep
        }
      }
    }

    th.update_cart(t, pitem, item);

  },

  //----------------------更新购物数量，加减,调用接口---------------------
  postCardList_ser: async function (t, item, pitem) {
    var e = this,
      th = e;
    var user_id = getApp().globalData.user_id;
    var txt = "service_data[" + pitem + "].goods[" + item + "].goods_num";

    e.setData({
      [txt]: t.goods_num
    });

    // 1.秒杀活动 ,团购的活动
    // 2.活动开始
    if((t.prom_type == 1 && t.is_pd_normal == 0) || t.prom_type==2) {
      var txt = "service_data[" + pitem + "].goods[" + item + "].goods_num";
      var redis_num = 0;

      // 获取其他门店，同类商品的数量
      var cartGoodsNum = 0;
      await getApp().request.promiseGet("/api/weshop/cartService/page?store_id=" + t.store_id + "&user_id=" + getApp().globalData.user_id + "&service_id=" + t.goods_id, {}).then(res => {
        if (res.data.data.pageData.length > 0) {
          const tmpObj = res.data.data.pageData;
          tmpObj.forEach(v => {
            if (t.id != v.id) {
              cartGoodsNum += parseInt(v.goods_num);
            }
          });
        }
      });
      // 当前商品数量包括其他门店
      var totalNum = 0
      if (cartGoodsNum > 0) {
        totalNum = t.goods_num + cartGoodsNum;
      } else {
        totalNum = t.goods_num;
      }

      //获取当前商品活动库存
      await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" +
        t.store_id + "/" + t.prom_type + "/" + t.prom_id, {
          1: 1
        }).then(res => {
        redis_num = res.data.data;
      });

      // 检测库存
      if (redis_num == 0) {
        wx.showToast({
          title: '超出活动库存',
          icon: 'none',
        });
        // getApp().my_warnning('超出活动库存', 0, th);
        th.setData({
          [txt]: redis_num
        });
        t.goods_num = redis_num;
        await th.doCheckAll();
        await th.update_cart_ser(t, pitem, item);
        return false;
      };

      // 限购数量
      var buylimit = 0
      if(t.prom_type==1) {
        await getApp().request.promiseGet("/api/ms/flash_sale/getNew/" + t.store_id + "/" + getApp().globalData.user_id + "/" + t.prom_id, {}).then(res => {
          if (res.data.code == 0 && res.data.data) {
            th.data.sele_g = res.data.data;
            th.data.sele_g.viplimited = res.data.data.buy_limit;
            buylimit = !res.data.data.buy_limit ? 0 : res.data.data.buy_limit;
          }
        });
      }

      if(t.prom_type==2) {
        await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" +  t.goods_id + "/" + t.prom_id, {}).then(res => {
          if (res.data.code == 0) {
            th.data.sele_g = res.data.data;
            th.data.sele_g.viplimited = res.data.data.buy_limit;
            buylimit = !res.data.data.buy_limit ? 0 : res.data.data.buy_limit;
          }
        });
      }


      //用户已经成功付款购买的数量
      var gd_buy_num = 0;
      await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum?store_id=" + t.store_id + "&isnew=1&user_id=" + getApp().globalData.user_id + "&card_id=" + t.card_id + "&prom_type=" + t.prom_type + "&prom_id=" + t.prom_id, {}).then(tt => {
        if (tt.data.code == 0) {
          gd_buy_num = !tt.data.data.promcardbuynum ? 0 : tt.data.data.promcardbuynum;
          th.setData({
            promcardbuynum: !tt.data.data.promcardbuynum ? 0 : tt.data.data.promcardbuynum,
            cardbuynum: tt.data.data.cardbuynum,
          });
        }
      })

      // 剩余购买数
      let num = buylimit - gd_buy_num;

      if (totalNum > redis_num) {
        wx.showToast({
          title: '超出活动库存',
          icon: 'none',
        });
        // getApp().my_warnning('超出活动库存', 0, th);
        // 开启限购
        if (buylimit > 0) {
          if (num > redis_num) {
            th.setData({
              [txt]: redis_num - cartGoodsNum
            });
            t.goods_num = redis_num - cartGoodsNum;
            await th.doCheckAll();
            await th.update_cart_ser(t, pitem, item);
          } else {
            th.setData({
              [txt]: num - cartGoodsNum
            });
            t.goods_num = num - cartGoodsNum;
            await th.doCheckAll();
            await th.update_cart_ser(t, pitem, item);
          }
        } else {
          th.setData({
            [txt]: redis_num - cartGoodsNum
          });
          t.goods_num = redis_num - cartGoodsNum;
          await th.doCheckAll();
          await th.update_cart_ser(t, pitem, item);
        }

        return false;
      };


      //--秒杀：判断商品是否超出活动限购--
      if (buylimit > 0) {

        // 如果限购数量<=活动库存数量，增加数量时会先超过限购数量，此时应提示“超出活动限购数量”
        if (totalNum > num) {
          // 计算还可以购买的数量：库存量 - 已购数
          wx.showToast({
            title: '超出活动限购',
            icon: 'none',
          });
          // getApp().my_warnning('超出活动限购', 0, th);
          if (num <= 0) num = 1;
          th.setData({
            [txt]: num - cartGoodsNum
          });
          t.goods_num = num - cartGoodsNum;
          await th.doCheckAll();
          await th.update_cart_ser(t, pitem, item);
          return false;
        }
      }

    }


    await e.doCheckAll();
    await e.update_cart_ser(t, pitem, item);
  },


  // 检查购物车数量
  async checkCartNum(t, item, pitem) {
    var th = this;
    if (t.is_pd_normal) return false;
    if (t.prom_type == 1) {
      var txt = "service_data[" + pitem + "].goods[" + item + "].goods_num";
      var redis_num = 0;

      //------判断活动是否抢光-----
      await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" +
        t.store_id + "/" + t.prom_type + "/" + t.prom_id, {
          1: 1
        }).then(res => {
        redis_num = res.data.data;
      });

      // 检测库存
      if (redis_num == 0) {
        wx.showToast({
          title: '超出活动库存',
          icon: 'none',
        });
        // getApp().my_warnning('超出活动库存', 0, th);
        th.setData({
          [txt]: redis_num
        });
        return false;
      };

      if (t.goods_num > redis_num) {
        wx.showToast({
          title: '超出活动库存',
          icon: 'none',
        });
        // getApp().my_warnning('超出活动库存', 0, th);
        th.setData({
          [txt]: redis_num
        });
        return false;
      };

      // 个人限购
      //----获取用户活动购买数----
      await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum?store_id=" + t.store_id + "&user_id=" + getApp().globalData.user_id + "&card_id=" + t.goods_id + "&prom_type=" + t.prom_type + "&prom_id=" + t.prom_id, {}).then(tt => {
        if (tt.data.code == 0) {
          th.setData({
            promcardbuynum: tt.data.data.promcardbuynum,
            cardbuynum: tt.data.data.cardbuynum,
          });
        }
      });


      var buylimit = 0
      await getApp().request.promiseGet("/api/ms/flash_sale/getNew/" + t.store_id + "/" + getApp().globalData.user_id + "/" + t.prom_id, {

      }).then(res => {
        if (res.data.code == 0) {

          th.data.sele_g = res.data.data;
          th.data.sele_g.viplimited = res.data.data.buy_limit;
          buylimit = res.data.data.buy_limit;
        }
      });


      //--秒杀：判断商品是否超出活动限购--
      if (buylimit > 0) {

        var gd_buy_num = th.data.promcardbuynum;

        // 如果限购数量<=活动库存数量，增加数量时会先超过限购数量，此时应提示“超出活动限购数量”
        if (t.goods_num + gd_buy_num > buylimit) {
          // 计算还可以购买的数量：库存量 - 已购数
          wx.showToast({
            title: '超出活动限购',
            icon: 'none',
          });
          // getApp().my_warnning('超出活动限购', 0, th);
          th.setData({
            [txt]: buylimit
          });
        };

      }

      th.doCheckAll();
      th.update_cart_ser(t, pitem, item);


    }
  },

  //---检验线下库存的数量---
  async check_down_line(t, pitem, item, erpwareid) {
    var ob = {},
      th = this;
    await this.check_down_line_next(t, pitem, item, erpwareid, function (res) {
      ob = res;
    });
    var log = 0;
    if (ob.code == -1) {
      // wx.showModal({
      //     title: '提示',
      //     content: '购买数量超出商品库存'
      // });
      wx.showToast({
        title: '购买数量超出商品库存',
        icon: 'none',
      });
      // getApp().my_warnning('购买数量超出商品库存', 0, th);
      var txt = "requestData[" + pitem + "].goods[" + item + "].goods_num";
      th.setData({
        [txt]: ob.CanOutQty
      });
      th.doCheckAll();
      t.goods_num = ob.CanOutQty;
    } else {

      var this_obj = this.data.requestData[pitem].goods[item];

      if (th.data.sales_rules >= 2 && this_obj.selected) {

        var goods_id = this_obj.goods_id;
        var num = 0;

        for (let i = 0; i < this.data.requestData.length; i++) {
          if (pitem == i) continue;
          var it = this.data.requestData[i].goods.find((e) => {
            return e.goods_id == goods_id;
          })
          if (it && it.selected) num += it.goods_num
        }

        if (num > ob.CanOutQty) {
          wx.showToast({
            title: '购买数量超出商品库存',
            icon: 'none',
          });

          th.data.up_dating = 0;
          return false;
        }

      }
    }


    this.update_cart(t, pitem, item);
  },



  //---检验线下库存的数量的子函数---
  async check_down_line_next(t, pitem, item, erpwareid, func) {

    var goodsinfo = this.data.requestData[pitem].goods[item];
    if (getApp().is_virtual(goodsinfo)) {
      var ob = {};
      ob.code = 1;
      ob.CanOutQty = 100000;
      func(ob);
      return false;
    }


    var lock = 0,
      pick_no, plist;

    var lock_rq = {
      store_id: os.stoid,
      wareId: t.goods_id,
      storageId: goodsinfo.pick_id,
      pageSize: 1000
    }

    if (this.data.sales_rules == 3) {
      lock_rq.appoint_pick_keyid = this.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;
      }
    })

    if (this.data.sales_rules == 2) {
      //先获取门店的编号
      await getApp().request.promiseGet("/api/weshop/pickup/get/" + os.stoid + "/" + goodsinfo.pick_id, {
        data: {
          storeId: os.stoid,
          goodsId: t.goods_id,
          pickupId: goodsinfo.pick_id
        }
      }).then(res => {
        if (res.data.code == 0) {
          pick_no = res.data.data.pickup_no;
        }
      })
    }

    var sto_rq = {
      storageNos: pick_no,
      wareIds: encodeURIComponent(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 (ut.ajax_ok(res)) {
        plist = res.data.data.pageData[0];
      }
    })
    var ob = {};
    ob.code = 1;

    if (!plist) {
      ob.code = -1;
      ob.CanOutQty = 0;
      func(ob);
      return false;
    }

    var c_num = t.goods_num;
    if (t.need_downlow_num) c_num = t.need_downlow_num;

    if (c_num > plist.CanOutQty - lock) {
      ob.code = -1;
      ob.CanOutQty = plist.CanOutQty - lock
      if (ob.CanOutQty < 0) ob.CanOutQty = 0;
    } else {
      ob.CanOutQty = plist.CanOutQty - c_num - lock;
    }


    func(ob)
  },


  //--更新购物车---
  update_cart: function (t, pitem, item) {
    var e = this;

    getApp().request.put("/api/weshop/cart/update", {
      data: t,
      success: async function (ee) {

        //-- 要先跟新一下商品的数量，在来计算商品价格  --
        var txt = "requestData[" + pitem + "].goods[" + item + "].goods_num";
        e.setData({
          [txt]: t.goods_num,
        });

        e.doCheckAll(async function (){
            e.data.duo_zp_num_arr = {};
            //await e.check_prom_activity(pitem)
            for (var i in e.data.requestData) {
              await e.check_prom_activity(i)
            }
        });
        getApp().requestCardNum(e);
      }
    });
  },

  //--更新购物车---
  update_cart_ser: function (t, pitem, item) {
    var e = this;

    getApp().request.put("/api/weshop/cartService/update", {
      data: t,
      success: async function (ee) {
        var txt = "service_data[" + pitem + "].goods[" + item + "].goods_num";
        e.setData({
          [txt]: t.goods_num,
        });
        e.doCheckAll();
        getApp().requestCardNum(e);
      }
    });
  },


  //-------下拉刷新---------
  onPullDownRefresh: function (t) {
    this.getCardList();
  },


  clear_checkouting(){
       wx.hideLoading();
       this.data.checkouting=0;
  },

  //--------------去结算------------
  async checkout() {
    if (getApp().is_sp_hao()) {
      wx.showToast({
        title: "视频号不支持购物车购买",
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    if (!this.data.total_num || this.data.total_num <= 0) {
      wx.showToast({
        title: "请选择商品",
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (!this.data.is_load) return false;
    if (this.data.up_dating) {
      wx.showLoading({
        title: "计算中"
      })
    }
    //--- 避免重复点击 ---
    if(this.data.checkouting) return false;
    this.data.checkouting=1;

    var garr = this.data.requestData;
    var check_is_goods_selected = 0;

    var th=this;

    if (garr) {
      for (var ii in garr) {
        for (var ij in garr[ii].goods) {
          if (garr[ii].goods[ij].selected) {
            check_is_goods_selected = 1;
            break;
          }
        }
      }
    }
    //-- 如果是商品的结算 --
    if (check_is_goods_selected) {
      var glist = []; //商品数组
      var map = new Map();       //使用map值键进行运算
      this.data.act_buy_map={};  //使用map值键进行运算活动商品的购买数量

      var g_arr = new Array(); //已选的商品列表
      var user_id = getApp().globalData.user_id;

      //用于判断是不是积分购的普通购买
      var normal_arr = {};
      var ab = 0; //选中
      wx.showLoading();
      let checkArr7 = []; //组合购选中的数据
      let checkObj3 = {}; //优惠促销次数判断

      var zh_buyed_m={};
      var zh_limit_m={}
      var zh_all_ck={};

      //多门店的时候，控制不能超出限购
      var yh_by_map={};
      // let checkOff=false
      for (var i = 0; i < this.data.requestData.length; i++) {

        var pid=this.data.requestData[i].pid;
        var _pick=null;
        var i_arr = this.data.requestData[i].goods;

        //-- 优化不用调用接口 --
        _pick={
          pickup_id:pid,
          distr_type:i_arr[0].pickup_distr_type
        };

        //判断一下商品能不能满足优惠促销的条件
        await th.check_can_yh_pro(i_arr);

        for (var j = 0; j < i_arr.length; j++) {
          if (i_arr[j].selected && i_arr[j].is_gift != 1) {

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

            if (i_arr[j].is_pd_normal || i_arr[j].prom_type == 0 || i_arr[j].prom_type == 3) {
              normal_arr[i_arr[j].goods_id] = 1;
            }

            //检查活动是不是满足了条件，或者要取满足条件的活动
            var fd1 = null;
            if (this.data.requestData[i].show_can_cx && (i_arr[j].prom_type == 3 || i_arr[j].prom_type == 7)) {

              var show_can_cx=this.data.requestData[i].show_can_cx;
              //-- 查找选中了什么 --
              for (var ik in show_can_cx) {
                var ch_map = show_can_cx[ik].ch_map;
                if (ch_map.indexOf(i_arr[j].goods_id) == -1) continue;

                var item_arr = show_can_cx[ik].act_arr;
                fd1 = item_arr.find(function (hb) {
                  return hb.sele;
                })
                if (fd1) break;
              }
              if (!fd1) {
                i_arr[j].prom_id = 0;
                i_arr[j].prom_type = 0;
              } else {
                i_arr[j].prom_id = fd1.prom_id;
                i_arr[j].prom_type = fd1.prom_type;

                var ky=i_arr[j]['prom_type']+'-'+i_arr[j]['prom_id']+'-'+i_arr[j]['goods_id'];
                var ky_n=0;
                if(yh_by_map[ky]){
                  ky_n+=yh_by_map[ky];
                }
                //-- 判断优惠促销活动的商品的限购,can_yh 表示商品满足优惠促销的条件 --
                if(i_arr[j].prom_type==3 && fd1.act.goodslimit>0 && i_arr[j].can_yh ){
                  var p_can_by=fd1.act.goodslimit-fd1.act.goodslimited;
                  if(i_arr[j].goods_num+ky_n>p_can_by){
                    getApp().confirmBox(i_arr[j].goods_name + "超出活动限购数量"+fd1.act.goodslimit+"件");
                    th.clear_checkouting();
                    return false;
                  }
                }
                //-- 把购物数量记录到map表中 --
                if(!yh_by_map[ky]) yh_by_map[ky]=0;
                yh_by_map[ky]+=i_arr[j].goods_num;

              }
            }


            if (i_arr[j].prom_type == 7  && i_arr[j].act && (i_arr[j].act.buy_limit>0 || i_arr[j].act.zh_num>0) ) {

              let userbuynum = await this.getUserBuyPromNum(i_arr[j].prom_id);

              if(!zh_buyed_m[i_arr[j].prom_id]) zh_buyed_m[i_arr[j].prom_id]=userbuynum;
              if(i_arr[j].act.buy_limit>0){
                if(!zh_limit_m[i_arr[j].prom_id]) zh_limit_m[i_arr[j].prom_id]=i_arr[j].act.buy_limit;
              }

              console.log('活动次数：' + userbuynum);

              if(0 >= i_arr[j].act.zh_num-i_arr[j].act.zh_buy_num && i_arr[j].act.zh_num>0){
                i_arr[j].out_all_num=1;
                checkArr7.push(i_arr[j])
              }else if (userbuynum >= i_arr[j].act.buy_limit && i_arr[j].act.buy_limit>0) {
                // i_arr[j].act.buy_userbuynum=true
                checkArr7.push(i_arr[j])
              }else{
                if (zh_all_ck[i_arr[j].prom_id]) {
                  //相同门店只记录一单
                  if(zh_all_ck[i_arr[j].prom_id].indexOf(i)==-1)  zh_all_ck[i_arr[j].prom_id].push(i);
                } else {
                  zh_all_ck[i_arr[j].prom_id] = [i];
                }

              }
            }
            //-- 优惠活动次数限制,相同门店的相同prom_id只能算一次 --
            if (i_arr[j].prom_type == 3) {
              if (checkObj3[i_arr[j].prom_id]) {
                if(checkObj3[i_arr[j].prom_id].indexOf(i)==-1) checkObj3[i_arr[j].prom_id].push(i);
              } else {
                checkObj3[i_arr[j].prom_id] = [i];
              }
            }

            //如果是普通购买的时候。
            if(i_arr[j].is_integral_normal || i_arr[j].is_pd_normal ){
              //-- 四大促销 --
              if([3,5,7,10].indexOf(i_arr[j].prom_tyoe)==-1){
                i_arr[j].prom_id=0;
                i_arr[j].prom_type=0;
              }
            }

            //map 的key是不会重复，会覆盖，，
            var ie = {
              goods_id: i_arr[j].goods_id,
              id: i_arr[j].id,
              goods_price: i_arr[j].goods_price,
              prom_id: i_arr[j].prom_id,
              prom_type: i_arr[j].prom_type,
              g_num:i_arr[j].goods_num  //新增
            };
            //判断是不是线下取价
            if (i_arr[j].is_offline) {
              ie.is_offline = i_arr[j].is_offline;
              ie.offline_price = i_arr[j].offline_price;
              ie.pricing_type = i_arr[j].pricing_type;
            }
            g_arr.push(ie);

            //赠品不拿来计算库存
            if(!i_arr[j].is_gift) {
                if (map.has(i_arr[j].goods_id + "")) {
                  var num11 = map.get(i_arr[j].goods_id + "");
                  var num22 = parseInt(i_arr[j].goods_num) + parseInt(num11);
                  map.set(i_arr[j].goods_id + "", num22);
                } else {
                  map.set(i_arr[j].goods_id + "", i_arr[j].goods_num);
                }

                var ky_0=i_arr[j].prom_type + "-"+i_arr[j].prom_id;
                if(th.data.act_buy_map[ky_0]){
                   var n11 = th.data.act_buy_map[ky_0];
                   var n22 = parseInt(i_arr[j].goods_num) + parseInt(num11);
                   th.data.act_buy_map[ky_0]=n22
                }else{
                   th.data.act_buy_map[ky_0]=i_arr[j].goods_num
                }

            }
            //glist += i_arr[j].goods_id + ",";
            if(!i_arr[j].is_gift){
              var et= {"prom_type":i_arr[j].prom_type,"prom_id":i_arr[j].prom_id,"goods_id":i_arr[j].goods_id};
              glist.push(et);
            }
            
            ab = 1;

            //-- 获取促销活动是不是有参与 --
            var act = getApp().get_has_cx_act2(i_arr[j].goodsActinfo);
            //-- 判断商品的起订数量 --
            var mo_num = getApp().get_limit_qty(i_arr[j], act.length);
            var steep = getApp().get_limit_qty(i_arr[j], act.length, 1);
            var py_type = parseInt(i_arr[j].prom_type + '');

            //-- 商品只查一次。看一下有没有,门店之前第一次就赋值了 --
            var gd = i_arr[j];
            //判断秒杀的指定门店和团购的指定门店
            if([1,2].indexOf(py_type)>-1 && i_arr[j].prom && i_arr[j].prom.pick_up_lists){
              var idx0=i_arr[j].prom.pick_up_lists.findIndex(function (e){
                return e.pickup_id==i_arr[j].pick_id;
              })
              if(idx0<0){

                var act_type=0;
                if(py_type==1) act_type='秒杀';
                if(py_type==2) act_type='团购';

                getApp().confirmBox(i_arr[j].goods_name + act_type+"活动的门店不可售");
                th.clear_checkouting();
                return false;
              }
            }

            if ([0, 3, 5, 7, 10].indexOf(py_type) > -1) {
              //如果是指定门店，就要判断
              if(gd.pick_group_ids){
                var idx0=gd.pick_up_lists.findIndex(function (e){
                  return e.pickup_id==i_arr[j].pick_id;
                })
                if(idx0<0){
                  getApp().confirmBox(i_arr[j].goods_name + "的门店不可售");
                  th.clear_checkouting();
                  return false;
                }
              }

              if (mo_num > i_arr[j].goods_num) {
                getApp().confirmBox(i_arr[j].goods_name + "的未达到起订数量");
                th.clear_checkouting();
                return false;
              }
              if (steep > 1 && (i_arr[j].goods_num - mo_num) % steep != 0) {
                getApp().confirmBox(i_arr[j].goods_name + "的购买的数量不是起订量的倍数");
                var num = mo_num + parseInt((i_arr[j].goods_num - mo_num) / steep) * steep + steep;
                var e = {
                  goods_num: num,
                  id: i_arr[j].id,
                  goods_id: i_arr[j].goods_id,
                  store_id: oo.stoid
                };

                th.postCardList(e, j, i);

                th.clear_checkouting();
                return false;
              }

            }

            //--普通商品，如果有开启线下库存的功能，要调用线下库存进行计算,赠品不要进行调用线下库存---
            if ((i_arr[j].prom_type == 0 || i_arr[j].prom_type == 3 || i_arr[j].prom_type == 5 || i_arr[j].prom_type == 7 || i_arr[j].prom_type == 10 ||
                i_arr[j].need_downlow_num) && th.data.sales_rules >= 2 && i_arr[j].is_gift != 1 && !i_arr[j].whsle_id) {

              //--判断商品是线下库存--
              var ob = {}
              await th.check_down_line_next(i_arr[j], i, j, gd.erpwareid, function (rs) {
                ob = rs;
              });
              if (ob.code == -1) {
                t.my_warnning(gd.goods_name + "门店库存不足", 0, th);
                th.clear_checkouting();
                return false;
              }

              var is_ok = 1;

              //如果是优惠活动话，要看活动有没有过期
              if (i_arr[j].prom_type == 3) {
                //判断有没有活动
                await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromList/" + os.stoid + "/" + i_arr[j].goods_id + "/1" + "/" + getApp().globalData.user_id, {}).then(res => {
                  if (res.data.code == 0) {
                    if (!res.data.data.promGoodsLists) {
                      t.my_warnning(i_arr[j].goods_name + "优惠活动已经过期", 0, th);
                      th.clear_checkouting();
                      is_ok = 0;
                    }
                  }
                })
              }
              if (!is_ok) {
                return false;
              }
            }

          } else {
            if (i_arr[j].is_gift == 1) continue;
            // rq.put("/api/weshop/cart/update", {
            //   data: {
            //     id: i_arr[j].id,
            //     selected: 0,
            //     store_id: oo.stoid
            //   },
            //   success: function (ee) {
            //     console.log(ee);
            //   }
            // });
          }
        }
      }


      console.log(checkObj3);
      let checkObj3_off = false

      //多门店优惠促销次数控制
      if (this.data.requestData.length > 1) {
        let pro_stord_id = ''
        let pro_stord_off = false
        this.data.requestData.map(ritem => {
          ritem.goods.map(gitem => {
            if (gitem.selected && gitem.prom_type == 3) {
              if (pro_stord_id) {
                if (gitem.pick_id != pro_stord_id) {
                  pro_stord_off = true
                }
              } else {``
                pro_stord_id = gitem.pick_id
              }
            }
          })
        })
        if (pro_stord_off) {
          let checkarr3 = Object.keys(checkObj3)
          if (checkarr3 && checkarr3.length > 0) {
            for (let x = 0; x < checkarr3.length; x++) {
              let prom = null
              let key = checkarr3[x]
              await getApp().request.promiseGet("/api/weshop/promgoods/get/" + os.stoid + "/" + key, {}).then(res => {
                if (res.data.code == 0) {
                  prom = res.data.data;
                }
              })

              if (prom && prom.limit_num) {
                let user_pre_buynum = await this.getUserBuyPromNum_pre(key)
                if (user_pre_buynum < prom.limit_num) {
                  user_pre_buynum +=  checkObj3[key].length
                  if (user_pre_buynum > prom.limit_num) {
                    checkObj3_off = true
                  }
                }

              }
            }
          }
        }
      }

      if (checkObj3_off) {
        t.my_warnning("已超出优惠促销次数", 0, th);
        th.clear_checkouting();
        return false
      }

      let zh_off = false
      //-- 如果有组合购限购的时候 --
      let zh_ck_arr = Object.keys(zh_limit_m);
      if(zh_ck_arr && zh_ck_arr.length ){
        for (let xg = 0; xg < zh_ck_arr.length; xg++) {
          var ky=zh_ck_arr[xg];
          var zh_buyed=zh_buyed_m[ky]?zh_buyed_m[ky]:0;
          var zh_limit=zh_limit_m[ky]?zh_limit_m[ky]:0;
          var zh_all=zh_all_ck[ky]?zh_all_ck[ky].length:0;
          if(zh_limit<=0) continue;

          if(zh_all+zh_buyed>zh_limit){
            zh_off=true;
            break;
          }
        }
      }

      if (zh_off) {
        t.my_warnning("已超出组合购优惠次数", 0, th);
        th.clear_checkouting();
        return false
      }


      if (checkArr7.length > 0) {

        let checkStr = [];
        let checkStr2 = [];

        checkArr7.map(item => {
          if(item.out_all_num){
            checkStr2.push(item.goods_name);
          }else{
            checkStr.push(item.goods_name)
          }
        })

        var msg_str='';
        if(checkStr.length){
          let str = checkStr.join();
          msg_str=`${str}超出组合购限购次数，将以普通商品购买`;
        }
        if(checkStr2.length){
          if(msg_str) msg_str+=",";
          msg_str+=checkStr2.join()+"超出组合购总数，将以普通商品购买";
        }

        wx.hideLoading()
        wx.showModal({
          title: '提示',
          // content: `商品${str},组合购活动，购买次数已超，将以普通商品购买？`,
          content: msg_str,
          success: res => {
            wx.showLoading();
            if (res.confirm) {
              console.log('用户点击确定')
              //排除失效商品结算
              this.data.invalidList.map(item => {
                if (item.selected && item.classType == 0) {
                  rq.put('/api/weshop/cart/update', {
                    data: {
                      id: item.id,
                      selected: 0,
                      store_id: oo.stoid
                    },
                    success: function (ee) {
                      console.log(ee);
                    }
                  });
                }
              })
              if (ab == 0) {
                t.my_warnning("未选择商品", 0, th);
                th.clear_checkouting();
                return false;
              }

              //进行到下一步
              th.cart_buy_next(glist,map,g_arr,checkArr7)

            } else if (res.cancel) {
              th.clear_checkouting();
              console.log('用户点击取消')
            }
          }
        })
      } else {
        //排除失效商品结算
        this.data.invalidList.map(item => {
          if (item.selected && item.classType == 0) {
            rq.put('/api/weshop/cart/update', {
              data: {
                id: item.id,
                selected: 0,
                store_id: oo.stoid
              },
              success: function (ee) {
                console.log(ee);
              }
            });
          }
        })
        if (ab == 0) {
          t.my_warnning("未选择商品", 0, th);
          th.clear_checkouting();
          return false;
        }

        //进行到下一步
        th.cart_buy_next(glist,map,g_arr,checkArr7)

      }
    } else {

      //进行累计，秒杀和团购的购买数量
      var flash_map = {};
      var group_map = {};

      //-- 开始服务卡的购物车购买 --
      for (var i = 0; i < this.data.service_data.length; i++) {
        var i_arr = this.data.service_data[i].goods;
        console.log(i_arr)

        for (var j = 0; j < i_arr.length; j++) {
            await rq.promisePut("/api/weshop/cartService/update", {
              data: {
                id: i_arr[j].id,
                selected: i_arr[j].selected,
                store_id: oo.stoid
              }
            });

            //-- 服务卡项的可售情况 --
            var sto_list=i_arr[j].sto_list;
            if(sto_list){
              let the_c_key=this.data.service_data[i].keyid
              if (sto_list.indexOf(the_c_key)==-1) {
                getApp().confirmBox(i_arr[j].service_name + "的门店不可售");
                th.clear_checkouting();
                return false;
              }
            }

            //判断秒杀的指定门店
            if( [1,2].includes(i_arr[j].prom_type) && i_arr[j].prom && i_arr[j].prom.pick_up_lists && i_arr[j].selected){
              var idx0=i_arr[j].prom.pick_up_lists.findIndex(function (e){
                return e.pickup_id==i_arr[j].pick_id;
              })
              if(idx0<0){
                getApp().confirmBox(i_arr[j].service_name + "秒杀活动的门店不可售");
                th.clear_checkouting();
                return false;
              }
            }

            //选中的情况下才进行计算
            if(i_arr[j].selected) {
              //进行秒杀和团购的累计
              switch (i_arr[j].prom_type) {
                case 1:
                  if (!flash_map[i_arr[j].prom_id]) {
                    flash_map[i_arr[j].prom_id] = {prom: i_arr[j].prom, num: i_arr[j].goods_num};
                  } else {
                    flash_map[i_arr[j].prom_id].num += i_arr[j].goods_num;
                  }
                  break;
                case 2:
                  if (!group_map[i_arr[j].prom_id]) {
                    group_map[i_arr[j].prom_id] = {prom: i_arr[j].prom, num: i_arr[j].goods_num};
                  } else {
                    group_map[i_arr[j].prom_id].num += i_arr[j].goods_num;
                  }
                  break;
              }
            }
        }
      }

      //判断flash_map是不是空,同时判断flash prom.buy_limit
      if(Object.keys(flash_map).length>0){
        for(let i in flash_map){


         if(flash_map[i].prom.buy_limit>0) {
           //查一下团购已经购买了多少减
           var f_buyed = 0;
           //获取当前商品活动库存
           var fl_rs=await th.get_buy_num_ser_2(flash_map[i].prom.goods_id,1,flash_map[i].prom.id);
           if(fl_rs.data.code==0 && fl_rs.data.data  && fl_rs.data.data.promcardbuynum){
             f_buyed=fl_rs.data.data.promcardbuynum
           }

           if (flash_map[i].num+f_buyed> flash_map[i].prom.buy_limit) {
             getApp().confirmBox(flash_map[i].prom.title + "秒杀活动的超出活动限购");
             th.clear_checkouting();
             return false;
           }
         }
          let redis_num=0;
          //获取当前商品活动库存
          await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" +oo.stoid + "/1/" + i, {
            1: 1
          }).then(res => {
            redis_num = res.data.data;
          });
          if(flash_map[i].num>redis_num){
            getApp().confirmBox(flash_map[i].prom.title + "秒杀活动的超出活动数量");
            th.clear_checkouting();
            return false;
          }
        }
      }
      //group_map,同时判断group prom.buy_limit
      if(Object.keys(group_map).length>0){
        for(let jg in group_map){

           if(group_map[jg].prom.buy_limit>0){
             //查一下团购已经购买了多少减
             var gr_buyed=0;
             //获取当前商品活动库存
             var gb_rs=await th.get_buy_num_ser_2(group_map[jg].prom.goods_id,2,group_map[jg].prom.id);
             if(gb_rs.data.code==0 && gb_rs.data.data && gb_rs.data.data.promcardbuynum){
               gr_buyed=gb_rs.data.data.promcardbuynum
             }
             if(group_map[jg].num+gr_buyed>group_map[jg].prom.buy_limit){
               getApp().confirmBox(group_map[jg].prom.title + "团购活动的超出活动限购");
               th.clear_checkouting();
               return false;
             }

           }


            let redis_num=0;
            //获取当前商品活动库存
            await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" +oo.stoid+ "/2/" + jg, {
              1: 1
            }).then(res => {
              redis_num = res.data.data;
            });
            if(group_map[jg].num>redis_num){
              getApp().confirmBox(group_map[jg].prom.title + "团购活动的超出活动数量");
              th.clear_checkouting();
              return false;
            }
        }
      }


      //排除失效服务结算
      this.data.invalidList.map(item => {
        if (item.selected && item.classType == 1) {
          rq.promisePut('/api/weshop/cartService/update', {
            data: {
              id: item.id,
              selected: 0,
              store_id: oo.stoid
            }
          });
        }
      })

      getApp().goto("/packageA/pages/cart2_ser/cart2_ser?is_cart=1");
    }
  },


  cart_buy_next(glist,map,g_arr,checkArr7){
    var th=this;
    var map_limit = new Map(); //使用map值键进行存储限购,这里存的是活动的
    var act_buyed_map={};      //活动当前购买数量的map
    var up_cart_data=[];

    //获取活动的购买的数量
    for (let ig = 0; ig <g_arr.length ; ig++) {
      var t_iter = g_arr[ig];
      var ky=t_iter.goods_id + "-"+t_iter.prom_type + "-"+t_iter.prom_id;
      var obj = act_buyed_map[ky];
      if (obj){
        obj.g_num+=t_iter.g_num;
        continue;
      }
      var ie = { g_num:t_iter.g_num};
      act_buyed_map[ky]= ie;
    }

    //--取一下商品的限购  以及活动的限购，redis数量--
    getApp().request.promisePost("/api/weshop/goods/listGoodsListNumNew", {
      is_json:1,
      data: {
        listNumNewDtos: glist,
        store_id: oo.stoid,
        user_id:getApp().globalData.user_id,
      }
    }).then(async ee=>{
      if (ee.data.code == 0 && ee.data.data && ee.data.data.length) {
        var ddata = ee.data.data,
            isok = 1,
            gname = "",
            err = "";

        //--组装活动购买的限购--
        for (var ij = 0; ij < ddata.length; ij++) {
          var val = ddata[ij];
          var ky=val.goods_id + "-"+val.prom_type + "-"+val.prom_id;
          var obj = map_limit.get(ky);
          if (obj){
            continue;
          }
          var promgoodsbuynum =val.promgoodsbuynum || 0;
          var goodsbuynum =val.goodsbuynum || 0;
          var ie = {
            promgoodsbuynum: promgoodsbuynum,
            goodsbuynum:goodsbuynum
          };
          map_limit.set(ky, ie);
        }

        //try {
        for (var ind in ddata) {
          var val = ddata[ind];
  
          var ky=val.goods_id + "-"+val.prom_type + "-"+val.prom_id;
          var ky2=val.prom_type + "-"+val.prom_id;

          var num = map.get(val.goods_id + "");
          var num2 = th.data.act_buy_map[ky2];

          var buyed = map_limit.get(ky);
          var cur_buyed=act_buyed_map[ky]

          if (num <= 0) {
            isok = 0;
            gname = val.goods_name;
            err= "购买数量不能为0";
            return false;
          }

          if (val.prom_type == 1 || val.prom_type == 2) {
            var s_num=num;
            //if(th.data.sales_rules> 1) s_num=buyed;
            if (s_num > val.store_count) {
              isok = 0;
              gname = val.goods_name;
              err="超出库存";
              return false;
            }

            if(cur_buyed && cur_buyed.g_num > val.redisnum && val.redisnum) {
              isok = 0;
              gname = val.goods_name;
              err="超出活动库存";
              break;
            }

            if(cur_buyed && cur_buyed.g_num > val.goods_num - val.buy_num && val.goods_num) {
              isok = 0;
              gname = val.goods_name;
              err="超出活动库存";
              break;
            }
          }

          if (th.data.sales_rules == 1 || val.prom_type == 1 || val.prom_type == 2) {
            if (num > val.store_count) {
              isok = 0;
              gname = val.goods_name;
              err="超出库存";
              break;
            }
          }

          if (num + buyed.goodsbuynum > val.viplimited && val.viplimited > 0) {
            isok = 0;
            gname = val.goods_name;
            err="超出商品限购";
            break;
          }

          if (num2 + buyed.promgoodsbuynum > val.buy_limit && val.buy_limit > 0) {
            isok = 0;
            gname = val.goods_name;
            err="超出活动限购";
            break;
          }

          var card_field = th.data.card_field;
          for (var i = 0; i < g_arr.length; i++) {
            if (g_arr[i].goods_id == val.goods_id) {

              //如果会员是等级会员,商品有等级价,且不是活动商品
              if (card_field && val[card_field] > 0 &&
                  ((val.prom_type == 0 && g_arr[i].prom_type == 0)  || g_arr[i].prom_type == 5 || g_arr[i].prom_type == 7 || g_arr[i].prom_type == 10)) {
                if (g_arr[i].goods_price != val[card_field]) {
                  isok = 0;
                  gname = val.goods_name;
                  err="商品价格已经变化";
                  break;
                }
              } else {
                if (g_arr[i].goods_price != val.shop_price && g_arr[i].goods_price != val.prom_price && val.prom_price > 0 && (g_arr[i].prom_type==1 && g_arr[i].prom_type==2) ) {
                  isok = 0;
                  gname = val.goods_name;
                  err="商品价格已经变化";
                  break;
                }
              }

              //-- 数据的更新 --
              var data = {
                id: g_arr[i].id,
                selected: 1,
                store_id: oo.stoid,
                prom_type: g_arr[i].prom_type,
                prom_id: g_arr[i].prom_id,
              };

              // let gitem = checkArr7.find(item => item.goods_id == g_arr[i].goods_id)
              // if (gitem) {
              //   data.prom_type = 0
              //   data.prom_id = 0
              // }

              //-- 如果有线下取价的时候 --
              if (g_arr[i].is_offline) {
                data.pricing_type = g_arr[i].pricing_type;
                data.offline_price = g_arr[i].offline_price;
              }
              //把更新数组存起来
              up_cart_data.push(data);

            }
          }

          if(!isok) break;

        }
        // } catch (e) {
        //   err = e;
        // }
        if (isok == 0) {
          t.confirmBox(gname + ":" + err);
          th.clear_checkouting();
          return false;
        }

        getApp().request.promisePost("/api/weshop/cart/updateCartPromInfo", {
          is_json: 1,
          data: up_cart_data,
        });

        wx.navigateTo({
          url: "/packageE/pages/cart/cart2/cart2"
        });
      }
    })
  },



  //结算到最后一个商品
  set_last: function (ab, isok, gname) {
    if (isok == 0) {
      t.my_warnning(gname + "商品超出库存", 0, this);
    } else {
      ab ? wx.navigateTo({
        url: "/packageE/pages/cart/cart2/cart2"
      }) : t.my_warnning("还没有选中商品", 0, this);
    }
  },


  //图片失败，默认图片
  bind_bnerr2: function (e) {
    var _errImg = e.target.dataset.errorimg;
    var _errurl = e.target.dataset.url;
    var ii = _errurl.indexOf(oo.imghost);
    if (ii != -1) {
      this.setData({
        [_errImg]: oo.imghost + "/miniapp/images/default_g_img.gif",
      })
    }
  },
  //设置点击按钮为true或者false
  radio_chick: function (checked, num) {
    var th = this;
    var requestData = th.data.requestData;
  },

  //点击编辑后的效果
  edit_cart: function (e) {
    var type = parseFloat(e.currentTarget.dataset.type);
    this.setData({
      is_edit: type
    });

    let dda = this.data.requestData;
    let sdda = this.data.service_data;

    //清空选中的状态
    if (dda && dda.length > 0) {
      for (var i = 0; i < dda.length; i++) {
        var item = dda[i].goods;
        var txt0 = "requestData[" + i + "].selected";
        this.setData({
          [txt0]: 0,
        });

        for (var j = 0; j < item.length; j++) {
          let txt = "requestData[" + i + "].goods[" + j + "].selected";
          this.setData({
            [txt]: 0,
          });
        }
      }
    }

    //清空选中的状态
    if (sdda && sdda.length > 0) {
      for (i = 0; i < sdda.length; i++) {
        var item1 = sdda[i].goods;
        var txt00 = "service_data[" + i + "].selected";
        this.setData({
          [txt00]: 0,
        });

        for (j = 0; j < item1.length; j++) {
          let txt1 = "service_data[" + i + "].goods[" + j + "].selected";
          this.setData({
            [txt1]: 0,
          });
        }
      }
    }

    this.setData({
      checkAllToggle: 0,
    })


  },

  //--多个删除购物车商品---
  check_del: function () {
    var glist = "",
      slist = ''; //用逗号隔开的
    var user_id = getApp().globalData.user_id;
    var th = this;

    var ab = 0; //选中
    var abc = 0;

    //如果有普通商品的时候
    if(this.data.requestData && this.data.requestData.length){
      for (var i = 0; i < this.data.requestData.length; i++) {
        var i_arr = this.data.requestData[i].goods;
        for (var j = 0; j < i_arr.length; j++) {
          if (i_arr[j].selected) {
            glist += i_arr[j].id + ",";
            ab = 1;
          }
        }
      }
    }

    //如果有普通服务卡的时候
    if(this.data.service_data && this.data.service_data.length){
      for (var ii = 0; ii < this.data.service_data.length; ii++) {
        var i_arr = this.data.service_data[ii].goods;
        for (var jj = 0; jj < i_arr.length; jj++) {
          if (i_arr[jj].selected) {
            slist += i_arr[jj].id + ",";
            abc = 1;
          }
        }
      }
    }




    if (ab == 0 && abc == 0) {
      t.my_warnning("未选择商品或者服务卡", 0, th);
      return false;
    }

    if (ab) {
      glist = glist.substring(0, glist.length - 1);
      //要删除购物车中的商品
      var url = '/api/weshop/cart/delIds/' + oo.stoid + '/' + user_id + "/" + glist;
      getApp().request.delete(url, {
        success: function (t) {
          // console.log('del done1111111111');
          th.getCardList();
          getApp().requestCardNum(th);
          // console.log('all================', th.data.all_num);
          // getApp().globalData.cartGoodsNum = 
        }
      });
    }
    if (abc) {
      slist = slist.substring(0, slist.length - 1);
      //要删除购物车中的商品
      var url = '/api/weshop/cartService/delIds/' + oo.stoid + '/' + user_id + "/" + slist;
      getApp().request.delete(url, {
        success: function (t) {
          th.getCardList();
          getApp().requestCardNum(th);
          console.log('all2================', th.data.all_num);
        }
      });
    }

    setTimeout(() => {
      if ((!th.data.requestData || th.data.requestData.length == 0) && (!th.data.service_data || th.data.service_data.length == 0)) {

        console.log('---1111---bb');
        var goods_list = th.selectComponent("#goods_list"); //组件的id
        if (goods_list) {
          goods_list.init();
          goods_list.get_list();
        }

      }

    }, 1200)


  },

  //跳到首页
  goto: function (e) {
    var url = '/pages/index/index/index';
    getApp().goto(url);
  },

  //---加载更多是靠这个函数----
  onReachBottom: function () {
    if (this.data.requestData && this.data.requestData.length == 0) {
      var goods_list = this.selectComponent("#goods_list"); //组件的id
      if (goods_list) goods_list.get_list();
    }
  },

  //检查莫个门店下的商品是不是优惠活动，有的话，看要不要送礼品，同时有没有倍增
  check_prom_activity: async function (cindex) {
    var make_up_arr = new Array();
    var send_gift_arr = new Array();
    var th = this;
    var map = new Map();
    var list = JSON.parse(JSON.stringify(this.data.requestData[cindex]));
    //循环处理活动，看活动商品的数量，用map来出来存储，key为活动id，值是数量

    //-- 所有的购物车的数据，要用拷贝的赖进行计算 --
    var alllist = JSON.parse(JSON.stringify(this.data.requestData));
    //var list2 = alllist[cindex];
    var no_gift_arr = [];

    //用来存销赠品的--2024-2-1
    let cart_zp=this.data.cart_zp;
    //要清空一下门店下的赠品
    if(cart_zp[list.pid] && cart_zp[list.pid].goods && cart_zp[list.pid].goods.length){
      let ids = cart_zp[list.pid].goods.map(obj => obj.id);
      //-- 批量把赠品删掉 --
      var url = '/api/weshop/cart/delIds/' + oo.stoid + '/' +getApp().globalData.user_id + '/' + ids.join(',');
      getApp().request.delete(url, {});

      cart_zp[list.pid]={};
    }
    //主要判断有没有促销活动
    var is_sele_prom = 0;
    var is_gift_del = 0;

    for (var i = 0; i < list.goods.length; i++) {
      var item = list.goods[i];
      if (item.prom_type == 3 && item.selected && !item.is_gift) {
        is_sele_prom = 1;
        if (map.has(item.prom_id + "")) {
          var ob = map.get(item.prom_id + "");
          ob.num += item.goods_num;
          ob.price += item.goods_num * item.goods_price;
          delete map[item.prom_id + ""];
          map.set(item.prom_id + "", ob);
        } else {
          var ob = {};
          ob.num = item.goods_num;
          ob.price = item.goods_num * item.goods_price;
          if (item.guide_id) {
            ob.guide_id = item.guide_id;
          }
          if (item.guide_type) {
            ob.guide_type = item.guide_type;
          }
          map.set(item.prom_id + "", ob);
        }
      }
      //-- list中不再添加和删除赠品，优化list不再添加赠品，2024-02-01 --
      // if (item.is_gift == 1) {
      //   var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
      //   //getApp().request.delete(url, {});
      //   await getApp().request.promiseDelete(url, {}) // 要用同步让赠品删除
      //   list2.goods.splice(i, 1);
      //   list.goods.splice(i--, 1);
      //   is_gift_del = 1;
      // }
    }
    //--如果没有选中的促销活动的，直接退出 --
    if (!is_sele_prom) {

      //--- 设置单赠品的显示---2024-2-1
      this.setData({
        cart_zp
      })

      //如果有赠品，要重新更新购物车的前台渲染--
      if (is_gift_del) {
        var rq_text = "requestData[" + cindex + "]";
        this.setData({
          [rq_text]: list
        });
      }

      var rq_text2 = "requestData[" + cindex + "].make_up_arr";
      this.setData({
        [rq_text2]: null,
      })

      var gift_text = "requestData[" + cindex + "].send_gift_arr";
      this.setData({
        [gift_text]: null,
      })

      return false;
    }


    //用来判断有没有list大小发生变化
    let is_change_list=0;
    //-- 循环判断活动 --
    for (let p_item of map.entries()) {
      var prom = null;
      //使用缓存，减少接口的调用
      if (th.data.promgoods_map[p_item[0]]) {
        prom = th.data.promgoods_map[p_item[0]];
      } else {

        await getApp().request.promiseGet("/api/weshop/promgoods/get/" + os.stoid + "/" + p_item[0], {}).then(res => {
          if (res.data.code == 0) {
            prom = res.data.data;
          }
        })
      }
      let limit_num = 0
      let user_pre_buynum = 0
      if (prom && prom.limit_num) {
        limit_num = prom.limit_num;
        user_pre_buynum = await this.getUserBuyPromNum_pre(prom.id)
      }

      //如果活动已经结束
      if (!prom || prom.is_end || prom.end_time < ut.gettimestamp()) {
        for (var ii in list.goods) {

          if (item.prom_id == p_item[0] && item.prom_type == 3) {
            // var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
            // getApp().request.delete(url, {});
            th.disInvalid(item);

            var item = list.goods[ii];
            list.goods.splice(ii, 1);
            is_change_list=1;
          }
        }
        continue;
      }

      if (!th.data.promgoods_map[p_item[0]]) th.data.promgoods_map[p_item[0]] = prom;
      //---读取打折的详情---
      var ob = p_item[1];
      var discount = null;

      //看一下是不是多赠品，如果是多赠品
      var promgoods_list = null;
      if (th.data.promgoods_list[p_item[0]]) {
        promgoods_list = th.data.promgoods_list[p_item[0]];
      } else {
        //-- 获取凑单提示 --
        await getApp().request.promiseGet("/api/weshop/promgoodslist/list", {
          data: {
            prom_id: prom.id
          }
        }).then(res => {
          if (res.data.code == 0) {
            promgoods_list = res.data.data;
          }
        })
        if (!promgoods_list) continue;
        th.data.promgoods_list[p_item[0]] = promgoods_list;
      }

      if (!limit_num || user_pre_buynum < limit_num) {
        for (var i in promgoods_list) {
          var item = promgoods_list[i];
          if (item.prom_type == 0) {
            if (ob.price < item.condition) {
              var elem = {
                prom_id: prom.id,
                diff_type: item.prom_type,
                diff: (item.condition - ob.price).toFixed(2),
                content: JSON.parse(item.preferential_type)
              }
              make_up_arr.push(elem);
              break;
            }
          } else {
            if (ob.num < item.condition) {
              var elem = {
                prom_id: prom.id,
                diff_type: item.prom_type,
                diff: (item.condition - ob.num).toFixed(2),
                content: JSON.parse(item.preferential_type)
              }
              make_up_arr.push(elem);
              break;
            }
          }
        }
      } else {
        continue;
      }

      //-- 只有在单赠品的时候，才要进行计算 --
      await getApp().request.promiseGet("/api/weshop/goods/getDiscount", {
        data: {
          price: parseFloat(ob.price).toFixed(2),
          prom_id: p_item[0],
          goods_num: ob.num,
          user_id: getApp().globalData.user_id,
          is_bz: prom.is_bz
        }
      }).then(res => {
        if (res.data.code == 0) discount = res.data.data;
      })

      if (discount) {
        if (!discount.zp_num || parseInt(discount.zp_num) == 0) discount.zp_num = 1;
        //判断一下赠品的模式,如果是多赠品的时候
        if (parseInt(discount.zp_mode) == 1) {

          var can_zp_num = 0;
          var a_limit_num = 0;
          for (let iy in discount.giftsinfo) {
            let item = discount.giftsinfo[iy];

            var c_zp=0;
            if(parseInt(item.limit_num)>0){
              c_zp= parseInt(item.gift_storecount) > parseInt(item.can_num) ? parseInt(item.can_num) : parseInt(item.gift_storecount);
            }else{
              c_zp= parseInt(item.gift_storecount);
            }
            if(c_zp<0) c_zp=0;
            can_zp_num +=c_zp;
          }

          var t_zp_num = parseInt(discount.zp_num) * parseInt(discount.bs);
          if (th.data.duo_zp_num_arr && th.data.duo_zp_num_arr[prom.id]) {
            t_zp_num += th.data.duo_zp_num_arr[prom.id];
          }

          if (can_zp_num >= t_zp_num) {
            var json = {};
            json.prom_id = prom.id;
            json.prom_name = prom.name;
            send_gift_arr.push(json);
            if(!th.data.duo_zp_num_arr) th.data.duo_zp_num_arr={};
            th.data.duo_zp_num_arr[prom.id] = t_zp_num;
          }

        } else {
          //---如果有打折的信息，赠送的信息,赠送的时候要判断是不是限购数量---
          if (discount && discount['goods_id'] && (!discount.limit_num || discount.limit_num >= discount.bs * discount.zp_num) &&
              discount.gift_storecount >= discount.bs * discount.zp_num) {
            //如果这礼品超了情况下
            if (no_gift_arr.indexOf(discount.gift_id) != -1) continue;
            var o = discount.goodsinfo;
            //-- 默认等于1，兼容旧的活动 --

            var newd = {
              goods_id: o.goods_id,
              goods_num: discount.bs * discount.zp_num, //是赠品的翻倍
              pick_id: list.pid,
              user_id: app.globalData.user_id,
              store_id: os.stoid,
              goods_price: 0,
              guide_id: ob.guide_id ? ob.guide_id : 0,
              guide_type: ob.guide_type ? ob.guide_type : 0,
              member_goods_price: 0,
              goods_name: o.goods_name,
              goods_sn: o.goods_sn,
              sku: o.sku,
              is_gift: 1,
              prom_id: p_item[0],
              prom_type: 3,
              selected: 1,
              gift_id: discount.gift_id,
              original_img: th.data.imgUrl + o.original_img
            };

            //list2.goods.push(newd);
            var all_num = 0;
            var all_limit_num = 0;

            for (var i in alllist) {
              var list_item = alllist[i];
              if (list_item.pid == list.pid) continue;
              for (var j in list_item.goods) {
                //如果赠品的ID一样，要进行统计数量
                if (list_item.goods[j].is_gift == 1 && list_item.goods[j].gift_id == newd.gift_id) {
                  all_num += list_item.goods[j].goods_num;
                }
                if (list_item.goods[j].is_gift == 1 && list_item.goods[j].gift_id == newd.gift_id && list_item.goods[j].prom_id == p_item[0]) {
                  all_limit_num += list_item.goods[j].goods_num;
                }

              }
            }

            //-- 赠品的数量超出库存数量和会员的限制,这里是保证所有的赠品部会超出 --
            if (discount.gift_storecount < all_num + newd.goods_num || (discount.limit_num &&  discount.limit_num < all_limit_num + newd.goods_num)) {
              no_gift_arr.push(discount.gift_id);
              //--进入下一个循环 --
              continue;
            }

            var url = "/api/weshop/cart/delGift?store_id=" + newd.store_id + "&user_id=" +
                newd.user_id + "&goods_id=" + newd.goods_id + "&is_gift=1&pick_id=" + newd.pick_id + "&prom_id=" + newd.prom_id
            await getApp().request.promiseDelete(url, {})

            var add_data = null;
            await getApp().request.promisePost("/api/weshop/cart/save", {
              data: newd
            }).then(res => {
              if (res.data.code == 0) {
                add_data = res.data.data;
              }
            })
            if (add_data) {
              newd.id = add_data.id;
              //list.goods.push(newd);
              if(!cart_zp[list.pid])  cart_zp[list.pid]={};
              if(!cart_zp[list.pid].goods) cart_zp[list.pid].goods=[];
              cart_zp[list.pid].goods.push(newd);
            }
          }
        }
      }

    }

    //--- 设置单赠品的显示---2024-2-1
    this.setData({
      cart_zp
    })

    //list大小有变换，才会渲染list
    if(is_change_list) {
      //--更新购物车的前台渲染--
      var rq_text = "requestData[" + cindex + "]";
      this.setData({
        [rq_text]: list
      });
    }

    var diff_text = "requestData[" + cindex + "].make_up_arr";
    //-- 如果有凑单的话 --
    if (make_up_arr.length > 0) {
      this.setData({
        [diff_text]: make_up_arr
      });
    } else {
      this.setData({
        [diff_text]: null
      });
    }

    var gift_text = "requestData[" + cindex + "].send_gift_arr";
    //-- 如果有凑单的话 --
    if (send_gift_arr.length > 0) {
      this.setData({
        [gift_text]: send_gift_arr
      });
    } else {
      this.setData({
        [gift_text]: null
      });
    }

  },



  //优惠促销用户参与次数
  async getUserBuyPromNum_pre(prom_id) {
    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}`;
    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
  },


  async all_check_prom_activity() {
    this.data.duo_zp_num_arr = {};
    //用来存销赠品的--2024-2-1
    let cart_zp=this.data.cart_zp;

    if(cart_zp){
      let ids=[];
      for (const Ky in cart_zp) {
          if(cart_zp[Ky].goods && cart_zp[Ky].goods.length) {
            let ids0 = cart_zp[Ky].goods.map(obj => obj.id);
            ids = [...ids, ...ids0];
          }
      }
      //调用接口把赠品删除
      if(ids.length>0){
        //-- 批量把赠品删掉 --
        var url = '/api/weshop/cart/delIds/' + oo.stoid + '/' + getApp().globalData.user_id + '/' + ids.join(',');
        getApp().request.delete(url, {});
      }
    }
    //要清空一下赠品数组
    cart_zp={};

    for (var i in this.data.requestData) {
      var cindex = i;
      var make_up_arr = new Array();
      var send_gift_arr = new Array();
      var th = this;
      var map = new Map();
      var list = JSON.parse(JSON.stringify(this.data.requestData[cindex]));
      //循环处理活动，看活动商品的数量，用map来出来存储，key为活动id，值是数量

      //-- 所有的购物车的数据，要用拷贝的赖进行计算 --
      var alllist = JSON.parse(JSON.stringify(this.data.requestData));
      //var list2 = alllist[cindex];

      var no_gift_arr = [];

      //主要判断有没有促销活动
      var is_sele_prom = 0;
      var is_gift_del = 0;
      for (var i = 0; i < list.goods.length; i++) {
        var item = list.goods[i];
        if (item.prom_type == 3 && item.selected && !item.is_gift) {
          is_sele_prom = 1;
          if (map.has(item.prom_id + "")) {
            var ob = map.get(item.prom_id + "");
            ob.num += item.goods_num;
            ob.price += item.goods_num * item.goods_price;
            delete map[item.prom_id + ""];
            map.set(item.prom_id + "", ob);
          } else {
            var ob = {};
            ob.num = item.goods_num;
            ob.price = item.goods_num * item.goods_price;
            if (item.guide_id) {
              ob.guide_id = item.guide_id;
            }
            if (item.guide_type) {
              ob.guide_type = item.guide_type;
            }
            map.set(item.prom_id + "", ob);
          }
        }

        //-- list中不再添加和删除赠品，优化list不再添加赠品，2024-02-01 --
        // if (item.is_gift == 1) {
        //   var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
        //   //getApp().request.delete(url, {});
        //   await getApp().request.promiseDelete(url, {}) // 要用同步让赠品删除
        //   list2.goods.splice(i, 1);
        //   list.goods.splice(i--, 1);
        //   is_gift_del = 1;
        // }
      }
      //--如果没有选中的促销活动的，直接退出 --
      if (!is_sele_prom) {
        //如果有赠品，要重新更新购物车的前台渲，list中不再显示--
        // if (is_gift_del) {
        //   var rq_text = "requestData[" + cindex + "]";
        //   this.setData({
        //     [rq_text]: list
        //   });
        // }
        //--- 设置单赠品的显示---2024-2-1
        this.setData({
          cart_zp
        })
        var rq_text2 = "requestData[" + cindex + "].make_up_arr";
        this.setData({
          [rq_text2]: null,
        })

        var gift_text = "requestData[" + cindex + "].send_gift_arr";
        this.setData({
          [gift_text]: null,
        })
        continue;
      }

      //用来判断有没有list大小发生变化
      let is_change_list=0;
      //-- 循环判断活动 --
      for (let p_item of map.entries()) {
        var prom = null;
        //使用缓存，减少接口的调用
        if (th.data.promgoods_map[p_item[0]]) {
          prom = th.data.promgoods_map[p_item[0]];
        } else {

          //使用缓存，不在调用接口
          if(!prom && th.data.yhcx_act_map && th.data.yhcx_act_map[p_item[0]] ){
            prom=th.data.yhcx_act_map[p_item[0]];
          }
          if(!prom){
            await getApp().request.promiseGet("/api/weshop/promgoods/get/" + os.stoid + "/" + p_item[0], {}).then(res => {
              if (res.data.code == 0) {
                prom = res.data.data;
              }
            })
          }


        }
        let limit_num = 0
        let user_pre_buynum = 0
        if (prom && prom.limit_num) {
          limit_num = prom.limit_num;
          user_pre_buynum = await this.getUserBuyPromNum_pre(prom.id)
        }
        //如果活动已经结束
        if (!prom || prom.is_end || prom.end_time < ut.gettimestamp()) {

          for (var ii in list.goods) {

            if (item.prom_id == p_item[0] && item.prom_type == 3) {
              // var url = '/api/weshop/cart/del/' + oo.stoid + '/' + item.id;
              // getApp().request.delete(url, {});
              th.disInvalid(item);

              var item = list.goods[ii];
              list.goods.splice(ii, 1);
              is_change_list=1;
            }
          }
          continue;
        }

        if (!th.data.promgoods_map[p_item[0]]) th.data.promgoods_map[p_item[0]] = prom;
        //---读取打折的详情---
        var ob = p_item[1];
        var discount = null;

        //看一下是不是多赠品，如果是多赠品
        var promgoods_list = null;
        if (th.data.promgoods_list[p_item[0]]) {
          promgoods_list = th.data.promgoods_list[p_item[0]];
        } else {
          //-- 获取凑单提示 --
          await getApp().request.promiseGet("/api/weshop/promgoodslist/list", {
            data: {
              prom_id: prom.id
            }
          }).then(res => {
            if (res.data.code == 0) {
              promgoods_list = res.data.data;
            }
          })
          if (!promgoods_list) continue;
          th.data.promgoods_list[p_item[0]] = promgoods_list;
        }

        if (!limit_num || user_pre_buynum < limit_num) {
          for (var i in promgoods_list) {
            var item = promgoods_list[i];
            if (item.prom_type == 0) {
              if (ob.price < item.condition) {
                var elem = {
                  prom_id: prom.id,
                  diff_type: item.prom_type,
                  diff: (item.condition - ob.price).toFixed(2),
                  content: JSON.parse(item.preferential_type)
                }
                make_up_arr.push(elem);
                break;
              }
            } else {
              if (ob.num < item.condition) {
                var elem = {
                  prom_id: prom.id,
                  diff_type: item.prom_type,
                  diff: (item.condition - ob.num).toFixed(2),
                  content: JSON.parse(item.preferential_type)
                }
                make_up_arr.push(elem);
                break;
              }
            }
          }
        }

        //-- 只有在单赠品的时候，才要进行计算 --
        await getApp().request.promiseGet("/api/weshop/goods/getDiscount", {
          data: {
            price: parseFloat(ob.price).toFixed(2),
            prom_id: p_item[0],
            goods_num: ob.num,
            user_id: getApp().globalData.user_id,
            is_bz: prom.is_bz
          }
        }).then(res => {
          if (res.data.code == 0) discount = res.data.data;
        })

        if (discount) {

          if (!discount.zp_num || parseInt(discount.zp_num) == 0) discount.zp_num = 1;
          //-- 判断一下赠品的模式,如果是多赠品的模式 --
          if (parseInt(discount.zp_mode) == 1) {

            var can_zp_num = 0;
            var a_limit_num = 0;
            for (let iy in discount.giftsinfo) {
              let item = discount.giftsinfo[iy];
              var c_zp=0;
              if(parseInt(item.limit_num)>0) {
                c_zp= parseInt(item.gift_storecount) > parseInt(item.can_num) ? parseInt(item.can_num) : parseInt(item.gift_storecount);
              }else{
                c_zp= parseInt(item.gift_storecount)
              }
              if(c_zp<0) c_zp=0;
              can_zp_num +=c_zp;
            }

            var t_zp_num = parseInt(discount.zp_num) * parseInt(discount.bs);
            if (th.data.duo_zp_num_arr[prom.id]) {
              t_zp_num += th.data.duo_zp_num_arr[prom.id];
            }

            if (can_zp_num >= t_zp_num) {
              var json = {};
              json.prom_id = prom.id;
              json.prom_name = prom.name;
              send_gift_arr.push(json);
              th.data.duo_zp_num_arr[prom.id] = t_zp_num;
            }

          } else {
            //---如果有打折的信息，赠送的信息,赠送的时候要判断是不是限购数量,因为增加了限购数量不限的情况---
            if (discount && discount['goods_id'] && (!discount.limit_num || discount.limit_num >= discount.bs * discount.zp_num) &&
                discount.gift_storecount >= discount.bs * discount.zp_num) {
              //如果这礼品超了情况下
              if (no_gift_arr.indexOf(discount.gift_id) != -1) continue;
              var o = discount.goodsinfo;
              //-- 默认等于1，兼容旧的活动 --

              var newd = {
                goods_id: o.goods_id,
                goods_num: discount.bs * discount.zp_num, //是赠品的翻倍
                pick_id: list.pid,
                user_id: app.globalData.user_id,
                store_id: os.stoid,
                goods_price: 0,
                guide_id: ob.guide_id ? ob.guide_id : 0,
                guide_type: ob.guide_type ? ob.guide_type : 0,
                member_goods_price: 0,
                goods_name: o.goods_name,
                goods_sn: o.goods_sn,
                sku: o.sku,
                is_gift: 1,
                prom_id: p_item[0],
                prom_type: 3,
                selected: 1,
                gift_id: discount.gift_id,
                original_img: th.data.imgUrl + o.original_img
              };

              //list2.goods.push(newd);
              var all_num = 0;
              var all_limit_num = 0;

              for (var i in alllist) {
                var list_item = alllist[i];
                if (list_item.pid == list.pid) continue;
                for (var j in list_item.goods) {
                  //如果赠品的ID一样，要进行统计数量
                  if (list_item.goods[j].is_gift == 1 && list_item.goods[j].gift_id == newd.gift_id) {
                    all_num += list_item.goods[j].goods_num;
                  }
                  if (list_item.goods[j].is_gift == 1 && list_item.goods[j].gift_id == newd.gift_id && list_item.goods[j].prom_id == p_item[0]) {
                    all_limit_num += list_item.goods[j].goods_num;
                  }

                }
              }
              //-- 赠品的数量超出库存数量和会员的限制,这里是保证所有的赠品部会超出 --
              if (discount.gift_storecount < all_num + newd.goods_num ||  (discount.limit_num && discount.limit_num < all_limit_num + newd.goods_num)) {
                no_gift_arr.push(discount.gift_id);
                //--进入下一个循环 --
                continue;
              }


              var url = "/api/weshop/cart/delGift?store_id=" + newd.store_id + "&user_id=" +
                  newd.user_id + "&goods_id=" + newd.goods_id + "&is_gift=1&pick_id=" + newd.pick_id + "&prom_id=" + newd.prom_id
              await getApp().request.promiseDelete(url, {})

              var add_data = null;
              await getApp().request.promisePost("/api/weshop/cart/save", {
                data: newd
              }).then(res => {
                if (res.data.code == 0) {
                  add_data = res.data.data;
                }
              })
              if (add_data) {
                newd.id = add_data.id;
                //list.goods.push(newd);
                if(!cart_zp[list.pid])  cart_zp[list.pid]={};
                if(!cart_zp[list.pid].goods) cart_zp[list.pid].goods=[];
                cart_zp[list.pid].goods.push(newd);
              }
            }
          }
        }
      }

      //--- 设置单赠品的显示---2024-2-1
      this.setData({
        cart_zp
      })

      //list大小有变换，才会渲染list
      if(is_change_list) {
        //--更新购物车的前台渲染--
        var rq_text = "requestData[" + cindex + "]";
        this.setData({
          [rq_text]: list
        });
      }

      var diff_text = "requestData[" + cindex + "].make_up_arr";
      //-- 如果有凑单的话 --
      if (make_up_arr.length > 0) {
        this.setData({
          [diff_text]: make_up_arr
        });
      } else {
        this.setData({
          [diff_text]: null
        });
      }

      var gift_text = "requestData[" + cindex + "].send_gift_arr";
      //-- 如果有凑单的话 --
      if (send_gift_arr.length > 0) {
        this.setData({
          [gift_text]: send_gift_arr
        });
      } else {
        this.setData({
          [gift_text]: null
        });
      }


    }
  },



  //去凑单
  go_cou_dang: function (e) {
    var prom_id = e.currentTarget.dataset.prom_id;
    var url = "/pages/goods/goodsList/goodsList?prom_type=3&prom_id=" + prom_id;
    getApp().goto(url);
  },

  //导航跳转
  nav_goto: function (e) {
    var url = e.currentTarget.dataset.url;
    if (!url || url == '') return;
    if (url[0] != '/') url = '/' + url;
    getApp().goto(url);
  },

  refresh_input: function () {
    this.data.btn_click = 0;
  },

  imageLoad: function (e) {
    var imgwidth = e.detail.width;
    var imgheight = e.detail.height;
    //宽高比
    var ratio = imgwidth / imgheight;
    //计算的高度值
    var viewHeight = 715 / ratio;
    var hei = this.data.max_sw_height;

    if (hei < viewHeight) {
      this.setData({
        max_sw_height: viewHeight
      });
    }
  },

  go_url(e) {
    var url = e.currentTarget.dataset.url;
    getApp().goto(url);
  },

  //跳转到商品
  go_gd: function (e) {
    var user_id = getApp().globalData.user_id;
    if (!user_id) user_id = 0;
    var gd = e.currentTarget.dataset.gd;
    var item2 = e.currentTarget.dataset.item;

    var good_url = "/pages/goods/goodsInfo/goodsInfo?goods_id=" + gd;

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

    // var url = "/api/weshop/activitylist/getGoodActInfo";
    // var req_data = {
    //   store_id: os.stoid,
    //   goodsidlist: gd,
    //   is_detail: 1,
    //   user_id: user_id
    // };
    var url = '/api/weshop/activitylist/listGoodActInfo2New';
    var req_d = {
      "store_id": os.stoid,
      "goods_id": gd,
      "user_id": user_id,
    }

    //获取秒杀的多规格
    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) {
          var item =arr2[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);
      }
    })
  },

  //赠品提示
  show_gift_toast: function () {
    wx.showToast({
      title: "请点击结算至提交订单页选择赠品",
      icon: 'none',
      duration: 2000
    });
  },

  //-- 开始显示活动的弹出 --
  switch_cx_group: function (e) {
    var idx = e.currentTarget.dataset.index;
    var gd_key = e.currentTarget.dataset.gd_key;
    this.data.sele_cx_group_cidx = idx;
    this.data.cx_group_gd_key = gd_key;
    //-- 获取到--
    var cx_prom_group = this.data.requestData[idx].show_can_cx[gd_key].act_arr;

    var cx_arr = [];
    var find_sele = 0;
    for (var h = 0; h < cx_prom_group.length; h++) {
      //-- 看有没有选中的活动 --
      if (cx_prom_group[h].sele) {
        find_sele = 1;
        cx_prom_group[h].act.sele = 1;
      } else {
        cx_prom_group[h].act.sele = 0;
      }
      cx_arr.push(cx_prom_group[h].act);
    }
    //-- 如果没有，就默认第一个为选中 --
    //-- if(!find_sele) cx_arr[0].sele=1; --
    var cp_arr = JSON.parse(JSON.stringify(cx_arr));
    var pro_pop = this.selectComponent("#pro_pop"); //组件的id
    pro_pop.set_init(1, cp_arr, 1);
  },

  //--- 选择回来时候的选择 ---
  sure_cx_group: function (e) {
    var th = this;
    var sele_prom_type=e.detail.sele_prom_type;
    //-- 获取到当前的 show_can_cx--
    var idx = this.data.sele_cx_group_cidx;
    var gd_key = this.data.cx_group_gd_key;
    var cx_prom_group = this.data.requestData[idx].show_can_cx[gd_key].act_arr;

    var fir_sele = 0;
    for (var dx = 0; dx < cx_prom_group.length; dx++) {
      if (cx_prom_group[dx].sele) fir_sele = dx;
      if (cx_prom_group[dx].prom_type!= sele_prom_type) cx_prom_group[dx].sele = 0;
      else cx_prom_group[dx].sele = 1;
    }

    let the_rs={code:0};
    // -- 判断 --
    this.cx_check_ok2(async function (the_rs) {
      if (the_rs.code == 0) {
        th.data.change_act = 1;

        th.doCheckAll(async function () {
          th.data.duo_zp_num_arr={};
          for (var i in th.data.requestData) {
            await th.check_prom_activity(i)
          }
        });

      } else {
        wx.showToast({
          title: the_rs.msg,
          icon: 'none',
          duration: 2500
        });

        for (var dx = 0; dx < cx_prom_group.length; dx++) {
          if (dx != fir_sele) cx_prom_group[dx].sele = 0;
          else cx_prom_group[dx].sele = 1;
        }

      }
    })

  },

  //--- 在点击商品和或者门店的时候调用,c_idx是购物车下标序号---
  async cx_check_ok(c_idx, sele_arr, func) {

    var th = this;
    var car = JSON.parse(JSON.stringify(this.data.requestData));
    var item = car[c_idx].goods, is_s_sele = 1;

    for (var i = 0; i < item.length; i++) {
      item[i].goods_price = item[i].init_goods_price;
    }

    var is_has_other = 0;
    for (var ii = 0; ii < car.length; ii++) {
      if (c_idx == ii) continue;
      if (car[ii].show_can_cx && Object.keys(car[ii].show_can_cx).length) {
        //is_has_other = 1;
        break;
      }
    }

    //其他门店并没有选择
    if (!is_has_other) {
      func({
        'code': 0,
        'msg': '成功'
      });
      return false;
    }
    //-- 让选择进入对应 --
    for (var i = 0; i < item.length; i++) {
        if (sele_arr.hasOwnProperty(i)) {
          item[i].selected = sele_arr[i];
        }
    }

    //-- 先批量判断一下活动的类型，同时要同步跟新 --
    m_cx.cart_cx_group(this, item, car[c_idx], 0, 0, (show_can_cx) => {
      car[c_idx].show_can_cx = show_can_cx;
      th.cx_check_ok2(func, car);
    });

  },

  //--- 在点击商品和或者门店的时候调用,这个可以在活动切换的时候调用，也可以被单个选择调用---
  async cx_check_ok2(func, car) {

    //如果购物车没有带入，要进行赋值
    if (!car) {
      car = JSON.parse(JSON.stringify(this.data.requestData));
    }

    var nei_in_zhact_gdmap = {};
    var nei_in_zhact = {};
    var nei_in_yhact = {};
    for (var i = 0; i < car.length; i++) {
      var show_can_cx = car[i].show_can_cx;
      for (var j in show_can_cx) {
        var sele_act = show_can_cx[j].act_arr.find(function (m) {
          return m.sele == 1;
        })

        if (!sele_act) continue;
        var pid = sele_act['prom_id'];
        if (sele_act['prom_type'] == 3) {
          if (!nei_in_yhact[pid]) nei_in_yhact[pid] = 0;
          nei_in_yhact[pid]++;
        }
        if (sele_act['prom_type'] == 7) {
          if (!nei_in_zhact[pid]) nei_in_zhact[pid] = 0;
          nei_in_zhact[pid] += sele_act['act_num'];
        }
        var in_zhact_gdmap1 = sele_act['in_zhact_gdmap'];
        for (var vg in in_zhact_gdmap1) {
          if (!nei_in_zhact_gdmap[vg]) nei_in_zhact_gdmap[vg] = 0;
          nei_in_zhact_gdmap[vg] += in_zhact_gdmap1[vg];
        }
      }
    }

    //-- 判断优惠促销是不是超出限购 --
    if (nei_in_yhact && Object.keys(nei_in_yhact).length) {
      for (var ky0 in nei_in_yhact) {
        var num = nei_in_yhact[ky0];

        var fd = null;
        var fd_res = await getApp().request.promiseGet('/api/weshop/promgoods/get/' + os.stoid + '/' + ky0, {})
        if (fd_res && fd_res.data.code == 0) {
          fd = fd_res.data.data;
        }
        if (fd && fd['limit_num'] > 0 && num > fd['limit_num']) {
          func({
            'code': -1,
            'msg': '超出优惠促销活动的限购'
          });
          return false;
        }
      }
    }

    //-- 判断组合促销是不是超出活动总数量 --
    if (nei_in_zhact && Object.keys(nei_in_zhact).length) {
      for (var ky in nei_in_zhact) {

        var num0 = nei_in_zhact[ky];
        var zh = this.data.zuhe_map[ky];
        var buyed = 0;

        //获取已经购买了多少件
        var z_url = "/api/weshop/ordergoods/getUserBuyPromNum?store_id=" + os.stoid + "user_id=" + getApp().globalData.user_id + "prom_type=7&prom_id=" + ky;
        var zbuy = await getApp().request.promiseGet(z_url, {});
        if (zbuy && zbuy.data.code == 0) {
          buyed = zbuy.data.data.userbuynum;
        }
        if (zh['zh_num'] > 0 && zh['zh_buy_num'] + num0 > zh['zh_num']) {
          // func({
          //   'code': -1,
          //   'msg': '超出组合购活动总数量'
          // });
          // return false;
        }
      }
    }

    //-- 判断组合促销是不是超出活动总数量 --
    if (nei_in_zhact_gdmap && Object.keys(nei_in_zhact_gdmap).length) {
      for (var key in nei_in_zhact_gdmap) {

        var num1 = nei_in_zhact_gdmap[key];
        var key_a = key.split('.');
        var gid = key_a[0];
        var pid = key_a[1];

        //-- 商品的限购 --
        var promgoodsbuynum = 0;
        var rq = {
          'store_id': os.stoid,
          'user_id': getApp().globalData.user_id,
          'goods_id': gid,
          'prom_type': 7,
          'prom_id': pid, isnew:1
        };

        var res = await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
          data: rq
        });
        if (res && res.data.code == 0) {
          promgoodsbuynum = res.data.data.promgoodsbuynum;
        }

        var gdlist_arr = this.data.zuhe_map_good[pid];
        var gdlist = gdlist_arr.find(function (e) {
          return e.goods_id == gid;
        })
        if (gdlist['buyqty'] > 0 && num1 + promgoodsbuynum > gdlist['buyqty']) {
          // func({
          //   'code': -1,
          //   'msg': '超出组合购商品的限购'
          // });
          // return false;
        }
      }
    }
    
    func({
      'code': 0,
      'msg': '成功'
    })
  },

  //-- 判断一下有没有满足优惠促销的条件 --
  check_can_yh_pro:async function (i_arr){
    var map={};
    for (let i = 0; i < i_arr.length; i++) {
        var item=i_arr[i];
        if(item.is_gift) continue;
        if(item.prom_type!=3) continue;

        if (map[item.prom_id]) {
          var ob = map[item.prom_id];
          //-- 避免同一件商品重复添加 --
          if (ob.goods && ob.goods.length) {
            var fid = ob.goods.findIndex(function (e) {
              e.goods_id == item.goods_id
            })
            if (fid > -1) continue;
          }
          ob.price += item.goods_price * item.goods_num;
          ob.goods_num += item.goods_num;
          ob.goods.push({ goods_id: item.goods_id, goods_price: item.goods_price, goods_num: item.goods_num });
        } else {
          var prom = null;
          await getApp().request.promiseGet("/api/weshop/promgoods/get/" + os.stoid + "/" + item.prom_id, {}).then(res => {
            if (res.data.code == 0) {
              prom = res.data.data;
            }
          })

          var ob = {};
          ob.is_bz = prom.is_bz;
          ob.prom_id=item.prom_id;
          ob.price = item.goods_price * item.goods_num;
          ob.goods_num = item.goods_num;
          ob.goods = new Array();
          ob.goods.push({ goods_id: item.goods_id, goods_price: item.goods_price, goods_num: item.goods_num });
          map[item.prom_id] = ob;
        }
    }

    var res=null;
    for (const mapKey in map) {
      var item_map=map[mapKey];
      //开始判断能不能参与优惠
      res=await getApp().request.promiseGet("/api/weshop/goods/getDiscount", {
        data: {
          price: parseFloat(item_map.price).toFixed(2), prom_id: item_map.prom_id,
          goods_num: item_map.goods_num, user_id: getApp().globalData.user_id,
          is_bz: item_map.is_bz
        }
      })
      if (res.data.code == 0 && res.data.data.condition) {

          for (let i = 0; i < i_arr.length; i++) {
            var item_g = i_arr[i];
            if (item_g.is_gift) continue;

            //-- 避免同一件商品重复添加 --
            if (item_map.goods && item_map.goods.length) {
              var fid = item_map.goods.findIndex(function (e) {
                e.goods_id == item_g.goods_id
              })
              if (fid > -1) continue;
            }
            //判断商品是可以参与优惠促销的
            i_arr[i].can_yh=1;
          }

      }

    }
    


  },

  async go_card(e){
    var gid=e.currentTarget.dataset.gid;
    var rurl = '/api/weshop/activitylist/listGoodActInfo2New';
    var req_d = {
      "store_id": app.globalData.setting.stoid,
      "goods_id": gid,
      "user_id": getApp().globalData.user_id,
      "goods_type":1
    }
    var res= await getApp().request.promiseGet(rurl, {data: req_d});

    var url = "/packageH/pages/goodsInfo/goodsInfo?goods_id=" + gid;
    if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
      var arr = res.data.data;
      let times = new Date().getTime();
      //-- 预热也要计算 --
      var arr2 = arr.filter(function (e) {
        return e.s_time < ut.gettimestamp() || (e.warm_uptime && e.warm_uptime < ut.gettimestamp())
      })
      if(arr2.length==1) {
        switch(arr2[0].prom_type){
          case 1:
            url+="&prom_type=1&prom_id="+arr2[0].act_id;
            break;
          case 2:
            url="/packageG/pages/group_buy/goodsInfo/goodsInfo?goods_id="+gid+"&prom_id="+arr2[0].act_id;
            break;
          case 6:
            url = `/packageA/pages/serviceCard_pd/goodsInfo/goodsInfo?goods_id=${gid}&prom_type=${arr2[0].prom_type}&prom_id=${arr2[0].act_id}`;
            break;
          case 8:
            url = `/packageC/pages/presell/cardInfo/goodsInfo?goods_id=${gid}&prom_id=${arr2[0].act_id}`;
            break;
        }
      }

    }

    app.goto(url);
  },

  //-- 在结算的时候，判断有没有超出限购 --
  get_buy_num_ser_2: async function (goods_id,prom_type,prom_id) {
    var th = this, user_id = getApp().globalData.user_id;
    //----获取活动购买数----
    return await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum", {
      data: {
        store_id: os.stoid,
        user_id: user_id,
        card_id: goods_id,
        prom_type: prom_type,
        prom_id: prom_id,
        isnew:1
      },
    });
  },


  //-- 图片失败，默认图片,赠品图片的处理 --
  bind_bnerr_gift: function (e) {
    var pid = e.target.dataset.pid;
    var idxx = e.target.dataset.idxx;
    var cart_zp=this.data.cart_zp;
    cart_zp[pid].goods[idxx].original_img= oo.imghost + "/miniapp/images/default_g_img.png";
    this.setData({
      cart_zp
    })
  },



});