// components/add_purchase/add_purchase.js
var s = getApp(),
  ut = require("../../utils/util"),
  i = s.request,
  rq = i,
  oo = s.globalData,
  o = s.globalData.setting,
  os = o;
let self = null;
var wxlog = require("../../utils/wxlog.js");
var w_time = null;
var timer_get = null;
var t_time = null;
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  lifetimes: {
    // attached: function () {
    //   // this.clearTime()
    //   console.error('加购组件');
    //   self = this
    //   // 在组件实例进入页面节点树时执行
    //   let ee = this, that = ee, th = ee;
    //   //先获取一下导购的门店
    //   th.check_guide(() => {
    //     th.get_user_store();
    //   })
    //   //----获取系统参数-----
    //   getApp().getConfig2(function (e) {
    //     ee.setData({
    //       bconfig: e,
    //       sales_rules: e.sales_rules,
    //     });
    //     th.wait_for_store_config();
    //     if (e.categoryset.indexOf("," + 1 + ",") != -1) {
    //       ee.setData({
    //         is_show_pl: 1
    //       });
    //     }
    //     if (e.categoryset.indexOf("," + 3 + ",") != -1) {
    //       ee.setData({
    //         is_show_pp: 1
    //       });
    //     }
    //     if (e.categoryset.indexOf("," + 2 + ",") != -1) {
    //       ee.setData({
    //         is_show_gb: 1
    //       });
    //     }
    //     console.log('获取系统参数');
    //     console.log(e);
    //     var json_d = JSON.parse(e.switch_list);
    //     ee.setData({
    //       store_config: e,
    //       sys_switch: json_d,
    //       is_closecoupon: json_d.is_closecoupon,
    //       is_newsales_rules: json_d.is_newsales_rules,
    //       is_retail_price: json_d.is_retail_price || 0,
    //       appoint_pick_keyid: json_d.appoint_pick_keyid,
    //       // goods_bottomconent:e.goods_bottomconent
    //     });

    //     //判断商品详情要有东西
    //     // if (e && e.goods_bottomconent) {
    //     //   //商品详情广告----
    //     //   a.wxParse("goodInfo_ad", "html", ut.format_content(e.goods_bottomconent), ee, 6);
    //     //   common.wxParseAddFullImageUrl(ee, "goodInfo_ad");
    //     //   //-------
    //     // }

    //     //------几人评价-------
    //     //n.init(th, "", "comments");

    //     // th.requestCardNum(), 
    //     wx.pageScrollTo && th.setData({
    //       supportPageScroll: !0
    //     });

    //     //计算等级价相关
    //     var swithc_list = e.switch_list;
    //     var sw_arr = JSON.parse(swithc_list);
    //     console.log('plus-111')
    //     //---如果后台又开等级卡的开关---
    //     ut.get_plus_name_price(sw_arr, th);

    //   }, 1);
    // },

  },
  /**
   * 组件的初始数据
   */
  data: {
    add_cart_show: false, //是否显示
    iurl: getApp().globalData.setting.imghost,
    prom_price: null,
    sele_g: null,
    gid: '',
    prom_type: '',
    prom_id: '',
    goodsInputNum: 1,
    def_pick_store: null, // 默认的门店
    openSpecModal_ind: 1,
    goods_type: 0,
    iscart: 0, //是否从购物车过来的
    cx_prom_group: [], //促销活动，用于显示和判断默认要用什么促销活动
    //门店相关
    ismend: 0,
    only_pk: null,
    stoid: o.stoid,
    is_get_local_ok: 0, //获取坐标是否完成
    def_pickpu_list: null,
    more_store: 0, //选择门店
    sort_store: 0, //门店分类
    choice_sort_store: 0, //选择分类门店
    sec_pick_index: 0, //第二级门店选择ID
    fir_pick_index: 0, //第一级门店选择ID
    all_pick_list: null, //所有的门店先记录起来
    fir_def_store: null, //客户默认的门店的
    keyword: '', //门店搜索
    is_no_new: 1,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    closeSpecModal() {
      this.clearTime()
      this.setData({
        add_cart_show: false
      })

      this.triggerEvent('hide_add_purchase', {})
    },
    clearTime() {
      if (timer_get) {
        clearInterval(timer_get);
      }
      if (w_time) {
        clearInterval(w_time);
      }
      if (t_time) {
        clearInterval(t_time);
      }

    },
    previewImage(e) {
      // this.data.show_prew_img = 1;
      getApp().pre_img(this.data.sele_g.original_img);
    },
    initbef: function () {
      // this.clearTime()
      console.error('加购组件');
      self = this
      // 在组件实例进入页面节点树时执行
      let ee = this, that = ee, th = ee;
      //先获取一下导购的门店
      th.check_guide(() => {
        th.get_user_store();
      })
      //----获取系统参数-----
      getApp().getConfig2(function (e) {
        ee.setData({
          bconfig: e,
          sales_rules: e.sales_rules,
        });
        th.wait_for_store_config();
        if (e.categoryset.indexOf("," + 1 + ",") != -1) {
          ee.setData({
            is_show_pl: 1
          });
        }
        if (e.categoryset.indexOf("," + 3 + ",") != -1) {
          ee.setData({
            is_show_pp: 1
          });
        }
        if (e.categoryset.indexOf("," + 2 + ",") != -1) {
          ee.setData({
            is_show_gb: 1
          });
        }
        console.log('获取系统参数');
        console.log(e);
        var json_d = JSON.parse(e.switch_list);
        ee.setData({
          store_config: e,
          sys_switch: json_d,
          is_closecoupon: json_d.is_closecoupon,
          is_newsales_rules: json_d.is_newsales_rules,
          is_retail_price: json_d.is_retail_price || 0,
          appoint_pick_keyid: json_d.appoint_pick_keyid,
          // goods_bottomconent:e.goods_bottomconent
        });

        //判断商品详情要有东西
        // if (e && e.goods_bottomconent) {
        //   //商品详情广告----
        //   a.wxParse("goodInfo_ad", "html", ut.format_content(e.goods_bottomconent), ee, 6);
        //   common.wxParseAddFullImageUrl(ee, "goodInfo_ad");
        //   //-------
        // }

        //------几人评价-------
        //n.init(th, "", "comments");

        // th.requestCardNum(), 
        wx.pageScrollTo && th.setData({
          supportPageScroll: !0
        });

        //计算等级价相关
        var swithc_list = e.switch_list;
        var sw_arr = JSON.parse(swithc_list);
        console.log('plus-111')
        //---如果后台又开等级卡的开关---
        ut.get_plus_name_price(sw_arr, th);

      }, 1);
    },
    init(gid, prom_type, prom_id, goods_type = 0, iscart = 0, cartid = 0) {
      this.initbef()
      // this.clearTime()
      //--先判断会员状态-- 
      var user_info = getApp().globalData.userInfo;
      if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
        wx.showModal({
          title: '提示',
          content: '你还没有登录',
          confirmText: '去登录',
          success(res) {

            if (res.confirm) {
              wx.navigateTo({
                url: '/packageE/pages/togoin/togoin',
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        return false;
      }


      if (!gid) {
        wx.showToast({
          title: '商品信息不对',
          icon: 'none'
        })
        return
      }
      this.setData({
        gid,
        prom_id,
        prom_type,
        goods_type,
        add_cart_show: true,
        goodsInputNum: 1,
        iscart,
        cartid
      })
      if (goods_type == 1) {
        this.get_ser_info()
      } else {
        this.get_goods_info()
      }

    },
    //获取服务详情 
    get_ser_info() {
      let i = getApp().request;
      let gid = this.data.gid
      let ee = this;
      let that = this
      let th = this;
      i.get("/api/weshop/serviceCard/get/" + o.stoid + "/" + ee.data.gid, {
        failRollback: !0,
        success: function (t) {
          if (t.data.code == 0) {
            // console.log('GET pic and video');
            if (t.data.data.listServiceItem) {
              that.setData({
                listServiceItem: t.data.data.listServiceItem,
              });
            };
            that.setData({
              'sele_g.goods_name': t.data.data.serviceName,
              'sele_g.shop_price': t.data.data.money,
              'sele_g.show_price': t.data.data.show_price,
              'sele_g.validDays': t.data.data.validDays,
              'sele_g.serviceContent': t.data.data.serviceContent,
              'sele_g.image_url': t.data.data.imgUrl,
              'sele_g.original_img': that.data.iurl + t.data.data.imgUrl,
              'sele_g.goods_id': t.data.data.id,
              'sele_g.id': t.data.data.id,
              'sele_g.sales_sum': t.data.data.sales_sum,
              'sele_g.storageId': t.data.data.storageId,
              'sele_g.service_sn': t.data.data.serviceSn,
              'sele_g.listServiceVideos': t.data.data.listServiceVideos,

              'data.goods_name': t.data.data.serviceName,
              'data.shop_price': t.data.data.money,
              'data.show_price': t.data.data.show_price,
              'data.validDays': t.data.data.validDays,
              'data.serviceContent': t.data.data.serviceContent,
              'data.image_url': t.data.data.imgUrl,
              'data.original_img': that.data.iurl + t.data.data.imgUrl,
              'data.goods_id': t.data.data.id,
              'data.id': t.data.data.id,
              'data.sales_sum': t.data.data.sales_sum,
              'data.storageId': t.data.data.storageId,
              'data.service_sn': t.data.data.serviceSn,
              'data.listServiceVideos': t.data.data.listServiceVideos,
            });

            // that.getTaohe();
            // ----> 秒杀
            let prom_type = th.data.prom_type;

            let goods_id = th.data.goods_id;
            if (!goods_id) goods_id = th.data.sele_g.goods_id;

            if (prom_type) { // 进入商品详情页地址传参有带goods_id、prom_type、prom_id参数, 即从秒杀入口进入
              let prom_id = th.data.prom_id;
              // 检查活动是否开始
              th.ser_check_prom(goods_id, prom_type, prom_id);

            } else { // 从非秒杀入口进入,地址不带prom_type、prom_id参数
              getApp().request.promiseGet('/api/weshop/activitylist/listGoodActInfo2', {
                data: {
                  store_id: os.stoid,
                  goods_id: goods_id,
                  goods_type: 1,
                  user_id: oo.user_id,
                }
              }).then(res => {
                if (res.data.code == 0) {
                  let result = res.data.data;
                  let resLength = result.length;
                  if (resLength == 1) { // 如果数组长度为1，则直接显示当前活动
                    let goods_id = th.data.gid;
                    let prom_type = result[0].prom_type;
                    let prom_id = result[0].act_id;
                    th.setData({
                      prom_type: prom_type,
                      prom_id: prom_id,
                    });
                    // 检查活动是否开始
                    th.ser_check_prom(goods_id, prom_type, prom_id);
                  } else if (resLength > 1) { //如果数组长度大于1，表示当前商品参加多个活动，以列表形式显示多活动
                    th.setData({
                      actList: res.data.data,
                    });
                  };

                } else {
                  th.setData({
                    actList: res.data.data,
                  });
                }
              });
            };

            // console.log('0xxxxx999999', t.data.data);
            //-----商品详情---
            //if(!t.data.data.serviceContent) t.data.data.serviceContent="  ";
            //a.wxParse("content", "html", ut.format_content(t.data.data.serviceContent), ee, 6);
            //e.wxParseAddFullImageUrl(ee, "content");
            // getApp().deal_iframe(a,e,'content',t.data.data.serviceContent,ee);

            //获取重表
            getApp().promiseGet("/api/weshop/serviceItem/list", {
              data: { store_id: o.stoid, service_id: t.data.data.id }
            }).then(res => {
              if (res.data.code == 0) {
                var list = res.data.data;
                that.setData({ service_list: list })
              }
            })

          } else {
            wx.showModal({
              title: t.data.msg,
              showCancel: !1,
              complete: function () {
                wx.navigateBack();
              }
            });
          };
        }
      });

    },
    get_normal(gid) {
      this.setData({
        prom_type: 0,
        isshow: 1,
      });
      if (this.data.goods_type != 1) {

        this.get_sku(os.stoid, this.data.data, gid);
      }

      this.get_sto();
      if (!this.data.data.whsle_id)
        this.check_is_youhui(gid);
      this.data.is_normal = 1;
    },
    //获取商品详情
    get_goods_info() {

      let i = getApp().request;
      let gid = this.data.gid
      let ee = this;
      i.get("/api/weshop/goods/get/" + getApp().globalData.setting.stoid + "/" + this.data.gid, {
        failRollback: !0,
        success: (t) => {
          console.log(t);
          // t.data.data.prom_type=0
          if (t.data.code == 0) {
            // if (t.data.data && t.data.data.prom_type == 4) {
            //   if (ee.data.prom_type4 == 1) {
            //     t.data.data.prom_type = 0
            //   }
            // }
            if (t.data.data.is_on_sale != 1) {
              wx.showToast({
                title: '商品已经下架',
                icon: 'none',
                duration: 2000
              })
              return
            }
            // ee.init(gid);
            var timestamp = Date.parse(new Date());
            timestamp = timestamp / 1000;
            if (t.data.data.on_time > timestamp) {
              wx.showToast({
                title: '商品还未上架',
                icon: 'none',
                duration: 2000
              })
              return
            }

            if (t.data.data.down_time > 0) {
              if (t.data.data.down_time < timestamp) {
                wx.showToast({
                  title: '商品已经到期下架',
                  icon: 'none',
                  duration: 2000
                })
                return
              }
            }

            // let p_type = parseInt(this.data.prom_type ? ee.data.prom_type : 0);



            //-- 把商品的赋值,同时给活动赋值 --
            ee.data.fir_goods = JSON.parse(JSON.stringify(t.data.data));

            t.data.data.on_time = ut.formatTime(t.data.data.on_time, 'yyyy-MM-dd hh:mm:ss');

            let cur_price = t.data.data.shop_price;
            if (getApp().globalData.userInfo && getApp().globalData.userInfo.card_field) {
              let cfile = getApp().globalData.userInfo.card_field;
              if (t.data.data[cfile]) {
                cur_price = t.data.data[cfile];
              }
            }
            let txt = (cur_price / t.data.data.market_price * 10).toFixed(2).toString();
            txt = parseFloat(txt);

            t.data.data['disc'] = txt;

            if (t.data.data.original_img.indexOf(o.imghost) == -1)
              t.data.data.original_img = o.imghost + t.data.data.original_img;


            t.data.data.prom_type = ee.data.prom_type;
            t.data.data.prom_id = ee.data.prom_id;

            //只有是普通商品的时候，才要给商品赋值指定门店
            if ([1, 2, 4, 6, 8, 9].indexOf(parseInt(ee.data.prom_type)) < 0 && t.data.data.pick_up_lists && t.data.data.pick_up_lists.length) {
              t.data.data.pickup_ids = t.data.data.pick_up_lists;
            }
            //}
            ee.setData({
              data: t.data.data,
              sele_g: t.data.data,
              userInfo: getApp().globalData.userInfo
            });

            //一件代发商品不去计算优惠
            if (!ee.data.fir_goods.whsle_id && ee.data.prom_type != 1 && ee.data.prom_type != 4 && ee.data.prom_type != 6 && ee.data.prom_type != 2) {
              ee.check_is_youhui(ee.data.gid);
            }


            //获取统一条形码,普通商品和优惠促销的商品
            if (ee.data.data.prom_type == 0 || ee.data.data.prom_type == 3 || ee.data.data.prom_type == 5 || ee.data.data.prom_type == 7 || ee.data.data.prom_type == 9 || ee.data.data.prom_type == 10) {
              ee.get_sto();
              ee.get_sku(o.stoid, t.data.data, gid);
              ee.check_has_flash();

            } else {
              var gg = "",
                item = t.data.data;

              if (item.goods_spec == "null" || item.goods_spec == null) item.goods_spec = "";
              if (item.goods_color == "null" || item.goods_color == null) item.goods_color = "";

              if (item.goods_spec != "" && item.goods_color != "") {
                gg = item.goods_spec + "/" + item.goods_color;
              } else if (item.goods_spec != "" || item.goods_color != "") {
                gg = item.goods_spec + item.goods_color;
              } else {
                gg = "规格1";
              }
              t.data.data.gg = gg;
              var uu = [];
              uu.push(t.data.data);

              ee.setData({
                sku_g: uu,
              });
            }
            ee.data.g_buy_num = new Map();

            //-- 增加相同的活动 --
            ee.check_prom(gid, ee.data.data.prom_type, ee.data.data.prom_id);
          } else {
            wx.showModal({
              title: t.data.msg,
              showCancel: !1,
            });
          }
        }
      });
    },
    //----------装载同一条形码的商品---------- 
    async get_sku(stoid, gd, g_id, is_normal, func) {
      console.log('get_sku');
      var tt = this,
        arrdata = null;
      var now = ut.gettimestamp();
      await getApp().request.promiseGet("/api/weshop/goods/page", {
        data: {
          store_id: o.stoid,
          sku: gd.sku,
          more_spec: gd.more_spec,
          isonsale: 1,
          is_on_sale: 1,
          pageSize: 500,
          orderField: 'gg_ordid,goods_spec,sort',
          isnewwhere: 1,
          js_pickup_id: 0
        }
      }).then(res => {
        var e = res;
        if (e.data.code == 0) arrdata = e.data.data.pageData;
      })
      if (!arrdata) return false;

      // if(arrdata[0]){
      //   tt.setData({
      //     new_share_imgurl:arrdata[0].share_imgurl
      //   })
      // }

      var arrsku = new Array();
      var gitem = null;
      var gb = 1,
        gg = "";
      for (var i = 0; i < arrdata.length; i++) {
        var goodsinfo = arrdata[i],
          prom = null;

        if (goodsinfo.goods_id != g_id) {


          //要判断一下商品的活动是不是多活动，确定一下商品的prom_type
          var url = '/api/weshop/activitylist/listGoodActInfo2New';
          var req_d = {
            "store_id": os.stoid,
            "goods_id": goodsinfo.goods_id,
            "user_id": getApp().globalData.user_id,
          }
          var ck_res = await getApp().request.promiseGet("/api/weshop/activitylist/listGoodActInfo2New", { data: req_d });
          if (ck_res.data.code == 0 && ck_res.data.data && ck_res.data.data.length > 0) {
            var arr = ck_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) {
              goodsinfo.prom_type = arr2[0].prom_type;
              goodsinfo.prom_id = arr2[0].act_id;
            }
          }

          switch (goodsinfo.prom_type) {
            case 1:

              if (goodsinfo.prom_id) {
                await getApp().request.promiseGet("/api/ms/flash_sale/get/" + os.stoid + "/" + goodsinfo.prom_id, {}).then(res => {
                  if (res.data.code == 0) prom = res.data.data;
                })
              }


              break;
            case 6:
              await getApp().request.promiseGet("/api/weshop/teamlist/get/" + os.stoid + "/" + goodsinfo.prom_id, {}).then(res => {
                console.log(res);
                if (res.data.code == 0) prom = res.data.data;
              })

              break;
            case 2:
              await getApp().request.promiseGet("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + goodsinfo.goods_id + "/" + goodsinfo.prom_id, {}).then(res => {
                if (res.data.code == 0) prom = res.data.data;
              })
              break;
            case 4:
              await getApp().request.promiseGet("/api/weshop/integralbuy/getActInfo/" + os.stoid + "/" + goodsinfo.goods_id + "/" + goodsinfo.prom_id, {}).then(res => {
                if (res.data.code == 0) prom = res.data.data;
              })
              break
            //预售和幸运购不参与
            case 8:
            case 9:
              continue;
          }

        } else {

          //只有是普通商品的时候，才要给商品赋值指定门店
          if ([1, 2, 4, 6, 8, 9].indexOf(parseInt(this.data.prom_type)) < 0 || is_normal) {
            //如果商品有设置分组
            if (goodsinfo.pick_group_ids) {
              goodsinfo.pickup_ids = goodsinfo.pick_up_lists;
            }
          }

        }
        //---如果有活动，不算在一起---
        if (prom) {
          if ([1, 2, 4, 6].indexOf(parseInt(goodsinfo.prom_type)) > -1) {
            console.log(prom);
            if (prom.is_end == 0 && prom.end_time > now && (prom.start_time < now || (prom.show_time && prom.show_time < now))) continue;
          } else {
            continue;
          }
        }
        var item = arrdata[i], gg = "";

        if (goodsinfo.goods_id != g_id) {
          //-- 如果商品有设置分组 --
          if (item.pick_group_ids) {
            item.pickup_ids = item.pick_up_lists;
          }
        }


        if (item.goods_spec == "null" || item.goods_spec == null) item.goods_spec = "";
        if (item.goods_color == "null" || item.goods_color == null) item.goods_color = "";

        if (item.goods_spec != "" && item.goods_color != "") {
          gg = item.goods_spec + "/" + item.goods_color;
        } else if (item.goods_spec != "" || item.goods_color != "") {
          gg = item.goods_spec + item.goods_color;
        } else {
          gg = "规格" + gb;
          gb++;
        }
        item.gg = gg;

        if (item.spec_img)
          item.original_img = os.imghost + item.spec_img;
        else
          item.original_img = os.imghost + item.original_img;


        if (item.goods_id == g_id) {
          gitem = item;
        } else {
          arrsku.push(item);
        }
      }

      //-----------排列在最前面-------------
      arrsku.splice(0, 0, gitem);

      if (is_normal == 1) {
        tt.setData({
          sku_g_pt: arrsku,
          sele_g: gitem
        });
        func();
      } else {
        tt.setData({
          sku_g: arrsku,
          sele_g: gitem
        });
      }
    },

    //-- 判断是否有秒杀 --
    check_has_flash: function (gid) {
      var th = this;
      var url = "/api/weshop/activitylist/getGoodActInfo";
      var user_id = getApp().globalData.user_id;
      if (!user_id) user_id = 0;

      if (!gid) gid = this.data.data.goods_id

      var req_data = {
        store_id: os.stoid,
        goodsidlist: gid,
        is_detail: 1,
        user_id: user_id,
        timetype: 0
      };
      //获取秒杀的多规格
      getApp().request.promiseGet(url, {
        data: req_data
      }).then(async function (res) {
        if (res.data.code == 0 && res.data.data && res.data.data.length) {
          var arr_data = res.data.data;
          var new_arr = [];
          for (let i in arr_data) {
            let item = arr_data[i];
            //找不到活动要剔除
            if (!item.act_name) continue;

            if ([1, 2, 4, 6, 8, 9].indexOf(item.prom_type) == -1) continue;
            new_arr.push(item);
          }

          // if (new_arr.length == 1) {
          //   th.data.prom_id = new_arr[0].act_id;
          //   th.data.prom_type = new_arr[0].prom_type;
          // }

          th.setData({
            more_flash: new_arr
          });
        }
      })
    },


    //--------检查是否活动，活动是否开始，或者是否结束-------
    async check_prom(gid, prom_type, prom_id) {

      console.log('check_prom');
      var ee = this,
        th = ee;
      var user_id = getApp().globalData.user_id;
      if (!user_id) user_id = 0;

      if (prom_type == 3 || prom_type == 0 || prom_type == 5 || prom_type == 7 || prom_type == 9 || prom_type == 10) {
        this.setData({
          prom_type: 0,
          isshow: 1,
        });
        return false;
      }

      if (prom_type == 2) {
        //-------判断团购活动是否抢光---------
        await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/" + prom_type + "/" + prom_id, {
          1: 1
        }).then(res => {
          var em = res;
          if (em.data.code == 0) {
            if (em.data.data <= 0) ee.setData({
              prom_r_null: 1
            });
            //拿取价格并且判断时间--
            getApp().request.get("/api/weshop/goods/groupBuy/getActInfo/" + os.stoid + "/" + gid + "/" + prom_id, {
              success: function (t) {
                if (t.data.code != 0) {
                  ee.get_normal(gid);
                  return false;
                }
                //----已经结束-----
                if (t.data.data.is_end == 1) {
                  ee.get_normal(gid);
                  return false;
                }
                //----已经过期-----
                var now = ut.gettimestamp();
                if (t.data.data.end_time < now || t.data.data.start_time > now) {
                  ee.get_normal(gid);
                  return false;
                }

                /*-- 还没有开始预热的也不显示 --*/
                if (t.data.data.show_time > now) {
                  ee.get_normal(gid);
                  return false;
                }

                var t_gd = ee.data.data;
                var prom_end_time = ut.formatTime(t.data.data.end_time, "yyyy-MM-dd hh:mm:ss");
                var prom_start_time = ut.formatTime(t.data.data.start_time, "yyyy-MM-dd hh:mm:ss");

                ee.setData({
                  prom_price: t.data.data.price,
                  prom_type: 2,
                  prom_id: prom_id,
                  prom_buy_limit: t.data.data.buy_limit,
                  prom_act: t.data.data,
                  prom_end_time: prom_end_time,
                  prom_start_time: prom_start_time,
                  isshow: 1,
                });

                ee.get_sto();
                var newTime = ut.gettimestamp();
                var endTime2 = t.data.data.end_time;
                var endTime1 = t.data.data.start_time;
                if (endTime1 > newTime) {
                  ee.setData({
                    prom_time_text: '距团购开始还有'
                  })
                  // ee.countDown(endTime1, 0);
                } else {
                  if (endTime2 > newTime) {
                    ee.setData({
                      prom_time_text: '距团购结束还有',
                      prom_st: 1
                    })
                    // ee.countDown(endTime2);
                  }
                }

              }
            });
          }
        })
      }

      if (prom_type == 1 && prom_id == 0) {
        this.setData({
          prom_type: 0,
          isshow: 1,
        });

        //获取门店
        this.get_sto();
        this.get_sku(o.stoid, this.data.data, gid);
        this.check_has_flash();
        this.data.is_normal = 1;
        if (!this.data.data.whsle_id) this.check_is_youhui(gid, 1);
        return false;
      }

      //if (prom_type != 3 && prom_type!=0){
      //---判断秒杀----
      if (prom_type == 1 && prom_id > 0) {
        //-------判断活动是否抢光---------
        await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/" + prom_type + "/" + prom_id, {
          1: 1
        }).then(res => {
          var em = res;
          if (em.data.code == 0) {

            if (em.data.data <= 0) ee.setData({
              prom_r_null: 1, pro_null: 1
            });
            //拿取价格并且判断时间--
            getApp().request.get("/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + prom_id, {
              success: function (t) {
                if (t.data.code != 0) {
                  ee.get_normal(gid);
                  return false;
                }
                ee.setData({
                  is_share_text: t.data.data.is_share_text
                })
                //----已经结束-----
                if (t.data.data.is_end == 1) {
                  ee.get_normal(gid);
                  return false;
                }
                //----已经过期-----
                var now = ut.gettimestamp();
                if (t.data.data.end_time < now) {
                  ee.get_normal(gid);
                  return false;
                }
                /*-- 还没有开始预热的也不显示 --*/
                if (t.data.data.show_time > now) {
                  ee.get_normal(gid);
                  return false;
                }

                var t_gd = ee.data.data;
                var prom_end_time = ut.formatTime(t.data.data.end_time, "yyyy-MM-dd hh:mm:ss");
                var prom_start_time = ut.formatTime(t.data.data.start_time, "yyyy-MM-dd hh:mm:ss");

                ee.setData({
                  prom_price: t.data.data.user_price,
                  prom_type: 1,
                  prom_id: prom_id,
                  prom_buy_limit: t.data.data.buy_limit,
                  prom_act: t.data.data,
                  prom_end_time: prom_end_time,
                  prom_start_time: prom_start_time,
                  isshow: 1,
                });

                ee.get_sto();
                var newTime = ut.gettimestamp();
                var endTime2 = t.data.data.end_time;
                var endTime1 = t.data.data.start_time;
                if (endTime1 > newTime) {
                  ee.setData({
                    prom_time_text: '距秒杀开始还有'
                  })
                  // ee.countDown(endTime1, 0);
                } else {
                  if (endTime2 > newTime) {
                    ee.setData({
                      prom_time_text: '距秒杀结束还有',
                      prom_st: 1
                    })
                    // ee.countDown(endTime2);
                  }
                }

                //如果是进行中的话
                if (endTime1 < newTime) {
                  //-- 获取秒杀活动的多少规格 --
                  ee.get_more_flahs(function (list) {
                    if (list && list.length > 1) {

                      var n_item = list[0];
                      var ind = list.findIndex(function (ele) {
                        return ele.goods_id == ee.data.data.goods_id;
                      })
                      if (ind < 0) return false;
                      if (ind > 0) {
                        n_item = JSON.parse(JSON.stringify(list[ind]));
                        list.splice(ind, 1);
                        list.unshift(n_item);
                      }

                      ee.data.sele_g.viplimited = n_item.viplimited;
                      ee.data.data.viplimited = n_item.viplimited;

                      ee.data.sele_g.prom_type = 1;
                      ee.data.sele_g.prom_id = n_item.act_id;

                      var gb = 1;
                      //-- 显示多规格 --
                      for (let i in list) {
                        let item = list[i];
                        var gg = "";
                        if (item.goods_spec == "null" || item.goods_spec == null) item.goods_spec = "";
                        if (item.goods_color == "null" || item.goods_color == null) item.goods_color = "";

                        if (item.goods_spec != "" && item.goods_color != "") {
                          gg = item.goods_spec + "/" + item.goods_color;
                        } else if (item.goods_spec != "" || item.goods_color != "") {
                          gg = item.goods_spec + item.goods_color;
                        } else {
                          gg = "规格" + gb;
                          gb++;
                        }
                        item.gg = gg;
                        item.prom_id = item.prom_id;
                        item.prom_type = 1;
                      }

                      ee.setData({
                        sku_g: list,
                        is_more_flash: 1
                      });

                    }
                  })
                }

              }
            });
          }
        })
      }

      if (prom_type == 4) {
        //th.setData({is_integral_normal:1});
        var rdata = {
          store_id: o.stoid,
          stype: 1,
          stypeup: 1,
          goods_id: gid,
          timetype: 2,
          user_id: getApp().globalData.user_id,
        }

        var integrals = 0;
        var get_datas = {
          user_id: getApp().globalData.user_id,
          store_id: o.stoid,
        };
        await getApp().request.promiseGet("/api/weshop/users/getAllPoints", {
          data: get_datas
        }).then(res => {
          if (res.data.code == 0) {
            integrals = res.data.data?.Integral ? res.data.data?.Integral : 0;
          }
        })

        //获取一下积分活动
        await getApp().request.promiseGet("/api/weshop/integralbuy/pageIntegralBuyGoodsList", {
          data: rdata
        }).then(res => {
          //调用接口有数据的时候
          if (res.data.code == 0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length > 0) {
            var inte_data = res.data.data.pageData[0];
            var can_integral = (parseFloat(integrals) >= parseFloat(inte_data.integral));
            let times = new Date().getTime()
            inte_data.show_time_off = ""
            let atimes = inte_data.start_time * 1000

            if (atimes > times) {
              inte_data.show_time_off = ut.formatTime(inte_data.start_time)
            }

            ee.setData({
              prom_price: parseFloat(inte_data.addmoney),
              prom_integral: parseFloat(inte_data.integral),
              prom_type: 4,
              prom_id: inte_data.id,
              prom_buy_limit: inte_data.limitvipqty,
              prom_act: inte_data,
              isshow: 1,
              can_integral: can_integral,
              is_shopbuy: parseInt(inte_data.is_shopbuy ? inte_data.is_shopbuy : 0)
            });
            ee.get_sto();

          } else {
            ee.get_normal(gid);
            return false;
          }
        })

      }

      //---判断拼单----
      if (prom_type == 6) {

        th.setData({
          user_order_pt_state: 0
        });

        //-------判断活动是否抢光---------
        await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/" + prom_type + "/" + prom_id, {
          1: 1
        }).then(res => {
          var em = res;
          var flag = null;
          if (em.data.code == 0) {
            if (em.data.data <= 0) ee.setData({
              prom_r_null: 1
            });
            //-- 拿取价格并且判断时间,同时判断会员身份 --
            getApp().request.get("/api/weshop/teamlist/getUser/" + os.stoid + "/" + prom_id + "/" + getApp().globalData.user_id, {
              success: async function (t) {
                if (t.data.code != 0) {
                  ee.get_normal(gid);
                  return false;
                }
                //----已经结束-----
                if (t.data.data.is_end == 1) {
                  ee.get_normal(gid);
                  return false;
                }
                //----已经过期-----
                var now = ut.gettimestamp();
                if (t.data.data.end_time < now) {
                  ee.get_normal(gid);
                  return false;
                }

                /*-- 还没有开始预热的也不显示 --*/
                if (t.data.data.show_time > now) {
                  ee.get_normal(gid);
                  return false;
                }

                /*-- 判断拼单是否启用 --*/
                if (!t.data.data.is_show) {
                  console.log('没启用');
                  wx.setNavigationBarTitle({
                    title: '系统提示',
                  });
                  wx.showToast({
                    title: '此商品暂时没有拼单活动',
                    icon: 'none',
                    success() {
                      setTimeout(() => {
                        wx.navigateBack()
                      }, 2000)
                    }
                  });
                  return false
                }


                //-------查看自己是不是有买过该团的商品，并还为支付，或者在进行中-------
                await getApp().request.promiseGet("/api/weshop/order/page", {
                  data: {
                    pt_prom_id: prom_id,
                    user_id: oo.user_id,
                    store_id: os.stoid,
                    pageSize: 1,
                    page: 1
                  }
                }).then(e => {
                  if (e.data.code == 0 && e.data.data.pageData.length > 0) {
                    var odr = e.data.data.pageData[0];
                    th.data.buy_order = odr;
                    if (odr.pt_status == 0 && odr.order_status == 1) {
                      th.setData({
                        user_order_pt_state: 1
                      });
                    }
                    if (odr.pt_status == 1 && odr.order_status == 1) {
                      if (odr.is_zsorder == 4) {
                        getApp().request.promiseGet("/api/weshop/teamgroup/page/", {
                          data: {
                            store_id: os.stoid,
                            team_id: odr.pt_prom_id,
                            listno: odr.pt_listno
                          }
                        }).then(res => {
                          var now = ut.gettimestamp();
                          if (res.data.code == 0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length > 0) {
                            var tgr = res.data.data.pageData[0];
                            //如果团的时间已经到了
                            if (now >= tgr.kt_end_time) {
                              th.update_jiti(tgr.id);
                            } else {
                              th.setData({
                                user_order_pt_state: 2
                              });
                            }
                          }
                        })

                      } else {
                        th.setData({
                          user_order_pt_state: 2
                        });
                      }
                    }

                    if (odr.pt_status == 2 && odr.is_zsorder == 4) {
                      th.setData({
                        user_order_pt_state: 3,
                      });
                      th.data.wk_order_id = odr.order_id;
                    }
                  }
                })

                //----------查看阶梯团------------
                if (t.data.data.ct_rylist != "null" && t.data.data.ct_rylist != "" && t.data.data.ct_rylist != null && t.data.data.ct_rylist != undefined) {
                  t.data.data.ct_rylist = JSON.parse(t.data.data.ct_rylist);
                  var max_num = 0;
                  t.data.data.ct_rylist.forEach(function (val, ind) {
                    if (parseInt(val.rynum) > max_num) max_num = parseInt(val.rynum);
                  })
                  t.data.data.max_ct_num = max_num;
                }

                var prom_end_time = ut.formatTime(t.data.data.end_time, "yyyy-MM-dd hh:mm:ss");
                var prom_start_time = ut.formatTime(t.data.data.start_time, "yyyy-MM-dd hh:mm:ss");
                ee.setData({
                  prom_price: t.data.data.price,
                  prom_type: 6,
                  prom_id: prom_id,
                  prom_buy_limit: t.data.data.buy_limit,
                  prom_act: t.data.data,
                  prom_end_time: prom_end_time,
                  prom_start_time: prom_start_time,
                  isshow: 1,
                });

                ee.get_sto();

                var newTime = now;
                var endTime2 = t.data.data.end_time;
                var endTime1 = t.data.data.start_time;

                if (endTime1 > newTime) {
                  ee.setData({
                    prom_time_text: '距拼单开始还剩:'
                  })
                  // ee.countDown(endTime1, 0);
                } else {
                  if (endTime2 > newTime) {
                    ee.setData({
                      prom_time_text: '距拼单结束还剩:',
                      prom_st: 1
                    })
                    // ee.countDown(endTime2);
                  }
                }
                //-------查看有多少人在开这个团-------
                // th.get_team_group(prom_id);
              }
            });
          }
        })
      }
    },


    //--------服务卡检查是否活动，活动是否开始，或者是否结束-------
    async ser_check_prom(gid, prom_type, prom_id) {
      var ee = this, th = ee;
      var user_id = getApp().globalData.user_id;
      if (!user_id) user_id = 0;

      if (prom_type == 1 && prom_id == 0) {
        this.setData({
          prom_type: 0
        });

        //获取门店
        this.get_sto();
        // this.get_sku(o.stoid, this.data.data, gid);
        this.check_has_flash();
        this.data.is_normal = 1;
        // this.check_is_youhui(gid, 1);
        return false;
      }

      //---判断秒杀----
      if (prom_type == 1 && prom_id > 0) {
        //-------判断活动是否抢光---------
        await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/" + prom_type + "/" + prom_id, {
          1: 1
        }).then(res => {
          var em = res;
          if (em.data.code == 0) {

            if (em.data.data <= 0) {
              th.setData({
                prom_r_null: 1,
                goodsInputNum: res.data.data,
              });

              // th.setData({goodsInputNum: redis_num})
            };
            //拿取价格并且判断时间--
            getApp().request.get("/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + prom_id, {
              success: function (t) {
                let sele_g_new = t.data.data
                let sele_g = th.data.sele_g
                if (sele_g_new && sele_g_new.original_img && !sele_g.original_img) {
                  sele_g.original_img = sele_g_new.original_img
                }
                th.setData({
                  sele_g
                });

                if (t.data.code != 0) {
                  ee.get_normal(gid);
                  return false;
                }
                //----已经结束-----
                if (t.data.data.is_end == 1) {
                  ee.get_normal(gid);
                  return false;
                }
                //----已经过期-----
                var now = ut.gettimestamp();
                if (t.data.data.end_time < now) {
                  ee.get_normal(gid);
                  return false;
                }
                /*-- 还没有开始预热的也不显示 --*/
                if (t.data.data.show_time > now) {
                  ee.get_normal(gid);
                  return false;
                }

                var t_gd = ee.data.data;
                var prom_end_time = ut.formatTime(t.data.data.end_time, "yyyy-MM-dd hh:mm:ss");
                var prom_start_time = ut.formatTime(t.data.data.start_time, "yyyy-MM-dd hh:mm:ss");

                ee.setData({
                  prom_price: t.data.data.user_price,
                  prom_type: 1,
                  prom_id: prom_id,
                  prom_buy_limit: t.data.data.buy_limit,
                  prom_act: t.data.data,
                  prom_end_time: prom_end_time,
                  prom_start_time: prom_start_time,
                });

                ee.get_sto();
                var newTime = ut.gettimestamp();
                var endTime2 = t.data.data.end_time;
                var endTime1 = t.data.data.start_time;
                if (endTime1 > newTime) {
                  ee.setData({
                    prom_time_text: '距秒杀开始还有',
                    prom_st: 0,
                  })
                  // ee.countDown(endTime1, 0);
                } else {
                  if (endTime2 > newTime) {
                    ee.setData({
                      prom_time_text: '距秒杀结束还有',
                      prom_st: 1
                    })
                    // ee.countDown(endTime2);
                  }
                }

                //如果是进行中的话
                if (endTime1 < newTime) {
                  //-- 获取秒杀活动的多少规格 --
                  ee.get_more_flash(function (list) {
                    if (list && list.length > 1) {

                      var n_item = list[0];
                      var ind = list.findIndex(function (ele) {
                        return ele.goods_id == ee.data.data.goods_id;
                      })
                      if (ind < 0) return false;
                      if (ind > 0) {
                        n_item = JSON.parse(JSON.stringify(list[ind]));
                        list.splice(ind, 1);
                        list.unshift(n_item);
                      }

                      ee.data.sele_g.viplimited = n_item.viplimited;
                      ee.data.data.viplimited = n_item.viplimited;

                      var gb = 1;
                      //-- 显示多规格 --
                      for (let i in list) {
                        let item = list[i];
                        var gg = "";
                        if (item.goods_spec == "null" || item.goods_spec == null) item.goods_spec = "";
                        if (item.goods_color == "null" || item.goods_color == null) item.goods_color = "";

                        if (item.goods_spec != "" && item.goods_color != "") {
                          gg = item.goods_spec + "/" + item.goods_color;
                        } else if (item.goods_spec != "" || item.goods_color != "") {
                          gg = item.goods_spec + item.goods_color;
                        } else {
                          gg = "规格" + gb;
                          gb++;
                        }
                        item.gg = gg;
                        item.prom_id = item.prom_id;
                        item.prom_type = 1;
                      }

                      ee.setData({
                        sku_g: list,
                      });

                    }
                  })
                }

              }
            });
          }
        })
      }

    },
    //获取更多秒杀
    get_more_flash: async function (func) {

      var f_more = false;
      var user_id = getApp().globalData.user_id;
      if (!user_id) user_id = 0;

      var url = "/api/weshop/goods/listSkuFlash?store_id=" + os.stoid + "&goods_id=" + this.data.gid + "&user_id=" + user_id;
      //获取秒杀的多规格
      await getApp().request.promiseGet(url, {}).then(res => {
        if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
          f_more = res.data.data;
        }
      })
      if (!f_more) {
        func(false);
        return false;
      }
      //-- 秒杀的价格要更新 --
      for (let i in f_more) {

        let item = f_more[i];
        f_more[i].prom_id = item.act_id;
        f_more[i].prom_type = 1;
        if (item.goods_id == this.data.sele_g.goods_id) {
          continue;
        }
        var url = "/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + item.act_id;
        await getApp().request.promiseGet(url, {}).then(rs => {
          if (rs.data.code == 0) {
            f_more[i].price = rs.data.data.user_price;

          }
        })
      }
      func(f_more);

    },
    //---------拿出门店分类和门店------------
    get_sto(e, func, item) {

      var th = this,
        that = this;
      var is_normal = e;

      if (e == 1) {
        th.setData({
          is_normal: 1
        })
      } else {
        th.setData({
          is_normal: 0
        })
      }

      timer_get = setInterval(function () {

        if (th.data.is_get_local_ok == 0) return false;
        if (!th.data.fir_def_store) return false;

        var dd = null,
          i = getApp().request;
        if (!th.data.sele_g) return false;

        var g_distr_type = th.data.sele_g.distr_type;
        if (g_distr_type && g_distr_type != 0) {
          dd = {
            store_id: o.stoid,
            distr_type: g_distr_type,
            isstop: 0,
            is_pos: 1,
            pageSize: 2000
          }
        } else {
          dd = {
            store_id: o.stoid,
            isstop: 0,
            is_pos: 1,
            pageSize: 2000
          }
        }
        //如果有距离的话
        if (th.data.lat != null) {
          dd.lat = th.data.lat;
          dd.lon = th.data.lon;
        }

        clearInterval(timer_get);

        //如果会员是有默认的门店话
        if (!th.data.def_pick_store && th.data.fir_def_store && Object.keys(th.data.fir_def_store).length > 0) {
          th.setData({
            def_pick_store: th.data.fir_def_store
          });
        }
        wx.showLoading({
          title: '加载中.',
          mask: true
        });
        //----------获取门店----------------
        getApp().request.promiseGet("/api/weshop/pickup/list", {
          data: dd,
        }).then(res => {
          var e = res;

          if (e.data.code == 0 && e.data.data && e.data.data.pageData && e.data.data.pageData.length > 0) {

            var pickup_ids = th.data.sele_g.pickup_ids;
            //不是单独购买的时候，要清空商品pickup_ids

            var py = parseFloat(th.data.prom_type + '');
            if (!is_normal && py > 0 && [3, 5, 7, 10].indexOf(py) < 0) {
              pickup_ids = null;
            }
            //-- 把秒杀的指定对象带入 --
            if (item) {
              if (item.is_pickup && item.pick_up_lists) {
                pickup_ids = item.pick_up_lists
              } else {
                pickup_ids = null;
              }

            } else if (!is_normal && [1, 2, 6].indexOf(py) > -1 && th.data.prom_act.pick_up_lists) { //指定门店判断， 不是普通购买的时候，秒杀的时候，秒杀有指定门店
              pickup_ids = th.data.prom_act.pick_up_lists
            }

            //-- 如果有指定门店的时候 --
            if (pickup_ids) {

              var ok_arr = [];
              for (let i in e.data.data.pageData) {
                let ite = e.data.data.pageData[i];
                //-- 查找一下门店有没有在 --
                var idx = pickup_ids.findIndex(function (e) {
                  return e.pickup_id == ite.pickup_id;
                })
                if (idx > -1) {
                  ok_arr.push(ite)
                }
              }

              //判断会员的默认的门店是不是匹配指定的门店
              if (th.data.def_pick_store && JSON.stringify(th.data.def_pick_store) != '{}') {
                //-- 查找一下门店有没有在 --
                var idx1 = pickup_ids.findIndex(function (e) {
                  return e.pickup_id == th.data.def_pick_store.pickup_id;
                })

                if (idx1 < 0) {
                  //如果是秒杀的指定门店，就要设置秒杀的
                  if (!is_normal && [1, 2, 6].indexOf(py) > -1) {
                    th.data.def_pick_store.is_no_dis_act = 1;
                  } else {
                    th.data.def_pick_store.is_no_dis_nor = 1;
                  }
                } else {
                  th.data.def_pick_store.is_no_dis_nor = 0;
                  th.data.def_pick_store.is_no_dis_act = 0;
                }

                that.setData({
                  def_pick_store: th.data.def_pick_store
                })

              }
              e.data.data.pageData = ok_arr;     //数组重新赋值
              e.data.data.total = ok_arr.length; //数组的长度
            }
            else {
              //-- 多规格指定门店优化 --
              if (th.data.def_pick_store && JSON.stringify(th.data.def_pick_store) != '{}') {

                th.data.def_pick_store.is_no_dis_nor = 0;
                th.data.def_pick_store.is_no_dis_act = 0;
                that.setData({
                  def_pick_store: th.data.def_pick_store
                })
              }
            }

            //过滤后门店数量还是要大于0
            if (e.data.data.pageData.length > 0) {

              var his_cate_num = 0;
              for (let i in e.data.data.pageData) {
                let item = e.data.data.pageData[i];
                if (item.category_id > 0) {
                  his_cate_num = 1;
                }
                if (getApp().is_virtual(th.data.sele_g) && th.data.sales_rules >= 2) {
                  e.data.data.pageData[i].CanOutQty = 100000;
                }
              }

              e.his_cate_num = his_cate_num;

              if (th.data.def_pick_store && JSON.stringify(th.data.def_pick_store) != '{}' &&
                getApp().is_virtual(th.data.sele_g) && th.data.sales_rules >= 2) {
                th.setData({
                  'def_pick_store.CanOutQty': 100000
                })
              }

              //如果有开启距离的功能，没有设置默认门店，要用最近的门店作为默认门店
              if (dd.lat && (!th.data.def_pick_store || JSON.stringify(th.data.def_pick_store) == '{}') && th.data.bconfig && th.data.bconfig.is_sort_storage) {
                th.setData({
                  def_pick_store: e.data.data.pageData[0],
                  sto_sele_name: e.data.data.pageData[0].pickup_name,
                  sto_sele_id: e.data.data.pageData[0].pickup_id,
                  sto_sele_distr: e.data.data.pageData[0].distr_type
                });
                th.data.fir_def_store = e.data.data.pageData[0];
              }

              //-- 如果有默认选择门店的时候，要把默认门店放在第一位，修改不要配送方式的判断 --
              if (th.data.def_pick_store && JSON.stringify(th.data.def_pick_store) != '{}') {
                for (var k = 0; k < e.data.data.pageData.length; k++) {
                  if (e.data.data.pageData[k].pickup_id == th.data.def_pick_store.pickup_id) {
                    e.data.data.pageData.splice(k, 1); //删除
                    break;
                  }
                }
                e.data.data.pageData.splice(0, 0, th.data.def_pick_store); //添加
              }


              th.setData({
                all_pick_list: e.data.data.pageData
              });

              //--获取线下库存,而且不是新的门店规则, 同时是普通购买的时候，或者同时不能是活动，秒杀，拼团，积分购--
              if (!getApp().is_virtual(th.data.sele_g) && th.data.sales_rules >= 2 && !th.data.is_newsales_rules
                && !th.data.sele_g.whsle_id && ([1, 2, 4, 6, 8, 9].indexOf(th.data.prom_type) == -1 || is_normal == 1)) {
                setTimeout(function () {
                  th.deal_pickup_dline(e);
                }, 800)
              } else {
                setTimeout(function () {
                  th.deal_pickup(e); //--普通门店排版--
                }, 800)
              }
              if (func) func();
            } else {

              if (func) func();
              th.setData({ sp_seleing: 0 })
              wx.hideLoading();
            }
          } else {
            if (func) func();
            th.setData({ sp_seleing: 0 })
            wx.hideLoading();
          }
        }, err => {
          ut.m_toast('网络繁忙，请稍后重试');
          if (func) func();
          th.setData({ sp_seleing: 0 })
          wx.hideLoading();
        })
      }, 200)

    },

    //------------处理门店---------------
    deal_pickup(e) {

      var th = this;
      if (!th.data.sele_g) {
        wx.hideLoading();
        return false
      }

      var g_distr_type = th.data.sele_g.distr_type;
      wx.hideLoading()


      /*--- 判断初始的用户的默认门店要不要弄进去 ---*/
      var fid = -1;
      if (th.data.fir_def_store) {
        var fid = e.data.data.pageData.findIndex((e) => {
          return e.pickup_id == th.data.fir_def_store.pickup_id;
        })
      }
      //--如果找到默认门店,同时也应该判断配送方式对不对--
      if (th.data.fir_def_store && th.data.fir_def_store.pickup_id && fid < 0 &&
        (g_distr_type == 0 || th.data.fir_def_store.distr_type == 0 || th.data.def_pick_store.distr_type == g_distr_type)) {
        th.data.fir_def_store.CanOutQty = 0;
        //--当选择的门店是客户默认的门店的时候--
        if (th.data.def_pick_store && th.data.fir_def_store.pickup_id == th.data.def_pick_store.pickup_id) {
          th.setData({
            def_pick_store: th.data.fir_def_store
          });
          e.data.data.pageData.unshift(th.data.def_pick_store);
        } else {
          e.data.data.pageData.splice(1, 0, th.data.fir_def_store);
        }
      }



      //单总量超出10个的时候，同时门店有分类
      if (e.data.data.total > 10 && e.his_cate_num) {
        getApp().request.get("/api/weshop/storagecategory/page", {
          data: {
            store_id: o.stoid,
            pageSize: 1000,
            orderField: "sort",
            orderType: 'asc',
          },
          success: function (ee) {
            if (ee.data.code == 0) {
              var check_all_cate = 0;
              if (ee.data.data && ee.data.data.pageData && ee.data.data.pageData.length > 0) {
                for (let i in ee.data.data.pageData) {
                  let item = ee.data.data.pageData[i];
                  if (item.is_show == 1) {
                    check_all_cate = 1;
                    break
                  }
                }
              }
              if (check_all_cate) {
                var sto_cate = ee.data.data.pageData;
                var sto_arr = e.data.data.pageData;
                var newarr = new Array();
                var qita = new Array();

                var is_del_pk = 0;
                //----要进行门店分组--------
                for (var i = 0; i < sto_arr.length; i++) {
                  //找一下这个门店有没有在分类数组内
                  var find2 = 0,
                    find2name = "",
                    sort = 0;
                  is_del_pk = 0;
                  for (var m = 0; m < sto_cate.length; m++) {
                    if (sto_arr[i].category_id == sto_cate[m].cat_id) {
                      if (sto_cate[m].is_show != 1) {
                        is_del_pk = 1;
                        sto_arr.splice(i, 1);
                        i--;
                      } else {
                        find2 = sto_cate[m].cat_id;
                        find2name = sto_cate[m].cat_name;
                        sort = sto_cate[m].sort;
                        is_del_pk = 0;
                      }
                      break;
                    }
                  }
                  if (is_del_pk) continue;

                  if (newarr.length > 0) {
                    var find = 0;
                    //如果有找到，那门店就在这个分组内，否则，分类就要排在其他
                    if (find2 != 0) {
                      for (var ii = 0; ii < newarr.length; ii++) {
                        if (sto_arr[i].category_id == newarr[ii].cat_id) {
                          newarr[ii].s_arr.push(sto_arr[i]);
                          find = 1;
                          break;
                        }
                      }
                      if (find == 0) {
                        var arr0 = new Array();
                        arr0.push(sto_arr[i]);
                        var item = {
                          cat_id: find2,
                          name: find2name,
                          sort: sort,
                          s_arr: arr0
                        };
                        newarr.push(item);
                      }
                    } else {
                      qita.push(sto_arr[i]);
                    }
                  } else {
                    //如果有找到，那门店就在这个分组内，否则，分类就要排在其他
                    if (find2 != 0) {
                      var arr0 = new Array();
                      arr0.push(sto_arr[i]);
                      var item = {
                        cat_id: find2,
                        name: find2name,
                        sort: sort,
                        s_arr: arr0
                      };
                      newarr.push(item);
                    } else {
                      qita.push(sto_arr[i]);
                    }
                  }
                }

                var def_arr = new Array();
                //-- 开始就看10个门店 --
                for (var k = 0; k < 10; k++) {
                  if (k == sto_arr.length) break;
                  def_arr.push(sto_arr[k]);
                }

                th.setData({
                  def_pickpu_list: def_arr,
                  pickpu_list: ee.data.data.pageData
                });


                //门店分类要排序下
                function compare(property) {
                  return function (a, b) {
                    var value1 = a[property];
                    var value2 = b[property];
                    return value1 - value2;
                  }
                }

                if (newarr.length > 0)
                  newarr.sort(compare("sort"));


                //----安排其他的分类-----
                if (qita.length > 0) {
                  var item = {
                    cat_id: -1,
                    name: "其他",
                    s_arr: qita
                  };
                  newarr.push(item);
                }

                var sd = {
                  all_sto: newarr,
                  is_show_sto_cat: 1
                }
                if (!sto_arr || sto_arr.length <= 10) {
                  sd.is_show_sto_cat = -1;
                  sd.only_pk = sto_arr;
                }
                th.setData(sd);

              } else {
                th.setData({
                  is_show_sto_cat: -1,
                  only_pk: e.data.data.pageData
                });
                //-----如果没有默认门店，要取第一个门店作为默认店.此时没有门店分类的情况------
                if (!th.data.def_pick_store) {
                  th.setData({
                    def_pick_store: e.data.data.pageData[0],
                    sto_sele_name: e.data.data.pageData[0].pickup_name,
                    sto_sele_id: e.data.data.pageData[0].pickup_id,
                    sto_sele_distr: e.data.data.pageData[0].distr_type
                  })
                }
              }
            } else {
              th.setData({
                is_show_sto_cat: -1,
                only_pk: e.data.data.pageData
              });
              //-----如果没有默认门店，要取第一个门店作为默认店.此时没有门店分类的情况------
              if (!th.data.def_pick_store) {
                th.setData({
                  def_pick_store: e.data.data.pageData[0],
                  sto_sele_name: e.data.data.pageData[0].pickup_name,
                  sto_sele_id: e.data.data.pageData[0].pickup_id,
                  sto_sele_distr: e.data.data.pageData[0].distr_type
                })
              }

            }
          }
        });
      } else {

        th.setData({
          is_show_sto_cat: 0,
          only_pk: e.data.data.pageData
        });
        //-----如果没有默认门店，要取第一个门店作为默认店------
        if (!th.data.def_pick_store && th.data.bconfig && th.data.bconfig.is_sort_storage) {
          th.setData({
            def_pick_store: e.data.data.pageData[0],
            sto_sele_name: e.data.data.pageData[0].pickup_name,
            sto_sele_id: e.data.data.pageData[0].pickup_id,
            sto_sele_distr: e.data.data.pageData[0].distr_type
          })
        }
      }
    },

    //------------处理线下门店库存--------
    deal_pickup_dline(e) {
      var pkno = [],
        th = this;
      if (!th.data.sele_g) {
        wx.hideLoading();
        return false;
      }

      if (this.data.def_pick_store) {
        pkno.push(this.data.def_pick_store.pickup_no);
      }
      for (var i in e.data.data.pageData) {
        var item = e.data.data.pageData[i];
        if (pkno.indexOf(item.pickup_no) < 0)
          pkno.push(item.pickup_no);
      }
      pkno.sort();
      var pkno_str = pkno.join(",");
      var o_plist = e.data.data.pageData;
      var new_list = [];
      var is_find_def_store = 0;


      var g_distr_type = th.data.sele_g.distr_type;
      var lock = [];

      var lock_rq = {
        store_id: os.stoid,
        wareId: th.data.sele_g.goods_id,
        pageSize: 1000
      };

      if (th.data.sales_rules == 3) {
        lock_rq.appoint_pick_keyid = th.data.appoint_pick_keyid;
      }

      //先读取门店的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) {
          lock = res.data.data.pageData
        }
        var sto_rq = {
          wareIds: encodeURIComponent(th.data.sele_g.erpwareid),
          storeId: os.stoid,
          pageSize: 2000
        }

        if (th.data.sales_rules == 3) {
          sto_rq.storageIds = th.data.appoint_pick_keyid;
        } else {
          sto_rq.storageNos = pkno_str;
        }


        //---通过接口获取门店的线下库存信息--
        return getApp().request.promiseGet("/api/weshop/goods/getWareStorages", {
          data: sto_rq
        })
      }).then(res => {

        wx.hideLoading();
        if (res.data.code == 0) {

          if (res.data.data.pageData && res.data.data.pageData.length > 0) {

            var def_pick_store = th.data.def_pick_store;
            var plist = res.data.data.pageData;

            if (th.data.sales_rules == 3) {
              var lock_num = 0;
              var Qty = 0;
              //-- 计算锁住的库存 --
              for (var i in lock) lock_num += lock[i].outQty;
              Qty = plist[0].CanOutQty - lock_num;

              if (Qty > 0) {
                for (var kk in o_plist) {
                  o_plist[kk].CanOutQty = Qty;
                  new_list.push(o_plist[kk]);
                }
                if (th.data.fir_def_store &&
                  (g_distr_type == 0 || th.data.fir_def_store.distr_type == 0 || (th.data.def_pick_store && th.data.def_pick_store.distr_type == g_distr_type))) {
                  th.data.fir_def_store.Qty = Qty;
                  if (def_pick_store && def_pick_store.pickup_id == th.data.fir_def_store.pickup_id)
                    th.setData({
                      def_pick_store: th.data.fir_def_store
                    })
                  is_find_def_store = 1;
                }

                if (def_pick_store) {
                  //-- 如果库存为0就要重新赋值 --
                  def_pick_store.CanOutQty = Qty;
                  th.setData({
                    def_pick_store
                  })
                }


              } else {
                th.setData({
                  all_sto: null,
                  only_pk: null,
                  def_pickpu_list: null
                });
                return false;
              }

            } else {


              //以原来的数组为外循环，保证距离的顺序
              for (var kk in o_plist) {
                for (var ii in plist) {
                  //线下的门店小心
                  var n_item = plist[ii];
                  if (n_item.StorageNo == o_plist[kk].pickup_no) {

                    //拿到锁库的数量
                    var lock_num = th.find_lock_num(o_plist[kk].pickup_id, lock);
                    //可出库数大于预出库库存的数量，可以判断为有库存
                    if (n_item.CanOutQty > lock_num) {
                      o_plist[kk].CanOutQty = n_item.CanOutQty - lock_num;
                      new_list.push(o_plist[kk]);

                      var ck_store = th.data.fir_def_store;
                      if (th.data.def_pick_store && JSON.stringify(th.data.def_pick_store) != '{}') {
                        ck_store = th.data.def_pick_store;
                      }


                      //--如果找到默认门店,同时也应该判断配送方式对不对--
                      if (th.data.fir_def_store && n_item.StorageNo == th.data.fir_def_store.pickup_no && (g_distr_type == 0 || th.data.fir_def_store.distr_type == 0 || th.data.def_pick_store.distr_type == g_distr_type)) {
                        th.data.fir_def_store.CanOutQty = n_item.CanOutQty - lock_num;
                        if (def_pick_store && def_pick_store.pickup_id == th.data.fir_def_store.pickup_id)
                          th.setData({
                            def_pick_store: th.data.fir_def_store
                          })
                        is_find_def_store = 1;
                      }

                      //-- 如果库存为0就要重新赋值 --
                      if (def_pick_store && n_item.StorageNo == def_pick_store.pickup_no) {
                        def_pick_store.CanOutQty = o_plist[kk].CanOutQty;
                        th.setData({ def_pick_store })
                      }

                    }
                    break;
                  }
                }
              }

            }



            //数据组装下
            var em = {};
            em.data = {};
            em.data.data = {};
            em.data.data.total = new_list.length;
            em.data.data.pageData = new_list;
            em.his_cate_num = e.his_cate_num;


            var fid = -1;
            if (th.data.fir_def_store) {
              var fid = em.data.data.pageData.findIndex((e) => {
                return e.pickup_id == th.data.fir_def_store.pickup_id;
              })
            }
            //--如果找到默认门店,同时也应该判断配送方式对不对--
            if (th.data.fir_def_store && th.data.fir_def_store.pickup_id && fid < 0 &&
              (g_distr_type == 0 || th.data.fir_def_store.distr_type == 0 || th.data.def_pick_store.distr_type == g_distr_type)) {
              th.data.fir_def_store.CanOutQty = 0;
              //--当选择的门店是客户默认的门店的时候--
              if (th.data.def_pick_store && th.data.fir_def_store.pickup_id == th.data.def_pick_store.pickup_id) {
                th.setData({
                  def_pick_store: th.data.fir_def_store
                });
                em.data.data.pageData.unshift(th.data.def_pick_store);
              } else {
                em.data.data.pageData.splice(1, 0, th.data.fir_def_store);
              }
            }

            for (let j = 0; j < em.data.data.pageData.length; j++) {
              var iu = em.data.data.pageData[j];
              if (iu.CanOutQty <= 0) iu.is_no_qyt = 1;

            }

            //---把数组组装进去---
            th.deal_pickup(em);

          } else {

            th.setData({
              all_sto: null,
              only_pk: null,
              def_pickpu_list: null
            })
          }

        } else {

          th.setData({
            all_sto: null,
            only_pk: null,
            def_pickpu_list: null
          })
        }
      })
    },

    //------------加入购物车--------------
    addCart: function (t) {
      //如果是切换规格的时候，让商品不能提交到确认订单的页面，否则活动会出错，金额也不对
      if (this.data.sp_seleing) {
        return false;
      }

      var th = this;
      var ind = t.currentTarget.dataset.openSpecModal_ind;
      if (!ind) ind = t.currentTarget.dataset.openspecmodal_ind;
      th.setData({
        open_ind_store: ind
      });


      if ("add" == t.currentTarget.dataset.action && getApp().is_sp_hao()) {
        wx.showToast({
          title: "视频号商品不允许加入购物车",
          icon: 'none',
          duration: 2000
        });
        return false;
      }

      if (th.data.adding) return false;
      th.data.adding = 1;

      wx.showLoading({
        mask: true
      })



      //如果是秒杀的话，要看redis够不够
      if (this.data.prom_type == 1 || this.data.prom_type == 2) {

        if (this.data.openSpecModal_flash_normal) {
          this.data.is_normal = 1; //是普通购买
          th.add_cart_func(t);
          return false;
        }


        this.getactLen(function (num) {
          if (num < th.data.goodsInputNum) {
            wx.hideLoading();
            th.data.adding = 0;
            // getApp().my_warnning("活动库存不足!", 0, th);
            wx.showToast({
              title: '活动库存不足!',
              icon: 'none',
            });
            return false;
          } else {
            th.add_cart_func(t);
          }
        });
      } else {
        th.add_cart_func(t);
      }
    },

    //------------加入购物车--------------
    addCartSer: async function (t) {
      var th = this;
      var ind = t.currentTarget.dataset.openSpecModal_ind;
      var action = t.currentTarget.dataset.action;



      if (getApp().is_sp_hao() && action == 'add') {
        wx.showToast({
          title: "视频号商品不允许加入购物车",
          icon: 'none',
          duration: 2000
        });
        return false;
      }


      if (this.data.goodsInputNum == 0) {
        getApp().my_warnning('请输入购买数量', 1, th, 450);
        return false;
      }



      if (!ind) ind = t.currentTarget.dataset.openspecmodal_ind;

      th.setData({
        open_ind_store: ind
      });

      if (!th.data.sto_sele_name) {
        getApp().my_warnning('请选择门店', 1, th, 450);
        return false;
      };

      // 库存
      var redisNums = 0;
      // 限购数
      var limitNum = 0;
      // 已购买数量
      var boughtNum = 0;

      var is_ok = 1;

      // 秒杀活动
      if (this.data.prom_type == 1) {
        // 如果是秒杀活动下的单独购买，is_normal为1
        if (this.data.openSpecModal_flash_normal) this.data.is_normal = 1;

        if (!this.data.is_normal) {// 秒杀购买

          // 获取redis当前可以购买的数量
          // 如果数量为0，设置和显示已抢光
          // 否则，进一步判断是否超出限购或超出库存
          await this.getactLenser().then(async function (res) {
            redisNums = res;
            let curNum = th.data.goodsInputNum;
            // res: redis可购买数量
            console.log('当前可以购买的数量:', res);
            if (res <= 0) {
              // 可购买数量<=0, 设置和显示已抢光
              th.setData({
                prom_r_null: 1,
              });
              // wx.showModal({
              // 	title: '超出活动库存',
              // });
              getApp().my_warnning('超出活动库存', 0, self);
              is_ok = 0;
              return false;
            } else {
              // 可购买数量>0
              // 计算自己还可以购买的数量
              // 自己还可购买的数量c = 每人活动限购数量a - 自己已经购买的数量b
              // 如果限购数量a>redis可购买数量d，当增加数量t>d, 提示超出库存
              // 如果限购数量a<=redis可购买数量d, 当增加数量t>a，提示超出限购
              let actInfo = th.data.sele_g;
              await th.get_buy_num2().then(function (data) {
                let limited = actInfo.buy_limit == 0 ? 100000 : actInfo.buy_limit; // 限购数量a
                let promcardbuynum = data.data.data.promcardbuynum;
                let buyedNum = promcardbuynum; // 自己已经购买的数量b
                let canBuyNum = limited - buyedNum; // 自己还可购买的数量c
                limitNum = limited;
                boughtNum = buyedNum;

                if (canBuyNum <= 0) {
                  canBuyNum = 0;
                };

                if (canBuyNum > res) {
                  if (curNum > res) { // t当前增减的数量
                    // wx.showModal({
                    // 	title: '超出活动库存',
                    // });
                    getApp().my_warnning('超出活动库存', 0, self);
                    th.setData({
                      goodsInputNum: res || 1
                    });
                    is_ok = 0;
                    return false;
                  };
                };

                if (canBuyNum <= res) {
                  if (curNum > canBuyNum) {
                    // wx.showModal({
                    // 	title: '超出限购数量',
                    // });
                    getApp().my_warnning('超出限购数量', 0, self);
                    th.setData({
                      goodsInputNum: canBuyNum || 1,
                    });
                    is_ok = 0;
                    return false;
                  }
                }
              })

            }
          })

        }
      }


      if (!is_ok) return false;



      if (action == "buy") {
        //--------------此时操作的数据------------
        var newd = {
          id: th.data.data.id,
          goods_num: th.data.goodsInputNum,
          pick_id: th.data.sto_sele_id,
          keyid: th.data.sto_sele_keyid,
        };
        newd['pick_name'] = th.data.sto_sele_name;
        newd['guide_id'] = getApp().globalData.guide_id;
        newd['guide_type'] = 0;

        if (getApp().globalData.groupchat_id) {
          newd['groupchat_id'] = getApp().globalData.groupchat_id;
        }
        if (this.data.prom_type && this.data.prom_type == 1) {
          newd['prom_type'] = this.data.prom_type;
          newd['prom_id'] = this.data.prom_id;
          newd['prom_price'] = this.data.prom_price;
        };

        if (this.data.prom_type == 1 && this.data.openSpecModal_flash_normal) {
          newd['prom_type'] = 0;
          newd['prom_price'] = this.data.data.shop_price;
        };

        console.log('newd++++++++', newd);
        th.buyNow(newd);
      } else {

        var newd = {
          service_id: th.data.data.id,
          service_sn: th.data.data.service_sn,
          service_name: th.data.data.goods_name,
          goods_num: th.data.goodsInputNum,
          pick_id: th.data.sto_sele_id,
          user_id: oo.user_id,
          store_id: os.stoid,
          money: th.data.data.shop_price,
        };
        if (getApp().globalData.guide_id) {
          newd['guide_id'] = getApp().globalData.guide_id;
          newd['guide_type'] = 0;
        };
        if (getApp().globalData.groupchat_id) {
          newd['groupchat_id'] = getApp().globalData.groupchat_id;
        }
        // 秒杀：单独购买的情况下，加入购物车显示的是零售价，否则显示秒杀活动价
        if (th.data.prom_type == 1) {
          newd['prom_type'] = th.data.prom_type;
          newd['prom_id'] = th.data.prom_id;
          if (th.data.openSpecModal_flash_normal) {
            newd['money'] = th.data.data.shop_price;
            newd['is_pd_normal'] = 1;
          } else {
            newd['money'] = th.data.prom_price;
          };
        };


        //----先看会员在购物车中是否加入了该商品-----
        getApp().request.get("/api/weshop/cartService/page", {
          data: {
            store_id: os.stoid,
            user_id: oo.user_id,
            service_id: th.data.data.id,
          },
          success: function (re) {
            //-------如果购物车中有相关的数据---------
            if (re.data.data.total > 0) {
              var item = null;
              // 多门店问题
              var cartGoodsNum = 0;
              const tmpObj = re.data.data.pageData;
              for (let i = 0; i < tmpObj.length; i++) {
                if (th.data.sto_sele_id != tmpObj[i].pick_id) {
                  cartGoodsNum += parseInt(tmpObj[i].goods_num);
                } else {
                  item = tmpObj[i];
                }
              }
              // 当前门店同类商品还没加入到购物车 但是有其他门店的同类商品
              if (th.data.prom_type == 1 && !th.data.is_normal && !item) {

                // 秒杀购物车购买 修正数量
                var snum = limitNum - boughtNum;
                if (snum <= 0) {
                  // wx.showModal({
                  // 	title: '超出限购数量',
                  // });
                  getApp().my_warnning('超出限购数量', 0, self);
                  return false;
                }

                var cSnum = snum - cartGoodsNum <= 0 ? 0 : snum - cartGoodsNum;
                var cRedisNums = redisNums - cartGoodsNum <= 0 ? 0 : redisNums - cartGoodsNum;

                if (newd['goods_num'] >= redisNums) {
                  if (redisNums > snum) {
                    newd['goods_num'] = cSnum;
                  } else {
                    newd['goods_num'] = cRedisNums;
                  }
                } else {
                  if (newd['goods_num'] > snum) newd['goods_num'] = cSnum;
                }

                if (newd['goods_num'] <= 0) {
                  getApp().my_warnning('加入购物车成功', 1, th, 450);
                  th.closeSpecModal();
                  return false;
                }
                getApp().request.post("/api/weshop/cartService/save", {
                  data: newd,
                  success: function (t) {
                    getApp().my_warnning('加入购物车成功', 1, th, 450);
                    var c_num = th.data.cartGoodsNum + th.data.goodsInputNum;
                    th.setData({
                      cartGoodsNum: c_num
                    });
                    th.closeSpecModal();
                  }
                });
                return false;
              }

              // 以下为当前门店同类商品已经加入到购物车
              var totalNum = th.data.goodsInputNum + item.goods_num;

              // 秒杀购物车购买 修正数量
              if (th.data.prom_type == 1 && !th.data.is_normal) {
                var snum = limitNum - boughtNum;
                if (snum <= 0) {
                  // wx.showModal({
                  // 	title: '超出限购数量',
                  // });
                  getApp().my_warnning('超出限购数量', 0, self);
                  return false;
                }
                if (totalNum >= redisNums) {
                  if (redisNums > snum) {
                    totalNum = snum - cartGoodsNum;
                  } else {
                    totalNum = redisNums - cartGoodsNum;
                  }
                } else {
                  if (totalNum > snum)
                    totalNum = snum - cartGoodsNum;
                }
              }

              var updata = {
                id: item.id,
                goods_num: totalNum,
                money: th.data.data.shop_price,
                store_id: os.stoid,
              };

              // 秒杀：单独购买的情况下，加入购物车显示的是零售价，否则显示秒杀活动价
              if (th.data.prom_type == 1) {
                // updata['prom_type'] = th.data.options.prom_type;
                // updata['prom_id'] = th.data.options.prom_id;
                if (th.data.openSpecModal_flash_normal) {
                  updata['money'] = th.data.data.shop_price;
                  updata['is_pd_normal'] = 1;
                } else {
                  updata['money'] = th.data.prom_price;
                };
              };

              if (getApp().globalData.guide_id) {
                updata['guide_id'] = getApp().globalData.guide_id;
                updata['guide_type'] = 1;
              }
              if (getApp().globalData.groupchat_id) {
                updata['groupchat_id'] = getApp().globalData.groupchat_id;
              }
              getApp().request.put("/api/weshop/cartService/update", {
                data: updata,
                success: function (t) {
                  getApp().my_warnning('加入购物车成功', 1, th, 450);
                  var c_num = th.data.cartGoodsNum + th.data.goodsInputNum;
                  th.setData({
                    cartGoodsNum: c_num
                  });
                  th.closeSpecModal();
                }
              });
            } else {
              getApp().request.post("/api/weshop/cartService/save", {
                data: newd,
                success: function (t) {
                  getApp().my_warnning('加入购物车成功', 1, th, 450);
                  var c_num = th.data.cartGoodsNum + th.data.goodsInputNum;
                  th.setData({
                    cartGoodsNum: c_num
                  });
                  th.closeSpecModal();
                }
              });
            }
          }
        });

      };







    },
    get_buy_num2: async function () {
      // var map = this.data.g_buy_num,
      var th = this,
        user_id = getApp().globalData.user_id;
      // if (user_id == null) {
      //     // map.set(gd.goods_id, 0);
      //     th.setData({
      //         // g_buy_num: map,
      //         prom_buy_num: 0,
      //     });
      //     "function" == typeof func && func();
      //     return false;
      // }


      //----获取商品购买数----

      //----获取活动购买数----
      return await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum", {
        data: {
          store_id: os.stoid,
          user_id: user_id,
          card_id: th.data.gid,
          prom_type: th.data.prom_type,
          prom_id: th.data.prom_id
        },
        //-----获取-----
        success: function (tt) {
          if (tt.data.code == 0) {
            // map.set(gd.goods_id, g_buy_num);
            th.setData({
              // g_buy_num: map,
              promcardbuynum: tt.data.data.promcardbuynum,
              cardbuynum: tt.data.data.cardbuynum,
            });
          }
        }
      });


    },

    //-- 加入购物的函数 --
    add_cart_func: function (t) {
      var i = getApp().request;
      if (oo.user_id == null) {
        wx.hideLoading();
        th.data.adding = 0;
        return s.my_warnning("还未登录！", 0, this);
      }

      if (!getApp().globalData.userInfo) {
        wx.hideLoading();
        th.data.adding = 0;
        return s.my_warnning("还未登录！", 0, this);
      }

      var e = this,
        th = e,
        a = 0,
        o = this.data.sele_g;
      a = o.goods_id;

      //----------添加到购物车时，要判断限购数量，--------
      e.get_buy_num(o, function (ee) {
        //---判断商品是否超出限购---
        if (th.data.g_buy_num != null && th.data.sele_g.viplimited > 0) {
          if (th.data.goodsInputNum + th.data.g_buy_num.get(th.data.sele_g.goods_id) > th.data.sele_g.viplimited) {
            wx.hideLoading();
            th.data.adding = 0;
            wx.showToast({
              title: '超出商品限购',
              icon: 'none',
            });
            // s.my_warnning('超出商品限购', 0, th);
            return false;
          }
        }
        //---判断商品是否超出活动限购---
        if ((th.data.prom_buy_num != -1 && th.data.prom_buy_limit > 0) && !th.data.is_normal) {
          if (th.data.goodsInputNum + th.data.prom_buy_num > th.data.prom_buy_limit) {
            wx.hideLoading();
            th.data.adding = 0;
            wx.showToast({
              title: '超出商品活动限购',
              icon: 'none',
            });
            // s.my_warnning('超出商品活动限购', 0, th);
            return false;
          }
        }

        if (th.data.goodsInputNum <= 0) {
          wx.hideLoading();
          th.data.adding = 0;
          return s.my_warnning("商品数量不能为0", 0, th);
        }
        if (th.data.sto_sele_name == null || th.data.sto_sele_name == undefined)
          th.setData({
            sto_sele_name: ""
          });
        if (th.data.sto_sele_name == "") {
          wx.hideLoading();
          th.data.adding = 0;
          return s.my_warnning("请选择门店", 0, th);
        }

        //--------------此时操作的数据------------
        var newd = {
          goods_id: o.goods_id,
          goods_num: th.data.goodsInputNum,
          pick_id: th.data.sto_sele_id,
          user_id: oo.user_id,
          store_id: th.data.stoid,
          goods_price: o.shop_price,
          member_goods_price: o.shop_price,
          goods_name: o.goods_name,
          goods_sn: o.goods_sn,
          sku: o.sku,
          prom_id: th.data.sele_g.prom_id,
          prom_type: th.data.sele_g.prom_type,
        };

        //-- 代发商品不参加优惠 --
        if (th.data.sele_g.whsle_id) {
          newd.prom_type = 0;
          newd.prom_id = 0;
        }

        //---是不是从收藏夹出来的---
        if (th.data.c_guide_id) {
          newd['guide_id'] = th.data.c_guide_id;
          newd['guide_type'] = 2;
          if ("add" == t.currentTarget.dataset.action) newd['guide_type'] = 3;
        } else {
          if (getApp().globalData.guide_id) {
            newd['guide_id'] = getApp().globalData.guide_id;
            newd['guide_type'] = 0;
            if ("add" == t.currentTarget.dataset.action) newd['guide_type'] = 1;
          }
        }
        if (getApp().globalData.groupchat_id) {
          newd['groupchat_id'] = getApp().globalData.groupchat_id;
        }
        //让商品带上房间号
        //让商品带上房间号
        if (!th.data.sys_switch.is_skuroom_id && th.data.sys_switch.is_skuroom_id == 1) {
          if (th.data.data.goods_id == getApp().globalData.room_goods_id) {
            newd.room_id = getApp().globalData.room_id;
          }
        } else {
          if (newd.goods_id == getApp().globalData.room_goods_id) newd.room_id = getApp().globalData.room_id;
        }

        //如果是积分够，is_integral_normal就要有积分购普通购买字段
        if (th.data.openSpecModal_inte_normal == 1 && th.data.prom_type == 4) {
          newd.is_integral_normal = 1;
        }

        //如果有线下取价
        if (o.offline_price) {
          newd.offline_price = o.offline_price;
          newd.pricing_type = o.pricing_type;
        }


        //获取到优惠测序类型
        //-----如果是秒杀，团购，积分购,拼团-----
        if (th.data.prom_type == 1 || th.data.prom_type == 2) {

          if (th.data.openSpecModal_flash_normal) {

            newd.prom_type = 0;
            newd.prom_id = 0;
            newd.is_pd_normal = 1;
            //---如果是线下门店销售的时候---
            if (th.data.sales_rules >= 2) {
              var pick = th.get_pick_from_list(th.data.sto_sele_id)
              //---通过接口获取门店的线下库存信息--
              th.check_CanOutQty(th.data.sele_g, pick, function (CanOutQty) {
                if (CanOutQty) {
                  if (CanOutQty < e.data.goodsInputNum) {
                    wx.hideLoading();
                    th.data.adding = 0;
                    wx.showToast({
                      title: '库存不足！',
                      icon: 'none',
                    });
                    return false;
                  }

                  th.add_cart_next(e, t, a, o, newd, CanOutQty);
                } else {
                  wx.hideLoading();
                  th.data.adding = 0;
                  wx.showToast({
                    title: '库存不足！',
                    icon: 'none',
                  });
                  return false;
                }
              })


            } else {
              if (o.store_count <= 0) {
                wx.hideLoading();
                th.data.adding = 0;
                wx.showToast({
                  title: '库存已为空！',
                  icon: 'none'
                });
                return false;
              }
              if (o.store_count < e.data.goodsInputNum) {
                wx.hideLoading();
                th.data.adding = 0;
                wx.showToast({
                  title: '库存不足！',
                  icon: 'none',
                });
                return false;
                // return s.my_warnning("库存不足！", 0, th);
              }
              th.add_cart_next(e, t, a, o, newd); //加入购物车下一步
            };
            return false;
          }

          newd.goods_price = th.data.prom_price;
          newd.member_goods_price = th.data.prom_price,
            newd.prom_type = th.data.prom_type;
          newd.prom_id = th.data.prom_id;

          if (o.store_count <= 0) {
            wx.hideLoading();
            th.data.adding = 0;
            wx.showToast({
              title: '库存已为空！',
              icon: 'none',
            });
            return false;
          }
          if (o.store_count < e.data.goodsInputNum) {
            wx.hideLoading();
            th.data.adding = 0;
            wx.showToast({
              title: '库存不足！',
              icon: 'none',
            });
            return false;
          }
          th.add_cart_next(e, t, a, o, newd); //加入购物车下一步

        }
        // else if (o.prom_type == 7) {
        //
        //   //判断进行中的活动，是不是要判断线下库存
        //   th.check_zh_acting(function (ee) {
        //       newd.prom_id = 0;
        //       newd.prom_type = 0;
        //       if (ee && th.data.sele_g.act) {
        //         newd.prom_id = th.data.sele_g.act.id;
        //         newd.prom_type = 7;
        //         if (o.store_count <= 0) {
        //           wx.hideLoading();
        //           th.data.adding=0;
        //           wx.showToast({
        //             title: '库存已为空！',
        //             icon: 'none',
        //           });
        //           return false;
        //         };
        //         if (o.store_count < e.data.goodsInputNum) {
        //           wx.hideLoading();
        //           th.data.adding=0;
        //           wx.showToast({
        //             title: '库存不足！',
        //             icon: 'none',
        //           });
        //           return false;
        //           //return s.my_warnning("库存不足！", 0, th);
        //         };
        //         th.add_cart_next(e, t, a, o, newd); //加入购物车下一步
        //         return false;
        //       } else {
        //         //---如果是线下门店销售的时候---
        //         if (!th.data.sele_g.whsle_id && th.data.sales_rules >= 2) {
        //           var pick = th.get_pick_from_list(th.data.sto_sele_id)
        //
        //           th.check_CanOutQty(th.data.sele_g, pick, function (CanOutQty) {
        //             if (CanOutQty) {
        //
        //               if (CanOutQty < e.data.goodsInputNum) {
        //                 wx.hideLoading();
        //                 th.data.adding=0;
        //                 wx.showToast({
        //                   title: '库存不足！',
        //                   icon: 'none',
        //                 });
        //                 return false;
        //               }
        //
        //               th.add_cart_next(e, t, a, o, newd, CanOutQty);
        //             } else {
        //               wx.hideLoading();
        //               th.data.adding=0;
        //               wx.showToast({
        //                 title: '库存不足！',
        //                 icon: 'none',
        //               });
        //               return false;
        //             }
        //           })
        //
        //         } else {
        //           if (o.store_count <= 0) {
        //             wx.hideLoading();
        //             th.data.adding=0;
        //             wx.showToast({
        //               title: '库存已为空！',
        //               icon: 'none',
        //             });
        //             return false;
        //             //return s.my_warnning("库存已为空！", 0, th);
        //           };
        //           if (o.store_count < e.data.goodsInputNum) {
        //             wx.hideLoading();
        //             th.data.adding=0;
        //             wx.showToast({
        //               title: '库存不足！',
        //               icon: 'none',
        //             });
        //             return false;
        //             //return s.my_warnning("库存不足！", 0, th);
        //           };
        //           th.add_cart_next(e, t, a, o, newd); //加入购物车下一步
        //         }
        //       }
        //     })
        // }
        //要包含积分购的普通购买0 3,5,7,10,  is_integral_normal积分普通购买字段
        else if ([0, 3, 5, 7, 10].indexOf(th.data.prom_type) > -1 || newd.is_integral_normal) {
          newd.prom_type = 0;
          newd.prom_id = 0;

          //---如果是线下门店销售的时候---
          if (th.data.sales_rules >= 2 && !th.data.sele_g.whsle_id) {
            var pick = th.get_pick_from_list(th.data.sto_sele_id)
            //---通过接口获取门店的线下库存信息--
            th.check_CanOutQty(th.data.sele_g, pick, function (CanOutQty) {
              if (CanOutQty) {

                if (CanOutQty < e.data.goodsInputNum) {
                  wx.hideLoading();
                  th.data.adding = 0;
                  wx.showToast({
                    title: '库存不足！',
                    icon: 'none',
                  });
                  return false;
                }

                th.add_cart_next(e, t, a, o, newd, CanOutQty);
              } else {
                wx.hideLoading();
                wx.showToast({
                  title: '库存不足！',
                  icon: 'none',
                });
                return false;
              }
            })

          } else {
            if (o.store_count <= 0) {
              wx.hideLoading();
              wx.showToast({
                title: '库存已为空！',
                icon: 'none',
              });
              return false;
              //return s.my_warnning("库存已为空！", 0, th);
            };
            if (o.store_count < e.data.goodsInputNum) {
              wx.hideLoading();
              wx.showToast({
                title: '库存不足！',
                icon: 'none',
              });
              return false;
              //return s.my_warnning("库存不足！", 0, th);
            }
            th.add_cart_next(e, t, a, o, newd); //加入购物车下一步
          }
        }



      })
    },

    //---加入购物车的最后一步---
    async add_cart_next(e, t, a, o, newd, CanOutQty) {


      if (getApp().globalData.groupchat_id) {
        newd.groupchat_id = getApp().globalData.groupchat_id
      }
      var th = this,
        i = getApp().request;
      //---如果商品不是积分购和拼团,要判断一个是否要进行等级价的判断------
      if ((o.prom_type != 6 && o.prom_type != 4 && o.prom_type != 2 && o.prom_type != 1) || th.data.is_normal) {
        var conf = th.data.bconfig;
        if (conf.switch_list && getApp().globalData.userInfo['card_field'] && getApp().globalData.userInfo['card_expiredate']) {
          var s_list = JSON.parse(conf.switch_list);
          var now = ut.gettimestamp();


          var str = getApp().globalData.userInfo['card_expiredate'].replace(/-/g, '/');
          var end = new Date(str);
          end = Date.parse(end) / 1000;


          //--如果后台有开启等级价的功能，而且会员的等级没有过期的情况下--
          if (parseInt(s_list.rank_switch) == 2 && end > now) {
            var card_price = o[getApp().globalData.userInfo['card_field']];
            //如果会员有等级价
            if (getApp().globalData.userInfo['card_field'] != undefined && getApp().globalData.userInfo['card_field'] != null &&
              getApp().globalData.userInfo['card_field'] != "" && card_price > 0) {
              newd.goods_price = card_price;
              newd.member_goods_price = card_price;
            }
          }
        }
      }

      //if (this.data.data.goods.is_virtual) return this.buyVirtualGoods(d);
      if ("add" == t.currentTarget.dataset.action) {

        if ([3, 5, 7, 10].indexOf(newd.prom_type) > -1) {
          newd.prom_type = 0;
          newd.prom_id = 0;
        }
        if(newd.prom_type==0){
          //-- 要拿一下商品有没有组合购活动 ---
          var rq_url = '/api/weshop/activitylist/listGoodActInfo2New';
          var req_d = {
            "store_id": os.stoid,
            "goods_id": a,
            "user_id": getApp().globalData.user_id,
          }

          var ck_res= await getApp().request.promiseGet(rq_url, {
            data: req_d,
          });

          if (ck_res.data.code == 0 && ck_res.data.data && ck_res.data.data.length > 0) {
            var arr = ck_res.data.data;
            var arr3 = arr.filter(function (e) {
              return e.s_time < ut.gettimestamp() && e.prom_type == 7;
            })

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


        wxlog.info(getApp().globalData.user_id + '-加入购物车:' + JSON.stringify(newd));
        //
        // //如果有搭配购的时候的时候
        // if(th.data.collocationGoods  && newd.prom_type==0){
        //   newd.prom_type = 5;
        //   newd.prom_id = th.data.collocationGoods.id;
        // }
        //
        // //如果有搭配购的时候的时候
        // if(th.data.zh_act && (!th.data.zh_act.zh_num || th.data.zh_act.zh_buy_num>th.data.zh_act.zh_num )  && newd.prom_type==0){
        //   newd.prom_type = 7;
        //   newd.prom_id = th.data.zh_act.id;
        // }      

        //----先看会员在购物车中是否加入了该商品-----
        i.get("/api/weshop/cart/page", {
          data: {
            store_id: e.data.stoid,
            user_id: oo.user_id,
            goods_id: a,
            pick_id: e.data.sto_sele_id,
            prom_type: newd.prom_type,
            prom_id: newd.prom_id,
            state: 0,
          },
          success: function (re) {

            //-- 判断活动是不是一样 --
            var item = null;
            //-------如果购物车中有相关的数据---------
            if (re.data.data.total > 0) {
                for (var j = 0; j < re.data.data.pageData.length; j++) {
                  if (!th.check_is_like(re.data.data.pageData[j], newd)) continue;
                  item = re.data.data.pageData[j];
                  break;
                }
            }

            if (item) {
              item = re.data.data.pageData[0];
              //判断数量，要看下购物车中有没有该商品
              if (CanOutQty) {
                if (item.goods_num + th.data.goodsInputNum > CanOutQty) {
                  wx.hideLoading();
                  th.data.adding = 0;
                  wx.showToast({
                    title: '库存不足！',
                    icon: 'none',
                  });
                  return false;
                  // return s.my_warnning("库存不足！", 0, th);
                }
              } else {
                if (item.goods_num + th.data.goodsInputNum > o.store_count) {
                  wx.hideLoading();
                  th.data.adding = 0;
                  wx.showToast({
                    title: '库存不足！',
                    icon: 'none',
                  });
                  return false;
                  //return s.my_warnning("库存不足！", 0, th);
                }

                //秒杀有限购的时候，同时不是普通购买
                if (item.goods_num + th.data.goodsInputNum + th.data.prom_buy_num > th.data.prom_buy_limit && th.data.prom_buy_limit > 0 && !newd.is_pd_normal && (th.data.prom_type == 1 || th.data.prom_type == 2)) {
                  wx.hideLoading();
                  th.data.adding = 0;
                  wx.showToast({
                    title: '此商品已在购物车，去购物车结算！',
                    icon: 'none',
                  });
                  return false;
                  //return s.my_warnning("库存不足！", 0, th);
                }
              }

              if(newd.zh_prom_id>0 && item.zh_prom_id && newd.zh_prom_id!=item.zh_prom_id){
                wx.hideLoading();
                wx.showModal({
                  title: '温馨提示',
                  content: '当前商品已在购物车，是否替换参与该活动？',
                  success(res) {
                    if (res.confirm) {
                      wx.showLoading();
                      th.add_cart_next2(e,item,newd);
                    }else{
                      th.data.adding = 0;
                    }
                  }
                })

              }else{
                th. add_cart_next2(e,item,newd);
              }



            } else {
              getApp().request.post("/api/weshop/cart/save", {
                data: newd,
                success: function (t) {
                  wx.hideLoading();
                  th.data.adding = 0;
                  getApp().my_warnning('加入购物车成功', 1, th, 450);
                  var c_num = th.data.cartGoodsNum + e.data.goodsInputNum;
                  th.setData({
                    cartGoodsNum: c_num
                  });
                  th.closeSpecModal();
                }
              });
            }
          }
        });

      } else {

        newd['pick_name'] = th.data.sto_sele_name;
        newd['pick_dis'] = th.data.sto_sele_distr;
        th.buyNow(newd);

      }
    },


    add_cart_next2(e,item,newd){
      let th=this;
      var updata = {
        id: item.id,
        goods_num: e.data.goodsInputNum + item.goods_num,
        goods_price: newd.goods_price,
        member_goods_price: newd.goods_price,
        store_id: th.data.stoid,
        prom_id: newd.prom_id, //把活动id带上去(用于购物车失效变成有效商品)
        prom_type: newd.prom_type
      };

      if (newd.is_pd_normal) {
        updata.is_pd_normal = 1
      }

      if (newd.zh_prom_id) {
        updata.zh_prom_id = newd.zh_prom_id
      }

      //---是不是从收藏夹出来的---
      if (th.data.c_guide_id) {
        updata['guide_id'] = th.data.c_guide_id;
        updata['guide_type'] = 3; //加入购物车之后就变成了3
      } else {
        if (getApp().globalData.guide_id) {
          updata['guide_id'] = getApp().globalData.guide_id;
          updata['guide_type'] = 0;
        }
      }
      if (getApp().globalData.groupchat_id) {
        updata['groupchat_id'] = getApp().globalData.groupchat_id;
      }

      getApp().request.put("/api/weshop/cart/update", {
        data: updata,
        success: function (t) {
          wx.hideLoading();
          th.data.adding = 0;
          getApp().my_warnning('加入购物车成功', 1, th, 450);
          var c_num = th.data.cartGoodsNum + th.data.goodsInputNum;
          th.setData({
            cartGoodsNum: c_num
          });
          th.closeSpecModal();
        }
      });

    },

    //-------------获取购买数量的总函数----------------
    get_buy_num: function (gd, func) {
      var map = this.data.g_buy_num,
        th = this,
        user_id = getApp().globalData.user_id;
      if (user_id == null) {
        map.set(gd.goods_id, 0);
        th.setData({
          g_buy_num: map,
          prom_buy_num: 0,
        });
        "function" == typeof func && func();
        return false;
      }

      if (map.has(gd.goods_id)) {
        "function" == typeof func && func();
      } else {
        //----获取商品购买数----
        getApp().request.get("/api/weshop/ordergoods/getUserBuyGoodsNum", {
          data: {
            store_id: os.stoid,
            user_id: user_id,
            goods_id: gd.goods_id, isnew: 1,
            timetype:gd.viplimited_timetype
          },
          success: function (t) {
            if (t.data.code == 0) {
              var g_buy_num = t.data.data.goodsbuynum;

              //如果是秒杀的时候
              if (th.data.prom_type == 0 && gd.prom_type == 1) {
                gd.prom_type = 0;
              }
              //如果全场优惠，商品做了秒杀
              if (th.data.prom_type == 3 && gd.prom_type == 1) {
                gd.prom_type = 0;
              }
              //如果全场阶梯优惠，商品做了秒杀
              if (th.data.prom_type == 10 && gd.prom_type == 1) {
                gd.prom_type = 0;
              }


              if (!th.data.is_normal && (gd.prom_type == 1 || gd.prom_type == 2 || gd.prom_type == 4 || gd.prom_type == 6)) {
                //----获取活动购买数----
                getApp().request.get("/api/weshop/ordergoods/getUserBuyGoodsNum", {
                  data: {
                    store_id: os.stoid,
                    user_id: user_id,
                    goods_id: gd.goods_id,
                    prom_type: gd.prom_type,
                    prom_id: gd.prom_id, isnew: 1
                  },
                  //-----获取-----
                  success: function (tt) {
                    if (tt.data.code == 0) {
                      map.set(gd.goods_id, g_buy_num);
                      th.setData({
                        g_buy_num: map,
                        prom_buy_num: tt.data.data.promgoodsbuynum,
                      });
                      "function" == typeof func && func();
                    }
                  }
                });
              } else {
                map.set(gd.goods_id, g_buy_num);
                th.setData({
                  g_buy_num: map
                });
                "function" == typeof func && func();
              }
            }
          }
        });
      }
    },
    //---  获取卡类列表 ---
    getPlusCardType: function (func) {
      var storid = os.stoid;
      var th = this;
      var user = getApp().globalData.userInfo;
      if (!user) return false;
      getApp().request.promiseGet("/api/weshop/plus/vip/mem/bership/list?" + "storeId=" + storid, {}).then(res => {
        var plusCard = res.data.data;
        var arr = [1219, 2089, 3031];
        var new_arr = new Array();
        var card_name_map = new Map();

        var list = [];
        for (var i = 0; i < plusCard.length; i++) {
          if ((!user || user.card_field == null || user.card_field == "") && plusCard[i].IsStopBuy == true) continue;
          var name = "card" + plusCard[i].CorrPrice.toLowerCase();
          card_name_map.set(name, plusCard[i].CardName);
          list.push(plusCard[i]);
        }

        var ob = {
          "card_list": list,
          "name_map": card_name_map
        };
        func(ob);
      })
    },


    //----------增加购买数量-----------
    addCartNum: function (t) {
      var add_num = 1;
      var p_type = parseInt(this.data.prom_type)
      if ([1, 2, 4, 6, 8, 9].indexOf(p_type) == -1 || this.data.openSpecModal_inte_normal == 1 || this.data.is_normal == 1) {
        add_num = getApp().get_limit_qty(this.data.sele_g, this.data.is_act, 1);
      }

      this.checkCartNum(this.data.goodsInputNum + add_num);
    },
    //------检查数量是不是超出限购------
    checkCartNum: function (t) {
      var th = this;

      var mo_num = getApp().get_limit_qty(th.data.sele_g, th.data.is_act);
      var steep = getApp().get_limit_qty(th.data.sele_g, th.data.is_act, 1);
      this.get_buy_num(this.data.sele_g, async function () {

        var is_show_bs = 0;
        var l_num = -1;

        //--判断商品是否超出限购--
        if (th.data.g_buy_num != null && th.data.sele_g.viplimited > 0) {

          var gd_buy_num = th.data.g_buy_num.get(th.data.sele_g.goods_id);

          if (t + gd_buy_num > th.data.sele_g.viplimited) {
            wx.showToast({
              title: '超出商品限购',
              icon: 'none',
            });

            is_show_bs = 1;

            // s.my_warnning('超出商品限购', 0, th);
            l_num = th.data.sele_g.viplimited - gd_buy_num;
            if (l_num < 0) l_num = 0;
            // th.setData({
            //   goodsInputNum: num
            // })
            // return false;
          }
        }

        //如果是普通购买的情况下
        if (th.data.openSpecModal_flash_normal) th.data.is_normal = 1;

        //--判断商品是否超出活动限购--
        if (th.data.prom_buy_num != -1 && th.data.prom_buy_limit > 0 && !th.data.is_normal) {
          if (t + th.data.prom_buy_num > th.data.prom_buy_limit) {
            wx.showToast({
              title: '超出商品活动限购',
              icon: 'none',
            });
            // s.my_warnning('超出商品活动限购', 0, th);
            var num = th.data.prom_buy_limit - th.data.prom_buy_num;
            if (num < 0) num = 0;
            th.setData({
              goodsInputNum: num
            })
            return false;
          }
        }

        if ((th.data.sele_g.prom_type == 1 || th.data.sele_g.prom_type == 2 || th.data.sele_g.prom_type == 6) && !th.data.is_normal) {
          var redis_num = 0;
          //------判断活动是否抢光-----
          await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" +
            os.stoid + "/" + th.data.sele_g.prom_type + "/" + th.data.sele_g.prom_id, {
            1: 1
          }).then(res => {
            redis_num = res.data.data;
          });

          if (t > redis_num) {
            wx.showToast({
              title: '超出商品活动库存',
              icon: 'none',
            });
            // s.my_warnning('超出商品活动库存', 0, th);
            th.setData({
              goodsInputNum: redis_num
            })
            return false;
          }
        }
        var e = th.data.sele_g.store_count;
        var p_type = parseInt(th.data.prom_type + ''); //&& p_type!=1 && p_type!=4
        if (!th.data.sele_g.whsle_id && th.data.sales_rules >= 2 &&
          ([1, 2, 4, 6, 8, 9].indexOf(p_type) == -1 || th.data.openSpecModal_inte_normal == 1 || th.data.is_normal == 1)) {

          //-- 如果是虚拟商品，默认给最大值 --
          if (getApp().is_virtual(th.data.sele_g)) {
            e = 100000;
          } else {
            if (!th.data.def_pick_store) {
              wx.showToast({
                title: '请选择门店',
                icon: 'none',
              });
              // wx.showModal({title: '请选择门店',});
              return false;
            } else {
              e = th.data.def_pick_store.CanOutQty;
            }
          }
        }

        //-- 限购数量也要进行计算一下 --
        if (l_num > -1) {
          if (e > l_num) e = l_num;
        }

        //--- 促销活动也不控制起订量, 这里很重要的一个控制，起订量的 ----
        if ([0, 3, 5, 7, 10].indexOf(p_type) > -1 || th.data.openSpecModal_inte_normal == 1 || th.data.is_normal == 1) {
          if (t < mo_num) {
            t = mo_num;
            if (!is_show_bs) {
              wx.showToast({
                title: '购买数未达到起订量',
                icon: 'none',
              });
            }
            is_show_bs = 1;
          }
          if (t > mo_num && (t - mo_num) % steep != 0) {

            if (!is_show_bs) {
              wx.showToast({
                title: '购买数必须是起订量的倍数',
                icon: 'none',
              });
            }

            t = mo_num + parseInt((t - mo_num) / steep) * steep + steep;
            is_show_bs = 1;
          }
        }

        if (!e) e = 0;
        //库存不足，不增加
        if (e < t) {
          if (!is_show_bs) {
            wx.showToast({
              title: '库存不足',
              icon: 'none',
            });
          }

          // wx.showModal({title: '库存不足',});
          if (e < 0) e = 0;

          //只有普通商品才有起购数
          if ([1, 2, 4, 6, 8, 9].indexOf(p_type) == -1 || th.data.openSpecModal_inte_normal == 1 || th.data.is_normal == 1) {
            if (e < mo_num) e = mo_num;
            if (e > mo_num && (e - mo_num) % steep != 0) {
              e = mo_num + parseInt((e - mo_num) / steep) * steep;
            }
          }
          th.setData({
            goodsInputNum: e
          });
          return false;
        }

        //var steep=getApp().get_limit_qty(th.data.sele_g,0,1);
        t > e || 0 == e ? t = e : t < 1 && (t = 1);


        //只有普通商品才有起购数
        if ([1, 2, 4, 6, 8, 9].indexOf(p_type) == -1 || th.data.openSpecModal_inte_normal == 1 || th.data.is_normal == 1) {
          if (t < mo_num) t = mo_num;
        }


        th.setData({
          goodsInputNum: t
        });
        th.is_show_more_buy();

      })
    },
    is_show_more_buy: async function () {
      var prom_goods = this.data.prom_goods;
      if (!prom_goods) return false;
      //如果系统默认的顺序不是以优惠促销为默认第一位的时候
      if (this.check_prom_custom(1) !== 3) {
        return false;
      }

      if (!this.data.sele_g) return false;

      var per_price = this.data.sele_g.shop_price
      if (this.data.card_field && this.data.sele_g[this.data.card_field] > 0) {
        per_price = this.data.sele_g[this.data.card_field];
      }

      var all_price = per_price * this.data.goodsInputNum;
      var con = null;
      for (var i in prom_goods) {
        var item = prom_goods[i];
        if (item.prom_type == 1) {
          if (item.condition > this.data.goodsInputNum) {
            con = item;
            con.need = (item.condition - this.data.goodsInputNum).toFixed(2) + "件";
            break;
          }
        } else {
          if (parseFloat(item.condition) > parseFloat(parseFloat(all_price).toFixed(2))) {
            con = item;
            con.need = (item.condition - all_price).toFixed(2) + "元";
            break;
          }
        }
      }
      //获取用户参与优惠促销的次数
      //if(con && con.prom_id){
      //await this.getUserBuyPromNum_pre(con.prom_id);
      //}
      this.setData({
        hui_condition: con
      });

    },

    //----------减少购买数量-----------
    subCartNum: function (t) {
      var add_num = 1;
      var p_type = parseInt(this.data.prom_type)
      if ([1, 2, 4, 6, 8, 9].indexOf(p_type) == -1 || this.data.openSpecModal_inte_normal == 1 || this.data.is_normal == 1) {
        add_num = getApp().get_limit_qty(this.data.sele_g, this.data.is_act, 1);
        var mo_num = getApp().get_limit_qty(this.data.sele_g, this.data.is_act);
        if (this.data.goodsInputNum - add_num < mo_num) {
          wx.showToast({
            title: '购买数量不能小于起订量',
            icon: 'none',
          });
          return false;
        }
      }
      this.checkCartNum(this.data.goodsInputNum - add_num);
    },
    //----------输入框输入购买数量-----------
    inputCartNum: function (t) {
      this.checkCartNum(Number(t.detail.value));
    },
    //统一一下获取线下库存的函数
    async check_CanOutQty(goodsinfo, item, func) {

      var sales_rules = this.data.sales_rules;
      //如果默认是商品
      if (getApp().is_virtual(goodsinfo)) {
        return func(100000);
      }

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

      if (sales_rules == 2) {
        lock_rq.storageId = item.pickup_id
      } else {
        lock_rq.appoint_pick_keyid = encodeURIComponent(this.data.appoint_pick_keyid)
      }

      var lock = 0;
      var CanOutQty = 0;
      var plist = null;
      //先读取门店的lock
      await getApp().request.promiseGet("/api/weshop/order/ware/lock/page", {
        data: lock_rq
      }).then(res => {
        if (res.data.code == 0 && res.data.data.total > 0) {
          for (var i in res.data.data.pageData)
            lock += res.data.data.pageData[i].outQty;
        }
      })

      var sto_req = {
        wareIds: encodeURIComponent(goodsinfo.erpwareid),
        storeId: os.stoid
      }
      if (sales_rules == 2) {
        sto_req.storageNos = item.pickup_no
      } else {
        sto_req.storageIds = encodeURIComponent(this.data.appoint_pick_keyid)
      }



      //读取线下的门店库存
      await getApp().request.promiseGet("/api/weshop/goods/getWareStorages", {
        data: sto_req
      }).then(res => {
        if (res.data.code == 0 && res.data.data.total > 0) {
          plist = res.data.data.pageData[0];
        }
      })

      if (plist && plist.CanOutQty - lock > 0) {
        CanOutQty = plist.CanOutQty - lock;
      }

      if (func) func(CanOutQty);

    },
    //获取更多秒杀
    get_more_flahs: async function (func) {
      var f_more = false;
      var user_id = getApp().globalData.user_id;
      if (!user_id) user_id = 0;

      var url = "/api/weshop/goods/listSkuFlash?store_id=" + os.stoid + "&goods_id=" + this.data.data.goods_id + "&user_id=" + user_id;
      //获取秒杀的多规格
      await getApp().request.promiseGet(url, {}).then(res => {
        if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
          f_more = res.data.data;
        }
      })
      if (!f_more) {
        func(false);
        return false;
      }
      //-- 秒杀的价格要更新 --
      for (let i in f_more) {

        let item = f_more[i];
        f_more[i].prom_id = item.act_id;
        f_more[i].prom_type = 1;

        var url = "/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + item.act_id;
        await getApp().request.promiseGet(url, {}).then(rs => {
          if (rs.data.code == 0 && rs.data.data) {
            f_more[i].price = rs.data.data.user_price;
            f_more[i].is_pickup = rs.data.data.is_pickup;
            f_more[i].pick_up_lists = rs.data.data.pick_up_lists;
          }
        })
      }
      func(f_more);

    },
    //获取redis中的数量
    async getactLen(func) {
      var r_num = 0,
        prom_type = this.data.prom_type,
        prom_id = this.data.prom_id;
      await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/" + prom_type + "/" + prom_id, {
        1: 1
      }).then(res => {
        var em = res;
        if (em.data.code == 0) {
          r_num = em.data.data;
        }
      })
      func(r_num);
    },
    //获取redis中的数量
    async getactLenser() {
      let prom_type = this.data.prom_type;
      let prom_id = this.data.prom_id;
      return await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/" + prom_type + "/" + prom_id, {
        1: 1
      }).then(res => {
        if (res.data.code == 0) {
          // 当前可以购买的数量
          let r_num = res.data.data;
          return r_num;
        };
      })
    },

    //因为在购物车  普通商品和 优惠促销，搭配购，组合购 阶梯购是一样的
    check_is_like(e, newd, idx) {
      if (e.prom_type == newd.prom_type) return true;
      if (!idx) {
        if (e.prom_type == 0) {
          if ([3, 5, 7, 10].indexOf(newd.prom_type) > -1) return true;
        }
        if (newd.prom_type == 0) {
          if ([3, 5, 7, 10].indexOf(e.prom_type) > -1) return true;
        }
      }
      return false;
    },
    //----------增加购买数量-----------
    addCartNumser: function (t) {
      this.checkCartNumser(this.data.goodsInputNum + 1);
    },
    //----------减少购买数量-----------
    subCartNumser: function (t) {
      this.checkCartNumser(this.data.goodsInputNum - 1);
    },
    //----------输入框输入购买数量-----------
    inputCartNumser: function (t) {
      this.checkCartNumser(Number(t.detail.value));
    },

    //------检查数量是不是超出限购------
    checkCartNumser: async function (t) {
      var th = this;

      if (!th.data.def_pick_store) {
        wx.showModal({ title: '请选择门店', });
        return false;
      };

      // 非秒杀活动
      if (this.data.prom_type != 1) {
        this.setData({
          goodsInputNum: t,
        });
      };

      // 秒杀活动
      if (this.data.prom_type == 1) {
        // 如果是秒杀活动下的单独购买，is_normal为1
        if (this.data.openSpecModal_flash_normal) this.data.is_normal = 1;

        if (this.data.is_normal) {// 单独购买
          this.setData({
            goodsInputNum: t,
          });
        } else {// 秒杀购买

          // 获取redis当前可以购买的数量
          // 如果数量为0，设置和显示已抢光
          // 否则，进一步判断是否超出限购或超出库存
          await this.getactLenser().then(async function (res) {
            // res: redis可购买数量
            // console.log('当前可以购买的数量:', res);
            if (res <= 0) {
              // 可购买数量<=0, 设置和显示已抢光
              th.setData({
                prom_r_null: 1,
              });
            } else {
              // 可购买数量>0
              // 计算自己还可以购买的数量
              // 自己还可购买的数量c = 每人活动限购数量a - 自己已经购买的数量b
              // 如果限购数量a>redis可购买数量d，当增加数量t>d, 提示超出库存
              // 如果限购数量a<=redis可购买数量d, 当增加数量t>a，提示超出限购
              let actInfo = th.data.sele_g;
              await th.get_buy_num2().then(function (data) {
                let limited = actInfo.buy_limit == 0 ? 100000 : actInfo.buy_limit; // 限购数量a
                let promcardbuynum = data.data.data.promcardbuynum;
                let buyedNum = promcardbuynum; // 自己已经购买的数量b
                let canBuyNum = limited - buyedNum; // 自己还可购买的数量c

                if (canBuyNum <= 0) {
                  canBuyNum = 0;
                };

                if (limited > res) {
                  if (t > res) { // t当前增减的数量
                    // wx.showModal({
                    // 	title: '超出活动库存',
                    // });
                    getApp().my_warnning('超出活动库存', 0, self);
                    th.setData({
                      goodsInputNum: res || 1,
                    });
                    return false;
                  };
                };

                if (limited <= res) {
                  if (t > canBuyNum) {
                    // wx.showModal({
                    // 	title: '超出限购数量',
                    // });
                    getApp().my_warnning('超出限购数量', 0, self);
                    th.setData({
                      goodsInputNum: canBuyNum || 1,
                    });
                    return false;
                  };
                };

                th.setData({
                  goodsInputNum: t,
                });
              });
            };
          });

        }


      };











      // var e = th.data.sele_g.goods_num;
      // var p_type = th.data.prom_type; //&& p_type!=1 && p_type!=4
      // if (th.data.sales_rules == 2 && (p_type != 1 && p_type != 4 && p_type != 6 || th.data.openSpecModal_inte_normal == 1 || th.data.is_normal == 1)) {
      //     if (!th.data.def_pick_store) {
      //         wx.showModal({title: '请选择门店',});
      //         return false;
      //     } else {
      //         e = th.data.def_pick_store.CanOutQty;
      //     }
      // }


      // th.setData({goodsInputNum: t});

      // });


    },
    //-----------选择属性的按钮事件----------
    sele_spec: function (e) {

      //如果只有一个规格直接结束
      if ((this.data.sku_g && this.data.sku_g.length == 1) || (this.data.sku_g_pt && this.data.sku_g_pt.length == 1)) {
        return
      }
      if (this.data.sp_seleing) {
        return false;
      }

      this.setData({ sp_seleing: 1 })

      var that = this;
      var th = this;

      //在切换规格的时候，指定门店不匹配的状态要清理
      if (th.data.def_pick_store && JSON.stringify(th.data.def_pick_store) != '{}') {
        th.data.def_pick_store.is_no_dis_nor = 0;
        that.setData({
          def_pick_store: th.data.def_pick_store
        })
      }

      //切换完商品后，海报图片都要跟换
      this.data.share_goods_img = null;

      var gid = e.currentTarget.dataset.gid;
      var nor = e.currentTarget.dataset.nor;
      var user_id = getApp().globalData.user_id;

      var sku_g = this.data.sku_g;
      if (nor || (gid != this.data.base_nor_goods_id && this.data.base_nor)) {
        sku_g = this.data.sku_g_pt;
        if (nor) this.data.base_nor = nor;
      }

      //要把不匹配还原
      if (th.data.def_pick_store && JSON.stringify(th.data.def_pick_store) != '{}') {
        th.data.def_pick_store.is_no_dis = 0;
        th.data.def_pick_store.is_no_dis_nor = 0;
        th.setData({ def_pick_store: th.data.def_pick_store })
      }

      //普通商品多规格的时候，商品切换
      if (this.data.base_nor_prom_type) this.data.base_nor_prom_type = parseInt(this.data.base_nor_prom_type);
      if ([1, 2, 4, 6, 8, 9].indexOf(this.data.base_nor_prom_type) == -1) {

        this.setData({
          prom_goods: null,
          jieti_prom: null,
          order_prom: null,
          zh_act: null,
          more_flash: null,
        })
      }

      //拼团在点击回来的时候，还是只能是立即购买，不能有购物车的情况
      if (this.data.base_nor_prom_type == 6 && parseInt(gid + '') == parseInt(this.data.base_nor_goods_id + '')) {
        this.setData({
          openSpecModal_pt: 1,
          openSpecModal: 0,
          sku_g: this.data.sku_g_pt,
          is_normal: 1
        })
        nor = 1;
      }


      //that.data.change=1;
      var item = null;
      for (var i in sku_g) {
        if (sku_g[i].goods_id == gid) {
          item = sku_g[i];
          if (item.original_img.indexOf(that.data.iurl) == -1) {
            item.original_img = that.data.iurl + item.original_img;
          }
          break
        }
      }
      console.log(item, 2000);
      var cur_price = item.shop_price;
      if (getApp().globalData.userInfo && getApp().globalData.userInfo.card_field) {
        var cfile = getApp().globalData.userInfo.card_field;
        console.log('cfile', cfile);
        if (item[cfile]) {
          cur_price = item[cfile];
        }
      }
      var txt = (cur_price / item.market_price * 10).toFixed(2).toString();
      txt = parseFloat(txt);
      item['disc'] = txt;
      if (item) this.setData({
        sele_g: item,
        gid: gid,
        data: item,
      });


      if (nor) {
        that.set_sele_g(sku_g)
        that.get_sto(1, () => {
          that.sele_spec_next(that, item, gid, nor);
        });
      }
      else that.get_sto(null, () => {
        that.sele_spec_next(that, item, gid, nor);
      }, item);

    },
    //-- 选择规格下一步 --
    sele_spec_next(that, item, gid, nor) {
      let th = this;
      if (!item.whsle_id && ([1, 2, 4, 6].indexOf(item.prom_type) == -1 || this.data.is_normal == 1))
        that.check_is_youhui(gid, that.data.is_normal, 1);

      //默认门店要拿下门店库存
      if (that.data.sales_rules >= 2 && that.data.def_pick_store && !that.data.sele_g.whsle_id && [1, 2, 4, 6].indexOf(item.prom_type) == -1) {
        var lock = 0,
          plist = null;

        that.check_CanOutQty(that.data.sele_g, that.data.def_pick_store, function (CanOutQty) {
          that.data.def_pick_store.CanOutQty = CanOutQty;
          //--给门店赋值线下库存--
          that.setData({
            def_pick_store: that.data.def_pick_store
          });
        })

      }
      that.sele_spec_chech_activity(nor);

      //如果是秒杀，拼团等互动，就不重新算界面
      if ([1, 2, 4, 6, 8, 9].indexOf(this.data.base_nor_prom_type) > -1) {
        return false;
      }

      that.check_has_flash(gid);
      var url = '/api/weshop/activitylist/listGoodActInfo2New';
      var req_d = {
        "store_id": os.stoid,
        "goods_id": that.data.gid,
        "user_id": getApp().globalData.user_id,
      }
      getApp().request.get(url, {
        data: req_d,
        success: function (e) {
          if (e.data.code != 0 || !e.data.data || e.data.data.length <= 0) return false;
          var arr = e.data.data;
          if (!arr || !arr.length) {
            return false;
          }
          var arr3 = arr.filter(function (e) {
            return e.s_time < ut.gettimestamp() && e.prom_type == 7;
          })

          //-- 组合购要在面前计算 --,计算完之后，再来计算check_is_youhui --
          if (arr3 && arr3.length > 0) {
            //获取活动信息
            var url = "/api/weshop/prom/zhbuy/get/" + os.stoid + "/" +
              arr3[0].act_id + "/" + getApp().globalData.user_id;
            getApp().request.get(url, {
              success: function (e) {
                if (e.data.code == 0 && e.data.data) {
                  if (ut.gettimestamp() < e.data.data.start_time) {
                    return false;
                  }
                  if (e.data.data.is_end == 0 && ut.gettimestamp() < e.data.data.end_time) {
                    //-- 获取商品列表 --
                    th.setData({
                      zh_act: e.data.data
                    });
                    th.getUserBuyPromNum(e.data.data.id)
                  }
                }
                if (!item.whsle_id) that.check_is_youhui(gid, that.data.is_normal);
              }
            });
          } else {
            if (!item.whsle_id) that.check_is_youhui(gid, that.data.is_normal);
          }

        }
      })
    },
    //选择了不同的规格的时候要判断是不是有活动正在进行中
    async sele_spec_chech_activity(nor) {
      //---如果是活动的时候---
      var prom = null, goodsinfo = this.data.sele_g, th = this;

      //如果是普通购买的时候，要返回原先
      if (goodsinfo.goods_id == this.data.base_nor_goods_id) {
        goodsinfo.prom_type = this.data.base_nor_prom_type;
        goodsinfo.prom_id = this.data.base_nor_prom_id;

        this.setData({
          prom_type: this.data.base_nor_prom_type,
          prom_id: this.data.base_nor_prom_id,
        })
      }

      var user_id = getApp().globalData.user_id;
      if (!user_id) user_id = 0;
      if (goodsinfo.prom_type == 1) {
        await getApp().request.promiseGet("/api/ms/flash_sale/getNew/" + os.stoid + "/" + user_id + "/" + goodsinfo.prom_id, {}).then(res => {
          if (res.data.code == 0 && res.data.data) {
            prom = res.data.data;
            prom.price = prom.user_price;
            this.setData({
              is_share_text: prom.is_share_text
            })
          }
        })
      }
      if (goodsinfo.prom_type == 6) {
        await getApp().request.promiseGet("/api/weshop/teamlist/get/" + os.stoid + "/" + goodsinfo.prom_id, {}).then(res => {
          if (res.data.code == 0) {
            prom = res.data.data;


            //----------查看阶梯团------------
            if (prom.ct_rylist != "null" && prom.ct_rylist != "" && prom.ct_rylist != null && prom.ct_rylist != undefined) {
              prom.ct_rylist = JSON.parse(prom.ct_rylist);
              var max_num = 0;
              prom.ct_rylist.forEach(function (val, ind) {
                if (parseInt(val.rynum) > max_num) max_num = parseInt(val.rynum);
              })
              prom.max_ct_num = max_num;
            }

          }
        })
      }

      if (goodsinfo.prom_type == 4) {
        await getApp().request.promiseGet("/api/weshop/integralbuy/getActInfo/" + os.stoid + "/" + goodsinfo.goods_id + "/" + goodsinfo.prom_id, {}).then(res => {
          if (res.data.code == 0) {
            prom = res.data.data;
          }
        })

        if (prom) {
          let times = new Date().getTime()
          prom.show_time_off = ""
          let atimes = prom.start_time * 1000

          if (atimes > times) {
            prom.show_time_off = ut.formatTime(prom.start_time)
          }
        }

      }
      console.log('活动详情------------');
      console.log(prom);
      //----------如果有活动，并且在进行中，就不计算线下库存---------------
      var now = ut.gettimestamp();
      if (prom) {

        var t1 = prom.start_time;
        var prom_st = 1;
        if (prom.show_time) {
          t1 = prom.show_time;
          if (prom.start_time > now) prom_st = 0;
        }
        if (prom.is_end == 0 && prom.end_time > now && t1 < now) {
          th.setData({
            prom_type: goodsinfo.prom_type,
            prom_price: prom.price,
            prom_buy_limit: prom.buy_limit ? prom.buy_limit : (prom.limitvipqty ? prom.limitvipqty : 0),
            prom_end_time: prom.end_time,
            prom_start_time: prom.start_time,
            prom_st: prom_st,
            prom_act: prom,
            prom_id: prom.id,
            sp_seleing: 0
          })

          var pro_null = null;
          if (goodsinfo.prom_type == 1) {
            var rs = await getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/1/" + prom.id, {});
            if (rs && rs.data.code == 0 && rs.data.data <= 0) {
              pro_null = 1;
            }
          }
          th.setData({ pro_null });


          //却换图片
          th.init(goodsinfo.goods_id);
          var newTime = ut.gettimestamp();
          var endTime2 = prom.end_time;
          var endTime1 = prom.start_time;

          this.data.is_timer = 0;

          setTimeout(function () {
            th.data.is_timer = 1;
            if (endTime1 > newTime) {
              th.setData({
                prom_time_text: '距秒杀开始还有'
              })
              // th.countDown(endTime1, 0);
            } else {
              if (endTime2 > newTime) {
                th.setData({
                  prom_time_text: '距秒杀结束还有',
                  prom_st: 1
                })
                // th.countDown(endTime2);
              }
            }

          }, 1000)

          return false;
        }
      }

      if (nor) {
        th.setData({ sp_seleing: 0 })
        return false;
      }

      //---设置普通商品---
      th.setData({
        prom_type: 0,
        prom_price: null,
        prom_buy_limit: null,
        prom_end_time: null,
        prom_start_time: null,
        prom_st: null,
        sp_seleing: 0
      })

    },
    //---检查有没有优惠活动---  is_nor的普通购买的时候，is_spec是切换规格的时候
    check_is_youhui: async function (gid, is_nor, is_spec) {
      var th = this;
      var user_id = getApp().globalData.user_id;
      if (!user_id) user_id = 0;

      //普通购买的时候，重新算一下组合购有没有
      if (is_nor || is_spec) {


        th.setData({
          cx_prom_group: []
        })

        var arr3 = null;
        var url = '/api/weshop/activitylist/listGoodActInfo2New';
        var req_d = {
          "store_id": os.stoid,
          "goods_id": gid,
          "user_id": user_id,
        }
        await getApp().request.promiseGet(url, {
          data: req_d,
        }).then(e => {
          if (e.data.code == 0 && e.data.data && e.data.data.length > 0) {
            var arr = e.data.data;
            if (arr.length) {
              arr3 = arr.filter(function (e) {
                return e.s_time < ut.gettimestamp() && e.prom_type == 7;
              })
            }
          }
        })

        if (arr3 && arr3.length > 0) {
          //获取活动信息
          var url = "/api/weshop/prom/zhbuy/get/" + os.stoid + "/" + arr3[0].act_id + "/" + getApp().globalData.user_id;
          await getApp().request.promiseGet(url, {

          }).then(e => {
            if (e.data.code == 0 && e.data.data) {
              if (ut.gettimestamp() < e.data.data.start_time) {
                return false;
              }
              if (e.data.data.is_end == 0 && ut.gettimestamp() < e.data.data.end_time) {
                //-- 获取商品列表 --

                if (is_spec) {
                  th.setData({
                    zh_act: e.data.data
                  })
                } else {
                  th.data.zh_act = e.data.data;
                }

                th.getUserBuyPromNum(e.data.data.id)
              }
            }
          })
        }
      }

      var r_data = null;


      //-- 如果有组合购的时候 --
      if (th.data.zh_act) {
        var show_time = ut.formatTime(th.data.zh_act.start_time) + "至" + ut.formatTime(th.data.zh_act.end_time);
        //-- 开始组装数据 --
        th.add_cx_prom_group({
          id: th.data.zh_act.id,
          title: th.data.zh_act.name,
          show_time: show_time,
          prom_type: 7
        });
      }

      //调用接口判断订单优惠，
      await getApp().request.promiseGet("/api/weshop/goods/getGoodsPromListNew1/" + os.stoid + "/" + gid + "/0" + "/" + user_id, {}).then(async res => {
        if (res.data.code == 0 && res.data.data) {
          r_data = res.data.data;
          var max = 0,
            min = 0;

          //如果是搭配购的时候
          if (r_data.collocationList) {
            for (var i in r_data.collocationList) {
              if (max == 0) max = r_data.collocationList[i].price;
              if (min == 0) min = r_data.collocationList[i].price;

              if (max < parseFloat(r_data.collocationList[i].price)) max = r_data.collocationList[i].price;
              if (min > parseFloat(r_data.collocationList[i].price)) min = r_data.collocationList[i].price;
            }
            r_data.collocationPromList.max = (max + th.data.data.shop_price).toFixed(2);
            r_data.collocationPromList.min = (min + th.data.data.shop_price).toFixed(2);
            var show_price = '￥' + r_data.collocationPromList.max + '-' + r_data.collocationPromList.min;
            var show_time = ut.formatTime(r_data.collocationPromList.start_time) + "至" + ut.formatTime(r_data.collocationPromList.end_time);

            //-- 开始组装数据 --
            th.add_cx_prom_group({
              id: r_data.collocationPromList.id,
              title: r_data.collocationPromList.title,
              show_price: show_price,
              show_time: show_time,
              prom_type: 5,
              main_gid: gid
            });
          }



          //优惠促销的时候
          if (r_data.promGoodsLists) {

            var fir_act = r_data.promGoodsLists[0];
            var is_yh_out_limit = 0;


            //-- 计算一下限购，满足限购数才显示  --
            if (fir_act.limit_num) {
              // await this.getUserBuyPromNum_pre(fir_act.prom_id);
              if (th.data.user_pre_buynum >= fir_act.limit_num) {
                is_yh_out_limit = 1;
              }
            }

            //如果是有限购的时候
            if (fir_act.gd_limit_num > 0 && !is_yh_out_limit) {
              var lrs = {
                store_id: os.stoid,
                user_id: user_id,
                goods_id: gid,
                prom_type: 3,
                prom_id: fir_act.prom_id, isnew: 1
              };
              var gd_limit_rs = await getApp().promiseGet('/api/weshop/ordergoods/getUserBuyGoodsNum', { data: lrs });
              var pro_by_num = 0;
              if (gd_limit_rs && gd_limit_rs.data.code == 0) {
                pro_by_num = gd_limit_rs.data.data.promgoodsbuynum
              }
              if (pro_by_num >= fir_act.gd_limit_num) {
                is_yh_out_limit = 1;
              }
            }
            //--  如果超出限购，就不显示了 --
            if (!is_yh_out_limit) {
              var more_arr = ut.format_yh_act(fir_act);

              var limit = '每人' + (fir_act.limit_num ? '限参与' + fir_act.limit_num + '次' : '参与不限次');
              if (fir_act.gd_limit_num > 0) {
                limit += ",限购" + fir_act.gd_limit_num + "件";
              }

              //-- 开始组装数据 --
              th.add_cx_prom_group({
                id: fir_act.prom_id,
                condition: fir_act.condition + (fir_act.prom_type == 1 ? '件' : '元'),
                limit: limit,
                gd_limit_num: fir_act.gd_limit_num > 0 ? fir_act.gd_limit_num : 0,
                more: more_arr,
                prom_type: 3,
                promGoodsListsDtos: r_data.promGoodsLists,
                is_yh_out_limit: is_yh_out_limit
              });
            }

          }

          //普通购买不在界面显示
          if (is_nor) {
            th.data.collocationGoods = r_data.collocationPromList;
            th.data.prom_goods = r_data.promGoodsLists;
          } else {
            th.setData({
              order_prom: r_data.promOrder,
              collocationGoods: r_data.collocationPromList,
              prom_goods: r_data.promGoodsLists,
            })
          }


        }
      })


      //-- 如果有阶梯购的时候 --
      if (r_data && r_data.ladderLists) {
        var act_id = r_data.ladderLists[0].form_id;
        //-- 判断会员能不能参与阶梯促销 --
        await getApp().request.promiseGet("/api/weshop/prom/ladderForm/getNew/" + os.stoid + "/" + user_id + "/" + act_id, {}).then(res => {
          if (res.data.code == 0 && res.data.data) {
            var prom_content = "";
            //暂定优惠促销还不能重叠
            // if (res.data.data.good_object == 0 && (r_data.promGoodsLists || th.data.zh_act)) {
            //   return false;
            // }
            // if (res.data.data.good_object == 1) {
            //   r_data.promGoodsLists = null;
            // }

            for (let jj in r_data.ladderLists) {
              if (r_data.ladderLists[jj].discount == 10) {
                prom_content += "第" + (parseInt(jj) + 1) + "件原价，";
              } else {
                prom_content += "第" + (parseInt(jj) + 1) + "件" + r_data.ladderLists[jj].discount + "折，";
              }
            }
            prom_content = ut.sub_last(prom_content);
            th.data.prom_type = 10;
            th.data.prom_id = act_id;
            th.setData({
              jieti_prom: prom_content,
              ladder_act_id: act_id
            })

            //-- 组装一下阶梯促销 --
            var s_time = res.data.data.start_time;
            var e_time = res.data.data.end_time;
            th.add_cx_prom_group({
              id: act_id,
              title: prom_content,
              show_time: ut.formatTime(s_time) + "至" + ut.formatTime(e_time),
              prom_type: 10
            });

          }
        })
      }

      th.is_show_more_buy();

      //-- 如果有促销活动也算是有参与活动，参与活动的也统一不进行计算起订的数量 --
      this.data.is_act = 0;
      if (this.data.zh_act || this.data.prom_goods || this.data.jieti_prom || this.data.collocationGoods) {
        this.data.is_act = 1;
      }

      console.log("11111111-gd");
      console.log(th.data.sele_g);

      //-- 更新默认购买的数量 ---
      var mo_num = getApp().get_limit_qty(th.data.sele_g, this.data.is_act);
      this.setData({
        goodsInputNum: mo_num
      })
      this.setData({
        mo_num: mo_num
      })
    },
    //获取促销活动的组合
    add_cx_prom_group(data) {
      var th = this;
      getApp().getConfig2(function (e) {
        //需要读者系统顺序
        var json_d = JSON.parse(e.switch_list);
        var auto_promote_sale = json_d.auto_promote_sale;
        if (auto_promote_sale) {
          var auto_promote_sale = auto_promote_sale.split(',');
          var fd = auto_promote_sale.indexOf(data.prom_type + '');
          data.sort = fd;
        } else {
          data.sort = data.prom_type;
        }

        var fdix = th.data.cx_prom_group.findIndex(function (em) {
          return em.prom_type == data.prom_type
        })

        if (fdix > -1) {
          th.data.cx_prom_group.splice(fdix, 1);
        }

        th.data.cx_prom_group.push(data);

        //-- 排序一下 --
        function comp(a, b) {
          return a.sort - b.sort; //升序
        }
        var ppdata = th.data.cx_prom_group;
        //使用sort排序
        ppdata.sort(comp);

        th.setData({
          cx_prom_group: ppdata
        })

      })
    },
    find_lock_num(pick_id, lock) {
      var lock_num = 0;
      if (!lock) return 0;
      if (lock.length < 0) return 0;
      for (var i in lock) {
        if (pick_id == lock[i].pickupId) {
          lock_num += lock[i].outQty;
        }
      }
      return lock_num;
    },
    //--- 获取默认的促销活动的默认活动 ---
    check_prom_custom(ind) {
      if (ind) {
        if (!this.data.cx_prom_group.length) return 0;
      } else {
        if (!this.data.cx_prom_group.length) return {
          prom_type: 0,
          id: 0
        };
      }

      var prom = null;
      prom = JSON.parse(JSON.stringify(this.data.cx_prom_group[0]));

      //-- 要判断有没有超出限购 --
      if (prom.prom_type == 3 && prom.is_yh_out_limit) {
        if (this.data.cx_prom_group.length > 1) {
          prom = this.data.cx_prom_group[1];
        } else {
          prom.prom_type = 0;
          prom.id = 0;
        }
      }

      if (ind) {
        return prom.prom_type;
      }
      return prom;
    },
    // 选择门店
    choice_store: function (ee) {
      var th = this;
      var ind = ee.currentTarget.dataset.ind;
      var bconfig = th.data.bconfig;
      this.setData({
        keyword: ''
      })
      //--先判断会员状态--
      var user_info = getApp().globalData.userInfo;
      if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
        wx.navigateTo({
          url: '/packageE/pages/togoin/togoin',
        })
        return false;
      }


      //如果开启了，则不在选择门店
      if (this.data.sys_switch.is_pricing_open_store && getApp().globalData.pk_store) {
        return false;
      }

      if (!th.data.only_pk && !th.data.def_pickpu_list && !th.data.change) {
        // getApp().confirmBox("门店库存不足", null, 25000, !1);
        wx.showToast({
          title: '门店库存不足',
          icon: 'none',
        });
        return false;
      }
      th.data.change = 0;

      if (th.data.only_pk && !th.data.only_pk.length) {
        // getApp().confirmBox("门店库存不足", null, 25000, !1);
        wx.showToast({
          title: '门店库存不足',
          icon: 'none',
        });
        return false;
      }
      if (th.data.def_pickpu_list && !th.data.def_pickpu_list.length) {
        // getApp().confirmBox("门店库存不足", null, 25000, !1);
        wx.showToast({
          title: '门店库存不足',
          icon: 'none',
        });
        return false;
      }

      //如果开启了，则不在选择门店
      if (th.data.sys_switch.is_pricing_open_store && getApp().globalData.pk_store) {
        return false;
      }



      if (bconfig && bconfig.is_sort_storage) {
        wx.getLocation({
          type: 'gcj02',
          success: function (res) {

            th.data.lat = res.latitude;
            th.data.lon = res.longitude;
            th.data.is_get_local_ok = 1;
            th.setData({
              is_gps: 1
            });
            //th.onShow();
            th.get_sto(th.data.is_normal);
          },
          fail: function (res) {



            //th.onShow();
            th.data.is_get_local_ok = 1;
            th.get_sto(th.data.is_normal);
            if (res.errCode == 2) {
              th.setData({
                is_gps: 0
              });
              if (th.data.is_gps == 0) {
                getApp().confirmBox("请开启GPS定位", null, 25000, !1);
              }
            } else {
              th.setData({
                is_gps: "3"
              });
            }

          }
        })
      } else {
        th.data.is_get_local_ok = 1;
        th.get_sto(th.data.is_normal);
      }

      if (ind != undefined && ind != null) {
        this.setData({
          open_ind_store: ind,
          store: 1,
          openSpecModal: !1,
          openSpecModal_pt: !1,
          openSpecModal_flash_normal: !1,
        })
      } else {
        this.setData({
          store: 1,
          openSpecModal: !1,
          openSpecModal_pt: !1,
          openSpecModal_flash_normal: !1

        })
      }
    },

    //关闭选择门店
    close_popup: function (e) {
      var th = this;
      this.setData({
        store: 0,
        choice_sort_store: 0,
        sort_store: 0,
        fir_pick_index: 0,
        sec_pick_index: 0
      })

      var openindstore = this.data.open_ind_store;
      if (openindstore == 1) {
        th.setData({
          openSpecModal: !0,
          openSpecModal_ind: openindstore,
        });
      } else if (openindstore == 2) {
        th.setData({
          openSpecModal: !0,
          openSpecModal_ind: openindstore,
        });
      } else if (openindstore == 4) { //4就是拼团
        th.setData({
          openSpecModal_pt: 1, //打开拼团购买界面
          store: 0, //关闭门店
          choice_sort_store: 0, //关闭门店2级
          sort_store: 0, //关闭门店2级
        });
      } else {
        th.setData({
          store: 0,
          choice_sort_store: 0,
          sort_store: 0
        })
      }


    },
    choose_for_store_fir: function (e) {
      var index_c = e.currentTarget.dataset.ind;
      var th = this;
      th.setData({
        fir_pick_index: index_c
      })

    },
    //选择更多门店
    more_store: function () {
      this.setData({
        sort_store: 1
      });
    },
    check_guide(func) {
      var first_leader = getApp().globalData.first_leader;
      if (!first_leader) {
        func();
        return false;
      }
      if (this.data.is_geted_guide_pick) {
        func();
        return false;
      }

      if (getApp().globalData.guide_pick_id) {
        func();
        return false;
      }
      var th = this;
      getApp().request.promiseGet("/api/weshop/shoppingGuide/get/" + os.stoid + "/" + first_leader, {}).then(res => {
        if (res.data.code == 0) {
          getApp().globalData.guide_pick_id = res.data.data.pickup_id;
        }
        th.data.is_geted_guide_pick = 1;
        func();
      })
    },

    //确定def_pick为选择的门店
    sure_pick: function (e) {
      var th = this;
      var item = null;
      var openindstore = parseInt(th.data.open_ind_store);

      if (th.data.choice_sort_store == 0) {
        var index = th.data.fir_pick_index;
        if (th.data.is_show_sto_cat == 1) {
          item = th.data.def_pickpu_list[index];
        } else {
          item = th.data.only_pk ? th.data.only_pk[index] : null; //当没有门店分类的时候
        }

      } else {
        var index = th.data.sec_pick_index;
        item = th.data.sec_sto.s_arr[index];
      }

      if (!item) return false;

      if (item.is_no_dis_nor || (item.is_no_dis_act && !th.data.is_normal)) {
        wx.showToast({
          title: "该门店不可售，请选择其他门店",
          icon: 'none',
          duration: 2000
        });
        return false;
      }


      if (!th.data.sele_g) return false;
      //判断门店的配送方式是不是匹配
      var g_distr_type = th.data.sele_g.distr_type;
      if (item.distr_type != 0 && g_distr_type != 0 && item.distr_type != g_distr_type) {
        wx.showToast({
          title: "门店配送方式不匹配，请选择其他门店",
          icon: 'none',
          duration: 2000
        });
        return false;
      }

      //--回调函数的用法--
      th.check_the_pick(item, function () {
        th.setData({
          def_pick_store: item,
          sto_sele_name: item.pickup_name,
          sto_sele_id: item.pickup_id,
          sto_sele_distr: item.distr_type,
          store: 0,
          choice_sort_store: 0,
          fir_pick_index: 0
        });

        switch (openindstore) {
          case 1:
            th.setData({
              openSpecModal: !0,
              openSpecModal_ind: openindstore,
            });
            break;
          case 2:
            th.setData({
              openSpecModal: !0,
              openSpecModal_ind: openindstore,
            });
            break;
          case 4:
            th.setData({
              openSpecModal_pt: 1, //打开拼团购买界面
              store: 0, //关闭门店
              choice_sort_store: 0, //关闭门店2级
              sort_store: 0, //关闭门店2级
            });
            break;
          case 5:
            th.setData({
              openSpecModal_flash_normal: 1, //打开拼团购买界面
              store: 0, //关闭门店
              choice_sort_store: 0, //关闭门店2级
              sort_store: 0, //关闭门店2级
            });
            break;
          default:
            th.setData({
              store: 0,
              choice_sort_store: 0,
              sort_store: 0
            })
            break
        }

        //如果商品没有其他活动,要取一下线下价格
        th.get_off_price();
      })
    },
    //---点击二级之后的选择---
    choose_for_store: function (e) {
      var index_c = e.currentTarget.dataset.ind;
      var th = this;
      th.setData({
        sec_pick_index: index_c,
        fir_pick_index: index_c
      })

    },
    //把选择的门店设置成默认的门店def_pick
    set_def_pick: function (e) {
      var th = this;
      var item = null;
      if (th.data.choice_sort_store == 0) {
        var index = th.data.fir_pick_index;
        if (th.data.is_show_sto_cat == 1) {
          item = th.data.def_pickpu_list[index];
        } else {
          item = th.data.only_pk ? th.data.only_pk[index] : null; //当没有门店分类的时候
        }
      } else {
        var index = th.data.sec_pick_index;
        item = th.data.sec_sto.s_arr[index];
      }

      if (!item) return false;

      //判断门店的配送方式是不是匹配
      var g_distr_type = th.data.sele_g.distr_type;
      if (item.distr_type != 0 && g_distr_type != 0 && item.distr_type != g_distr_type) {
        wx.showToast({
          title: "门店配送方式不匹配",
          icon: 'none',
          duration: 2000
        });
        return false;
      }

      //先设置之前,要判断是不是有库存
      th.check_the_pick(item, function () {
        var store_id = o.stoid;
        var user_id = getApp().globalData.user_id;
        var def_pickup_id = item.pickup_id;

        getApp().request.put('/api/weshop/users/update', {
          data: {
            user_id: user_id,
            def_pickup_id: def_pickup_id
          },
          success: function (res) {
            if (res.data.code == 0) {
              if (th.data.choice_sort_store == 0) th.setData({
                fir_pick_index: 0
              });
              getApp().globalData.pk_store = item;
            } else {
              //s.showWarning("设置默认门店地址失败", null, 500, !1);
              getApp().my_warnning("设置默认门店地址失败", 0, th)
            }

          }
        });

        th.setData({
          def_pick_store: item,
          sto_sele_name: item.pickup_name,
          sto_sele_id: item.pickup_id,
          sto_sele_distr: item.distr_type,
          store: 0,
          choice_sort_store: 0
        });

        var openindstore = th.data.open_ind_store;
        if (openindstore == 1) {
          th.setData({
            openSpecModal: !0,
            openSpecModal_ind: openindstore,
            store: 0,
            choice_sort_store: 0,
            sort_store: 0,
          });
        } else if (openindstore == 2) {
          th.setData({
            openSpecModal: !0,
            openSpecModal_ind: openindstore,
            store: 0,
            choice_sort_store: 0,
            sort_store: 0,
          });
        } else if (openindstore == 4) { //4就是拼团
          th.setData({
            openSpecModal_pt: 1, //打开拼团购买界面
            store: 0, //关闭门店
            choice_sort_store: 0, //关闭门店2级
            sort_store: 0, //关闭门店2级
          });
        } else {
          th.setData({
            store: 0,
            choice_sort_store: 0,
            sort_store: 0,
          })
        }

        //如果商品没有其他活动,要取一下线下价格
        th.get_off_price();

      })
    },


    get_user_store() {

      var th = this;
      var that = this;
      //--获取用户的默认门店
      getApp().get_user_store(function (e) {
        if (!e) {
          th.data.fir_def_store = {}; //赋值空对象
          return false;
        }
        if (getApp().globalData.is_dj_pk) th.setData({
          has_def: 1
        });

        var ee = JSON.parse(JSON.stringify(e));

        //--定时器推迟一下--
        var appd = getApp().globalData;
        w_time = setInterval(function () {
          if (that.data.is_get_local_ok == 0) return false;
          if (!that.data.sele_g) return false;
          if (th.data.fir_goods) var g_distr_type = th.data.fir_goods.distr_type;
          //--如果默认门店的配送方式不对，就不能被选择，这里不控制，如果不一样，就说明配送方式不对--
          if (ee.distr_type != 0 && g_distr_type != 0 && ee.distr_type != g_distr_type) {
            ee.is_no_dis = 1;
          }

          //-- 如果有指定门店的时候,pickup_ids是经过判断是不是普通商品后才会有的 --
          if (th.data.sele_g && th.data.sele_g.pickup_ids && th.data.prom_type == 0) {
            var idx = th.data.sele_g.pickup_ids.findIndex(function (e) {
              return e.pickup_id == ee.pickup_id;
            })
            if (idx < 0) {
              ee.is_no_dis_nor = 1;
            }
          }

          clearInterval(w_time);
          var distance = null;
          var e = JSON.parse(JSON.stringify(ee));

          //如果有开启近距离的话,同时距离优不一样了
          if (that.data.lat != null) {
            //如果经纬度有变化的话
            if (e && appd.lat == that.data.lat && appd.lon == that.data.lon && e.distance > 0) {
              that.set_def_storage(e);
            } else {
              //要用接口是获取距离，js的计算不准
              getApp().request.promiseGet("/api/weshop/pickup/list", {
                data: {
                  store_id: os.stoid,
                  pickup_id: e.pickup_id,
                  lat: th.data.lat,
                  lon: th.data.lon,
                  isstop: 0,
                  is_pos: 1
                },
              }).then(res => {
                if (res.data.code == 0) {
                  e = res.data.data.pageData[0];
                  if (e) {
                    e.is_no_dis = ee.is_no_dis;
                    appd.pk_store = e;
                    that.set_def_storage(e);
                  }

                }
              })
            }
            //e.distance = distance;
            appd.lat = that.data.lat;
            appd.lon = that.data.lon;

          } else {
            if (e) {
              e.distance = null;
              that.set_def_storage(e);
            }
          }
        }, 200)

      });
    },
    //如果开启线下库存，已经急速库存才会使用
    check_the_pick(item, func) {
      var th = this;
      var goodsinfo = th.data.sele_g;
      var erpwareid = goodsinfo.erpwareid;
      var plist = null;
      var lock = 0;

      //---如果是活动的时候,同时不是普通购买---
      if (getApp().is_virtual(th.data.sele_g) || th.data.sele_g.whsle_id || ([1, 2, 4, 6, 8, 9].indexOf(th.data.prom_type) > -1 && !th.data.is_normal)) {
        func();
        return false;
      }

      if (this.data.sales_rules == 1) {
        func();
      } else {
        // if (plist && plist.CanOutQty - lock > 0) {
        //     item.CanOutQty = plist.CanOutQty - lock;
        //     func();
        //     return false;
        // }
        this.check_CanOutQty(goodsinfo, item, function (CanOutQty) {

          // let str = item.pickup_name + '库存不足！';
          if (!CanOutQty) {
            wx.showToast({
              title: item.pickup_name + '库存不足！',
              icon: 'none',
            });
            return false;
          }
          item.CanOutQty = CanOutQty;
          func();

        });

      }
    },
    //----获取线下价格-------
    get_off_price() {
      var th = this;
      //没有开启就返回
      if (!th.data.is_open_offline) return false;
      //先看下购买的功能有没有到期
      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) {
          return false;
        } else {
          //已经过期
          var item = res.data.data.pageData[0];
          if (item.end_time < ut.gettimestamp()) {
            return false;
          }
        }


        var cur_goods = this.data.sele_g;
        var cur_price = cur_goods.shop_price;
        if (th.data.card_field && cur_goods[th.data.card_field] > 0) {
          cur_price = cur_goods[th.data.card_field];
        }

        var user_info = getApp().globalData.userInfo;
        //获取一下接口，判断是不是有线下接口,必须是普通商品，全局优惠活动也是不行
        if (cur_goods.prom_type == 0 && !this.data.prom_goods) {
          cur_goods.offline_price = null;
          //如果没有门店，不用计算线下价格
          var def_pick_store = this.data.def_pick_store;
          if (!def_pick_store) return false;
          getApp().request.get("/api/weshop/goods/listWarePrice", {
            data: {
              VIPId: encodeURIComponent(user_info.erpvipid),
              store_id: os.stoid,
              PickupId: def_pick_store.pickup_id,
              WareIds: encodeURIComponent(cur_goods.erpwareid)
            },
            success: function (res) {
              if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
                var datalist = res.data.data;
                if (datalist[0].WarePrice < cur_price) {
                  cur_goods.offline_price = datalist[0].WarePrice; //存储线下活动的价格
                  cur_goods.pricing_type = datalist[0].PriceType; //存储线下活动的类型
                }
              }
              th.setData({
                sele_g: cur_goods
              });
            }

          })
        }

      })


    },
    //--- 设置一下默认库存的数量 ----
    set_def_storage(ee) {
      var that = this,
        th = this;
      getApp().getConfig2(function (e) {
        var sales_rules = e.sales_rules;
        if (sales_rules >= 2 && [1, 2, 4, 6, 8, 9].indexOf(th.data.prom_type) == -1 && !th.data.sele_g.whsle_id) {
          getApp().waitfor2(that, "wait_for_user_store", "fir_goods", function () {
            var lock = 0,
              plist = null;
            var gd = that.data.fir_goods;
            //先读取门店的lock,采用链式写法，少用await
            // getApp().request.promiseGet("/api/weshop/order/ware/lock/page", {
            //     data: {
            //         store_id: os.stoid,
            //         wareId: that.data.fir_goods.goods_id,
            //         storageId: ee.pickup_id,
            //         pageSize: 1000
            //     }
            // }).then(res => {
            //     if (res.data.code == 0 && res.data.data.total > 0) {
            //         for (var i in res.data.data.pageData)
            //             lock += res.data.data.pageData[i].outQty
            //     }
            //     //---通过接口获取门店的线下库存信息--
            //     return getApp().request.promiseGet("/api/weshop/goods/getWareStorages", {
            //         data: {
            //             storageNos: ee.pickup_no,
            //             wareIds: encodeURIComponent(th.data.data.erpwareid),
            //             storeId: os.stoid
            //         }
            //     })
            // }).then(res => {
            //     if (res.data.code == 0 && res.data.data.total > 0) {
            //         plist = res.data.data.pageData[0];
            //     } else {
            //         wx.showToast({
            //             title: '库存不足，请更换其他门店',
            //             icon: 'none',
            //         });
            //     }
            //
            //     if (plist && plist.CanOutQty - lock > 0) {
            //         ee.CanOutQty = plist.CanOutQty - lock;
            //     } else {
            //         ee.CanOutQty = 0;
            //     }
            //     //--给门店赋值线下库存--
            //     that.data.fir_def_store = ee;
            //     that.setData({
            //         def_pick_store: ee,
            //         sto_sele_name: ee.pickup_name,
            //         sto_sele_id: ee.pickup_id,
            //         sto_sele_distr: ee.distr_type
            //     })
            // })
            //最新的获取线下门店库存
            th.check_CanOutQty(gd, ee, function (CanOutQty) {
              ee.CanOutQty = CanOutQty;
              //--给门店赋值线下库存--
              that.data.fir_def_store = ee;
              that.setData({
                def_pick_store: ee,
                sto_sele_name: ee.pickup_name,
                sto_sele_id: ee.pickup_id,
                sto_sele_distr: ee.distr_type
              })
            })


          })
        } else {
          that.data.fir_def_store = ee;
          that.setData({
            def_pick_store: ee,
            sto_sele_name: ee.pickup_name,
            sto_sele_id: ee.pickup_id,
            sto_sele_distr: ee.distr_type
          })
        }
      })

    },
    wait_for_store_config: function () {
      var th = this;
      //----获取系统参数-----
      getApp().getConfig2(function (e) {
        th.setData({
          bconfig: e,
        });
      })
      t_time = setInterval(function () {


        if (th.data.bconfig == null) false;
        var e = th.data.bconfig;
        if (e && e.is_sort_storage) {


          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              th.data.lat = res.latitude;
              th.data.lon = res.longitude;
              th.data.is_get_local_ok = 1;
            },
            fail: function (res) {
              if (res.errCode == 2) {
                th.setData({
                  is_gps: 0
                });
                if (th.data.is_gps == 0) {
                  getApp().confirmBox("请开启GPS定位", null, 10000, !1);
                }

              } else {
                th.setData({
                  is_gps: "3"
                });
              }

              th.data.is_get_local_ok = 1;
            }
          })
        } else {
          th.data.is_get_local_ok = 1;
        }
        clearInterval(t_time);
      }, 500)
    },
    //获取搜索门店输入的值 
    input_store: function (e) {
      this.setData({
        keyword: e.detail.value
      })
    },
    //搜索门店
    searchfn() {
      let choice_sort_store = this.data.choice_sort_store
      if (choice_sort_store == 0) { //全局搜索
        let all_pick_list = this.data.all_pick_list
        let def_pickpu_list = this.data.def_pickpu_list
        let keyword = this.data.keyword
        if (keyword) {
          let arr = all_pick_list.filter(item => {
            let i = item.pickup_name.indexOf(keyword)
            if (i > -1) {
              return true
            } else {
              return false
            }
          })
          if (arr && arr.length > 0) {
            if (this.data.is_show_sto_cat == 1) {
              this.setData({
                def_pickpu_list: arr
              })
            } else {
              this.setData({
                only_pk: arr
              })
            }
          } else {
            wx.showToast({
              title: '没有搜索到门店',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          if (this.data.is_show_sto_cat == 1) {
            this.setData({
              def_pickpu_list: all_pick_list.slice(0, 10)
            })
          } else {
            this.setData({
              only_pk: all_pick_list
            })
          }

        }
      } else { //分类下搜索
        let sec_i = this.data.sec_i
        let all_sto = this.data.all_sto
        let old_all_sto = this.data.old_all_sto
        if (!old_all_sto) {
          this.setData({
            old_all_sto: JSON.parse(JSON.stringify(all_sto))
          })
        }
        let sec_sto = this.data.sec_sto
        let sec_arr = this.data.old_all_sto[sec_i].s_arr
        let keyword = this.data.keyword
        let text = 'sec_sto.s_arr'
        if (keyword) {
          let arr = sec_arr.filter(item => {
            let i = item.pickup_name.indexOf(keyword)
            if (i > -1) {
              return true
            } else {
              return false
            }
          })
          if (arr && arr.length > 0) {
            this.setData({
              [text]: arr
            })
          } else {
            wx.showToast({
              title: '没有搜索到门店',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          if (this.data.old_all_sto) {
            this.setData({
              [text]: this.data.old_all_sto[sec_i].s_arr
            })
          } else {
            this.setData({
              [text]: all_sto[sec_i].s_arr
            })
          }
        }


      }
    },
    //---选择分类门店---
    choice_sort_store: function (e) {
      var index = e.currentTarget.dataset.index;
      var region_name = e.currentTarget.dataset.region;
      var item = this.data.all_sto[index];
      this.setData({
        region_name: region_name,
        sort_store: 0,
        choice_sort_store: 1,
        sec_sto: item,
        sec_i: index,
        sec_pick_index: 0
      });
    },
    // 返回按钮
    returns: function () {
      this.setData({
        sort_store: 0,
        choice_sort_store: 0
      });
    },
    pop_err_img: function (e) {
      var txt = e.currentTarget.dataset.errorimg;
      var ob = {};
      ob[txt] = this.data.iurl + "/miniapp/images/default_g_img.gif";
      this.setData(ob);
    },
    async getUserBuyPromNum(prom_id, is_zh) {
      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
      }
      this.setData({
        userbuynum
      })
      if (is_zh) this.data.user_zh_buy_num = userbuynum;
      // return userbuynum
    },
    //-- 根据ID拿出门店 --
    get_pick_from_list(pid) {
      var all_pick_list = this.data.all_pick_list;
      for (var i in all_pick_list) {
        var item = all_pick_list[i];
        if (item.pickup_id == pid) {
          return item;
        }
      }
    },

  }
})
