var ut = require("../../../../utils/util.js"),
  s = getApp(),
  i = s.request,
  oo = s.globalData,
  o = s.globalData.setting,
  os = o;
var regeneratorRuntime = require('../../../../utils/runtime.js');


Page({
  data: {
   
    num: 1, //输入框值 加减之间的值
    minusStatus: 'disable', //禁用按钮
    ii_endname: 'disable', //吐司的禁用按钮
    pd_xx: false, //弹框
    buy_start_date: null, //转换完的时间
    ssl: null,
    yijian: false, //一键参加按钮显示隐藏

    //选择门店
    qh: true, //取货
    xz: false, //选择
    one: false, //第一层显示隐藏
    se: false, //已选择的值
    list: false, //第二层显示隐藏
    ssl_child: null, //第二层的值
    sele_dl_name: "", //选择的值
    end_name: "", //最后显示的值

    ii: 0, //选择门店显示隐藏
    zk: true, //展开列表显示隐藏
    stoid: o.stoid,
    hiddenName: false, //收起列表显示隐藏
    teamlist: null, //活动主表
    teamgroup: null, //活动从表
    goods: null, //商品数据
    pindGoods: null, //拼单数据
    imageurl: os.imghost, //有礼派图片地址
    team_id: 0, //支付是否成功
    listno: "", //订单编号
	
	  //选择的门店id
  	pick_id:0,
    //会员团满团时的判断
    tg_arr:null,
    //是否显示
    is_show:0,
    //是不是团结束
    is_group_end:0,
    //团结束的提示语句
    end_text:"",
    //是开团或者参团，0参团，1开团（但是，商家团还是参团）
    is_kt_or_ct:0,
    //判断redis的数组
    redis_arr:null,

    iurl:os.imghost,
		
		
	openSpecModal: !1,
	openSpecModal_pt: !1, //拼单的弹起，
		
	
	//门店相关
	ismend: 0,
	is_sec_mend: 0,
	sto_sele_name: "", //选中的门店名称
	sto_sele_id: "", //选中的门店id
	sto_sele_distr: "", //选择的门店的配送方式
	is_show_sto_cat: 1, //是否显示门店分类
	only_pk: null,
	all_sto: null,
	sec_sto: null, //选择了的门店分类
	pickpu_list: null, //读出的所有门店list
	def_pickpu_list: null, //一开始5个门店list
	sec_pick_index: 0, //第二级门店选择ID
	fir_pick_index: 0, //第一级门店选择ID
	all_pick_list:null,//所有的门店先记录起来	
	bconfig:null,	
	def_pick_store: null, // 默认的门店
	fir_def_store:null,  //客户默认的门店的
	lat: null, //维度
	lon: null, //经度
	
	is_get_local_ok: 0, //获取坐标是否完成
	
	sort_store: 0, //门店分类
	choice_sort_store: 0, //选择分类门店
		
  },
  onLoad: function(options) {
      wx.setNavigationBarTitle({ title: "拼团订单",})

      var postdata=options;
      var tg_id = postdata.tg_id, first_leader=options.first_leader,goods_id=options.goods_id;
      //如果tg_id是空的话
      if(tg_id==null ||goods_id==null){
        var tg_id_str=decodeURIComponent(postdata.scene);
        tg_id_str=tg_id_str.split("_");
        switch(tg_id_str.length){
          case 1:
            tg_id=tg_id_str[0];
            break;
          case 2:
            tg_id=tg_id_str[0];
            first_leader=tg_id_str[1];
            break;
          case 3:
            tg_id=tg_id_str[0];
            first_leader=tg_id_str[1];
            goods_id=tg_id_str[2];
            break;
        }
      }
      //--判断一下是不是导购--
      if(first_leader){
      getApp().globalData.first_leader=first_leader;
      //调用接口判断是不是会员
      getApp().request.promiseGet("/api/weshop/shoppingGuide/get/"+os.stoid+"/"+first_leader,{}).then(res=>{
        if(res.data.code==0){
          getApp().globalData.guide_id=res.data.data.id;
          getApp().globalData.guide_pick_id= res.data.data.pickup_id
        }
      })
    }
    this.setData({tg_id: tg_id,goods_id});
    getApp().globalData.to_group=null;
	
	  var th=this;
	  getApp().getConfig2(function(e) {

         var json_d = JSON.parse(e.switch_list);
	     th.setData({ bconfig: e,sys_switch:json_d});
	     th.wait_for_store_config(); //获取默认的门店
    })

		
  },

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

    getApp().check_can_share();
    var tg_id = this.data.tg_id,th=this;
    this.init(tg_id);		
  },

  //c点击打开拼团弹窗
  cpd: function() {
    this.setData({  pd_xx: true,})
  },

  //点击关闭拼团弹窗
  close_pt_xx: function() {
    this.setData({ pd_xx: false, })
  },

  //按钮点击一键参加团按钮
  cyijian: function(e) {
    //--先判断会员状态--
    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;
    }

    var is_kt_or_ct=e.currentTarget.dataset.isct;
    this.setData({
      yijian: true,is_kt_or_ct:is_kt_or_ct,
    })
  },
  //关闭展开列表
  click: function(e) {
    this.setData({
      hiddenName: !this.data.hiddenName,
      zk: !this.data.zk,
    })
  },
  //打开收起拼团列表
  czk: function(e) {
    this.setData({
      zk: !this.data.zk,
      hiddenName: !this.data.hiddenName,
    })
  },
  //关闭购买页面
  cbcou: function(e) {
    this.setData({
      yijian: false,
    })

  },
  //qh点击取货
  cqh: function(e) {	  
	if(this.data.ssl)  {		
		this.setData({
		  qh: false,
		  xz: true,
		  one: true,
		})
	}else{
		this.setData({
		  qh: false,
		  xz: true,
		  one: false,
		  list:1,
		})
	}
	
  },

  //cxz点击选择门店
  cxz: function(e) {
    this.setData({
      qh: true,
      xz: false,
      one: false,
    })
  },
  //ccc点击选择的
  sel: function(e) {
    this.setData({
      list: false,
      se: false,
      one: true,
      xz: true,
    })
  },
  //list点击底二层
  clist: function(e) {
    var i = e.currentTarget.dataset.end;
    var pick_id = e.currentTarget.dataset.pick_id;
    var pick_dis = e.currentTarget.dataset.pick_dis;

    this.setData({
      end_name: i,
      pick_id: pick_id,
      ii: 1,
      qh: true,
      se: false,
      list: false,
      pick_dis: pick_dis
    })
  },

  //点击第一层
  setchild: function(e) {
    var ind = e.currentTarget.dataset.bindex;
    var nn = e.currentTarget.dataset.bname;
    console.log(nn);
    var list = this.data.ssl[ind].s_arr;
    this.setData({
      ssl_child: list,
      sele_dl_name: nn,
      xz: false,
      one: false,
      list: true,
      se: true
    });
  },

  //事件处理函数
  /*点击减号*/
  bindMinus: function() {
    var num = this.data.num;
    if (num > 1) {
      num--;
    }
    var minusStatus = num > 1 ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
    })
  },

  /*点击加号*/
  bindPlus: function() {
    var th=this;
    var num = this.data.num;
    var ii = this.data.ii;
    var minusStatus = num > 1 ? 'normal' : 'disable';

      num++;
      //要判断库存数量，限购数量
      th.check_num(num,minusStatus);

  },

  async check_num(num,minusStatus){

    var gd=this.data.goods;
    var th=this;
    var user_id=getApp().globalData.user_id;
    var promcardbuynum=0;
    var goodsbuynum=0;
    await getApp().request.promiseGet("/api/weshop/rechargeServicelist/getUserBuyGoodsNum", {
      data: {
        store_id: os.stoid,
        user_id: user_id,
        card_id: gd.id,
        prom_type: 6,
        prom_id: gd.prom_id,        
        isnew:1
      },
    }).then(res=>{
       var buy_num_data=res.data.data;
       if(buy_num_data.promcardbuynum) promcardbuynum=buy_num_data.promcardbuynum;
       goodsbuynum=buy_num_data.cardbuynum;
    })

    if (num+promcardbuynum>th.data.teamlist.buy_limit && th.data.teamlist.buy_limit>0) {
      getApp().confirmBox("超出活动限购");
      return false;
    }

    var r_num=0;
    await  getApp().request.promiseGet("/api/weshop/activitylist/getActLen/" + os.stoid + "/6/" + th.data.teamlist.id, {
      1: 1
    }).then(res => {
      var em = res;
      if (em.data.code == 0) {
        r_num=em.data.data;
      }
    })
    //--判断库存---
    if ( num>r_num) {
      getApp().confirmBox("超出商品库存");
      return false;
    }

    this.setData({
      num: num,
      minusStatus: minusStatus,
    })

    return true;

  },

  /*输入框事件*/
  bindManual: function(e) {
    var num = e.detail.value;
    var minusStatus = num > 1 ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus
    })
  },

  //---------------初始化代码----------------
  async init(tg_id) {
    var goods_id = 0, //商品ID,
      pageteam = null, //
      original_img = null, //商品图片
      ee = this,
      ordertx = [],
      teamlist = null,  //活动表
      goods = null,     //商品
      teamgroup = null, //活動从表
      max_num = 0,
      min_price = 0,
      th=this,
      that=th,
      flag=null,
      odr=null;
      await getApp().request.promiseGet("/api/weshop/teamlist/pageteam/2",{
        data:{
          store_id: os.stoid,
          is_end: 0,
          is_show: 1,
          user_id: getApp().globalData.user_id,
          pageSize:1000,
          goods_id:th.data.goods_id
        }
      }).then(res=>{
        let pd_list=res.data.data.pageData;
        if(res.data.code==0 && pd_list.length>0){
          flag =pd_list.find(pd=>{
                return pd.goods_type==1;
          })
        }
      })
      if(!flag){
        wx.showToast({title: "当前会员身份不符，无法参与", icon: 'none', duration: 3000});
          setTimeout(function () {
              ut.wx_back();
          }, 1000)
          return false;
      }

    //获取活动从表信息team_id,listno团编号（券号）
    await getApp().request.promiseGet("/api/weshop/teamgroup/get/"+os.stoid+"/"+tg_id, {
    }).then(res => {
    
      if(res.data.code !=0 ){
        getApp().showWarning(res.data.msg);
        th.go_back();
        return false;
      }
		
	  if(res.data && res.data.data )	{
		
		  teamgroup = res.data.data;
		  //获取当前时间,并且判断剩余时间
		  var nt = ut.gettimestamp();
		  var buy_start_date = ut.formatTime(teamgroup.buy_start_date, "yyyy-MM-dd hh:mm:ss");
		  ee.setData({
			pindGoods: teamgroup,
			buy_start_date: buy_start_date
		  });

		  if(nt>teamgroup.kt_end_time) {
			th.setData({is_group_end:1,end_text:"团期已经结束"})
		  }
		  if(teamgroup.state==1) {
			th.setData({is_group_end:1,end_text:"团期已经结束"})
		  }
		  if(teamgroup.state==3 || teamgroup.state==4 || teamgroup.state==5 ) {
			th.setData({is_group_end:2,end_text:"团期已满"})
		  }
	  
	  }
    })

    //判断是不是要继续的开关
    var is_ok=1;

    //要先读取订单，看自己有没有买过该团的商品
    await getApp().request.promiseGet("/api/weshop/rechargeServicelist/page", {
      data: {
        prom_id:teamgroup.team_id,
        prom_type:6,
        user_id: oo.user_id,
        store_id: os.stoid,
        pageSize: 1,
        page: 1
      }
    }).then(res => {
      var e=res;
      if (e.data.code != 0) {
        getApp().showWarning("读取订单失败");
        th.go_back();
        is_ok=0;
        return fasle;
      }
      //--跳转到已经购买的情况--
      if (e.data.data.pageData.length > 0) {
        odr = e.data.data.pageData[0];
        //还未支付
        if (odr.pt_status == 0 && odr.order_status == 1) {

            getApp().goto("/packageA/pages/details_serviceCard/details_serviceCard?order_id=" + odr.order_id)
            is_ok=0;
        }else if (odr.pt_status == 1 && odr.order_status == 1){
            getApp().goto( "/packageA/pages/serviceCard_pd/team_success/team_success?ordersn=" + odr.order_sn);
            is_ok=0;
        }
      }
    })
    if(!is_ok) return false;

    //获取活动表的信息根据活动team_id
    await getApp().request.promiseGet("/api/weshop/teamlist/get/" + os.stoid + "/" + teamgroup.team_id, {
      data: {}
    }).then(res => {
      if (res.data.code == 0) {
        teamlist = res.data.data;
        goods_id = res.data.data.goods_id;
        //----------查看阶梯团------------
        if (teamlist.ct_rylist != "" && teamlist.ct_rylist != null && teamlist.ct_rylist != undefined) {
          var ct_rylist = JSON.parse(teamlist.ct_rylist);
          var max = 0; var pri = 0;
          ct_rylist.forEach(function (val, ind) {
            if (val.rynum > max) {
              max = val.rynum;
              pri = val.price;
            }
          })
          max_num = max;
          min_price = pri;
        }

      }
    })

    if(!teamlist){
        getApp().showWarning("未找到活动");
        is_ok=0;
    }else{
       if(teamlist.is_end==1){
          getApp().showWarning("拼单活动已经结束"); is_ok=0;
       }
       var now=ut.gettimestamp();
       if(teamlist.end_time<now && is_ok){
         getApp().showWarning("拼单活动已经结束"); is_ok=0;
       }
    }
    if(!is_ok) {
        th.go_back();
        return false;
    }

    //多少人参团头像
    await getApp().request.promiseGet("/api/weshop/rechargeServicelist/pagePtList", {
      data: {
        store_id: o.stoid,
        pt_listno: teamgroup.listno,
      }
    }).then(res => {
      ordertx = res.data.data.pageData;
    })

    //获取商品信息
    await getApp().request.promiseGet("/api/weshop/serviceCard/get/" + os.stoid + "/" + goods_id, {
    }).then(res => {
          //商品地址
          original_img = ee.data.imageurl + res.data.data.original_img,
          goods = res.data.data
    })

    if(!goods){
      getApp().showWarning("拼单活动商品未找到");
      th.go_back();
      return false;
    }
    goods.prom_id=teamgroup.team_id;


    //只装5个
    var ordertx2 = [], sf_num = 0, ct_nun = teamlist.ct_num;
    if (max_num) {
      ct_nun = parseInt(max_num);
      if (ordertx && ct_nun < ordertx.length) ct_nun = ordertx.length;
    }

    if (ct_nun > 5) ct_nun = 5;
    for (var i = 0; i < ct_nun; i++) {
      if (!ordertx || i >= ordertx.length) sf_num++
      else
        ordertx2.push(ordertx[i]);
    }

    var sf_arr = [];
    for (var i = 0; i < sf_num; i++) {
      sf_arr.push(i);
    }
    
    //-- 团期已满的优化 --
    if(th.data.is_group_end==1 || th.data.is_group_end==2 ){
        //getApp().confirmBox(th.data.end_text);
        wx.showToast({
          title: th.data.end_text,
          icon: 'none'
        });
        setTimeout(()=>{
          getApp().goto("/pages/index/index/index"); //返回首页
        },2000)

        return false;
    }

    //--当是会员团的时候才显示倒计时多久可以参团--
    if(teamlist.kttype==2) {
        //显示判断多久才能购买商品,获取没有支付的会员
        await getApp().request.promiseGet("/api/weshop/teamgroup/getTeamUser/" + os.stoid + "/" + teamgroup.id, {
          1: 1
        }).then(res => {
          var em = res;
          if (em.data.code == 0) {
            var tg_list = em.data.data.split("|");
            var t_obj = {};
            t_obj.order_id = tg_list[0];
            t_obj.time = parseFloat(tg_list[1]) + 5 * 60; //五分钟后
            t_obj.user_name = tg_list[2];
            th.setData({tg_arr: t_obj})
          }
        })
    }

    //获取大家都在团信息
    await getApp().request.promiseGet("/api/weshop/teamlist/pageteam/"+os.stoid, {
      data: {
        pageSize: 2,
        page: 1,
        store_id: 1,
        is_end: 0,
        is_show: 1
      }
    }).then(res => {
        if(ut.ajax_ok(res)){
            pageteam = res.data.data.pageData;
        }
    });

    //-- 获取用户的默认门店 --
    getApp().get_user_store(function(ee) {	
      if(!ee) {
        th.data.fir_def_store={}; //赋值空对象
        return false;
      }

      if(getApp().globalData.is_dj_pk) th.setData({has_def:1})
      //--定时器推迟一下--
      setTimeout(function () {
        if(!th.data.goods) return false;
        var g_distr_type=th.data.goods.distr_type;
        //--如果默认门店的配送方式不对，就不能被选择--
        // if(ee.distr_type!=0 && g_distr_type!=0 && ee.distr_type!=g_distr_type ){
		 //  ee.is_no_dis=1;
        // }
        var ser_card = th.data.goods;
        //--如果默认门店不在等级卡的默认们店以内
        if (ser_card.storageId != null && ser_card.storageId != "" && ser_card.storageId.indexOf(ee.keyid) == -1) {
          ee.is_no_dis = 1;
        }

    
        var appd=getApp().globalData;
        var w_time = setInterval(function() {
          if (that.data.is_get_local_ok == 0) return false;
          clearInterval(w_time);
          var e=JSON.parse(JSON.stringify(ee));
    
          //如果有开启近距离的话,同时距离优不一样了
          if (that.data.lat != null) {
            //如果经纬度有变化的话
            if( appd.lat==that.data.lat && appd.lon==that.data.lon  && e.distance>0 ){
              that.data.fir_def_store=e;
              that.setData({
                def_pick_store: e,
                sto_sele_name: e.pickup_name,
                sto_sele_id: e.pickup_id,
                sto_sele_distr: e.distr_type
              })
            }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,is_pos: 1},
              }).then(res=>{
                if(ut.ajax_ok(res)){
                  e=res.data.data.pageData[0];
                  if (e){
                    appd.pk_store=e;
                    that.data.fir_def_store=e;
                    that.setData({
                      def_pick_store: e,
                      sto_sele_name: e.pickup_name,
                      sto_sele_id: e.pickup_id,
                      sto_sele_distr: e.distr_type
                    })
                  }
    
                }
              })
            }
    
            //e.distance = distance;
            appd.lat=that.data.lat;
            appd.lon=that.data.lon;
    
          }else{
            if (e) {
              e.distance = null;
              that.data.fir_def_store=e;
              that.setData({
                def_pick_store: e,
                sto_sele_name: e.pickup_name,
                sto_sele_id: e.pickup_id,
                sto_sele_distr: e.distr_type
              })
            }
          }
    
        }, 500)
      },1000)	
    });
    	
	//获取下redis长度，如果团已经弄完，或者拼单已经卖完
    //设置值
    ee.setData({
      ordertx2: ordertx2,
      ordertx: ordertx,
      teamlist: teamlist,
      teamgroup: teamgroup,
      goods: goods,
      pageteam: pageteam,
      image: original_img,
      is_show:1,
      sf_arr: sf_arr
    });
    ee.countDown2();
	//---设置门店---
    ee.get_sto();
    //---定时设置一下待支付的订单---
	ee.time_out();
  },

  onHide:function(){
    this.setData({is_show:0,});
  },
  go_back:function(){
    if(getCurrentPages()>1)
      wx.navigateBack({delta: 1})
    else
       getApp().goto("/pages/index/index/index");

  },
  //---小于10的格式化函数----
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  countDown2() {
    var th = this;
    // 获取当前时间，同时得到活动结束时间数组
    var newTime = ut.gettimestamp();
    var o = this.data.pindGoods;
    var endTime = o.kt_end_time;

    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime);
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        day: this.timeFormat(day),
        hou: this.timeFormat(hou),
        min: this.timeFormat(min),
        sec: this.timeFormat(sec)
      }
    } else {
      //活动已结束，全部设置为'00'
      obj = {
        day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }
    }
    var txt = "pindGoods.djs";
    th.setData({
      obj: obj
    });
    setTimeout(th.countDown2, 1000);
  },
 
  //------去支付，购买-------
  go_pay:async function () {
      var th=this;
	  var def_pick_store=this.data.def_pick_store;
	  if(def_pick_store && def_pick_store.pickup_id) {
		  th.data.pick_id=def_pick_store.pickup_id;  //选择门店	 
		  th.data.end_name=def_pick_store.pickup_name; 
	  } 	  
      if (!th.data.pick_id) return s.my_warnning("请选择门店", 0, th);
	  if (th.data.pick_id==0) return s.my_warnning("请选择门店", 0, th);

      //----判断起购数----
      var qnum=parseFloat(th.data.teamlist.minbuynum);
      if(qnum>0 && qnum>th.data.num ){
        getApp().confirmBox("拼团商品至少要买"+qnum+"件!");
        return false;
      }


      var minusStatus = th.data.num > 1 ? 'normal' : 'disable';
      //判断限购
      var f=await this.check_num(th.data.num,minusStatus);
      if(!f) return false;


      //先判断团的redis数量
      this.buy_check_redis(function () {
        var arr=th.data.redis_arr;
        if(th.data.num>arr[0]){
          if(arr[0]>0){
            getApp().showWarning("超出活动库存");
          }else{
            getApp().showWarning("拼单已经抢光");
          }
           return false;
        }
        if(th.data.teamlist.kttype==2 && 1>arr[1]){
          getApp().showWarning("拼团已满");
          return false;
        }



        //--------------此时操作的数据------------
        var newd = {
          id: th.data.goods.id,
          goods_num: th.data.num,
          pick_id: th.data.pick_id,
            keyid: th.data.def_pick_store.keyid,
          user_id: oo.user_id,
          store_id: os.stoid,
          goods_name: th.data.goods.service_name,
          goods_sn: th.data.goods.service_sn,
        };

        //---是不是从收藏夹出来的---
        if(th.data.c_guide_id){
          newd['guide_id'] = th.data.c_guide_id;
          newd['guide_type']=2;

        }else{
          if(getApp().globalData.guide_id){
            newd['guide_id'] = getApp().globalData.guide_id;
            newd['guide_type']=0;

          }
        }

        //-----拼团-----
        newd.goods_price = th.data.teamlist.price;
        newd.prom_type = 6;
        newd.prom_id = th.data.teamlist.id;
        newd.kt_type = th.data.teamlist.kttype; //开团类型
        newd.is_pt_tz = 0;
        newd.pick_name = th.data.end_name;
        newd.pick_dis = 1;
        newd.is_normal = 0;
        //判断开团还是参团
        switch (th.data.is_kt_or_ct) {
          case "0":
            //如果不是商家团，就要带团期号
            if(th.data.teamlist.kttype>1){
              newd.qh=th.data.teamgroup.listno;
            }
            break;
          case "1":
            //阶梯团和会员团都要设置is_pt_tz
            if (newd.kt_type > 1) {
              newd.is_pt_tz = 1; //开团类型
            }
            break;
        }
        newd['pick_dis'] = th.data.pick_dis;

        if(getApp().globalData.guide_id){
          newd['guide_id'] = getApp().globalData.guide_id;
          newd['guide_type']=0;
        }

        s.set_b_now(newd);
        wx.redirectTo({
          url: "/packageA/pages/serviceCard_pd/cart/cart?is_bnow=1&goods_id=" + th.data.goods.card_id,
        });
      });
  },

  //购买前的判断redis
  async buy_check_redis(func){
      //获取redis中的数量
      var r_num=0,prom_type=6,prom_id=this.data.teamlist.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;
        }
      })

      //只有会员团要判断团的人数
      var gr_num=0,grp_id=this.data.teamgroup.id;
      if(this.data.teamlist.kttype==2){
        await  getApp().request.promiseGet("/api/weshop/activitylist/getActTuanLen/" + os.stoid + "/" + grp_id, {
          1: 1
        }).then(res => {
          var em = res;
          if (em.data.code == 0) {
            gr_num=em.data.data;
          }
        })
      }
      var arr=[];arr.push(r_num);arr.push(gr_num);
      this.data.redis_arr=arr;
      func();
  },

  //定时设置一下待支付的订单
  time_out:function () {
    var list=this.data.tg_arr,th=this;
    if(!list) return false;
    // 获取当前时间，同时得到活动结束时间数组
    var newTime = ut.gettimestamp();
    var endTime = list.time;

    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime);
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        day: th.timeFormat(day),
        hou: th.timeFormat(hou),
        min: th.timeFormat(min),
        sec: th.timeFormat(sec)
      }
    } else {
      //活动已结束，全部设置为'00'
      obj = {
        day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }

      //调用接口清理订单，并且返回redis数量
      th.back_order(function () {
         th.setData({ tg_arr: null});
      });
      return false;
    }
    var txt = "pindGoods.djs";
    th.setData({
      r_obj: obj
    });
    setTimeout(th.time_out, 1000);
  },

  //清理订单，并且返回redis数量ss
  back_order:function (func) {
      var th=this;
      //---取消订单---
      getApp().request.delete("/api/weshop/order/cancelTeamOrder/"+th.data.stoid+"/"+th.data.tg_arr.order_id,{
            data:{},
            success: function(t) {
                if(t.data.code==0){
                  th.setData({tg_arr:null})
                }
            },
      })
  },

    go_goodsinfo:function (e) {
        var index=e.currentTarget.dataset.index;
        var item=this.data.pageteam[index];
        var gid=item.goods_id;
        var url="/pages/goods/goodsInfo/goodsInfo?goods_id="+gid+"&prom_id="+item.id+"&prom_type=6";
        if(item.goods_type==1){
            url="/packageA/pages/serviceCard_pd/goodsInfo/goodsInfo?goods_id="+gid+"&prom_id="+item.id+"&prom_type=6";
        }
        getApp().goto(url);     //跳到非tabbar页
    },

  gohome:function(){
    getApp().goto("/pages/index/index/index");
  },

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

  //------ 分享配置 --------
  onShareAppMessage: function (e) {
    getApp().globalData.no_clear=1;
    var curPage=this;
    var pagePath = curPage.route; //当前页面url
    if (pagePath.indexOf('/') != 0) {
      pagePath = '/' + pagePath;
    }
    var url=pagePath;

    //--分享图片--
    var img=this.data.iurl+this.data.teamlist.share_imgurl;
    //--把会员分享出去--
    if(getApp().globalData.user_id){
      if(url.indexOf("?")>0)
        url+="&first_leader="+getApp().globalData.user_id;
      else
        url+="?first_leader="+getApp().globalData.user_id;
    }

    if(url.indexOf('goods_id')==-1){
      url+="&goods_id="+this.data.goods.id;
    }

    if(url.indexOf('tg_id')==-1){
      url+="&tg_id="+this.data.teamgroup.id;
    }

    return {
      path:url,
      title: "拼团",
      imageUrl: img,
    }
  },
	

	
	closeSpecModal: function() {
		this.setData({
		  yijian: false
		});
	},
	
	close_popup: function() {
		this.setData({
		  showStore: true
		});
	},
	
	
	
	//-- 选择门店。此时的门店选择与门店有关系 --
	choice_store: function(ee) {

      //--先判断会员状态--
      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;
      }

				
			  var th = this;
			  var bconfig = th.data.bconfig;

        //如果开启了，则不在选择门店
        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){
				getApp().confirmBox("门店库存不足", null, 25000, !1);
				return false;
			  }			
			  if(th.data.only_pk && !th.data.only_pk.length){
				getApp().confirmBox("门店库存不足", null, 25000, !1);
				return false;
			  }
			  if(th.data.def_pickpu_list &&  !th.data.def_pickpu_list.length){
				getApp().confirmBox("门店库存不足", null, 25000, !1);
				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();
			  },
			  fail: function(res) {
				//th.onShow();
				th.data.is_get_local_ok = 1;
				th.get_sto();
				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();
		  }
	
		      this.setData({
			  store: 1,
			  yijian: false,
			  choice_sort_store:0
			})
		  
	},
	

	//选择更多门店
	more_store: function() {
	  this.setData({ sort_store: 1});
	},
	
	// 返回按钮
	returns: function() {
	  this.setData({
	    sort_store: 0,choice_sort_store: 0
	  });
	},
	
	
	//-- 等待获取定位系统 --
	wait_for_store_config: function() {
	  var th = this;
	  var 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)
	},
	
	
	//---------拿出门店分类和门店------------
	get_sto(e) {
	  var th = this,that=this;
	  var timer_get = setInterval(function() {
	    if (th.data.is_get_local_ok == 0) return false;
	    if (!th.data.goods) return false;
        if (!th.data.fir_def_store) return false;

        var dd = null, i = getApp().request;
	    var g_distr_type = th.data.goods.distr_type;

	      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){
	    	th.setData({def_pick_store:th.data.fir_def_store});
	    }
	
	    //----------获取门店----------------
	    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 sto_list = th.data.goods.storageId;
              if (sto_list) {
                for (var k = 0; k < e.data.data.pageData.length; k++) {
                  var it = e.data.data.pageData[k];
                  if (sto_list.indexOf(it.keyid) == -1) {
                    //删除
                    e.data.data.pageData.splice(k--, 1);
                  }
                }
              }

              //如果有秒杀的指定门店
              if( th.data.teamlist && th.data.teamlist.pick_up_lists && e.data.data.pageData.length){
                var pick_up_lists=th.data.teamlist.pick_up_lists;
                for (var kq = 0; kq < e.data.data.pageData.length; kq++) {
                  var it0=e.data.data.pageData[kq];
                  var idx0=pick_up_lists.findIndex(function (e){
                    return e.pickup_id==it0.pickup_id;
                  })
                  if (idx0<0) {
                    //删除
                    e.data.data.pageData.splice(kq--, 1);
                  }
                }

                if (th.data.def_pick_store && JSON.stringify(th.data.def_pick_store)!='{}'){
                  //-- 查找一下门店有没有在 --
                  var idx1=pick_up_lists.findIndex(function (e){
                    return e.pickup_id==th.data.def_pick_store.pickup_id;
                  })
                  if(idx1<0){
                    //如果是秒杀的指定门店，就要设置秒杀的
                    th.data.def_pick_store.is_no_dis_act=1;
                    that.setData({
                      def_pick_store: th.data.def_pick_store
                    })
                  }
                }

              }

              if(e.data.data.pageData.length){
                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;break;
                  }
                }
                e.his_cate_num=his_cate_num;

                //如果有开启距离的功能，没有设置默认门店，要用最近的门店作为默认门店
                if(dd.lat && !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});

                setTimeout(function(){
                  th.deal_pickup(e);  //--普通门店排版--
                },800)
              }

	      }
	    })
	  }, 200)
	
	},
	
	//------------处理门店,拼团活动只有线上库存---------------
	deal_pickup(e){
	  var th=this;	
	  var g_distr_type=th.data.goods.distr_type;	
	  //单总量超出5个的时候
	  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]})
	            }
	          }
	        } 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]})
	          }
	
	        }
	      }
	    });
	  } 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
	      })
	    }
	  }
	},		
	
	
	
	//---选择分类门店---
	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_pick_index: 0,
	  });
	},
	
	choose_for_store_fir: function(e) {
	  var index_c = e.currentTarget.dataset.ind;
	  var th=this;
	  th.setData({
	    fir_pick_index: index_c
	  })	
	},
	
	//---点击二级之后的选择---
	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为选择的门店
	sure_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;
	
	 
	    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
	    });
	
	    
	      th.setData({
	        yijian: 1,      //打开拼团购买界面
	        store: 0,                 //关闭门店
	        choice_sort_store: 0,     //关闭门店2级
	        sort_store: 0,             //关闭门店2级
	      });
	   
	  
	},
	
	
	
	//把选择的门店设置成默认的门店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 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,
	        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 {
	          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
	    });
		 
	      //4就是拼团
	      th.setData({
	        yijian: 1,      //打开拼团购买界面
	        store: 0,                 //关闭门店
	        choice_sort_store: 0,     //关闭门店2级
	        sort_store: 0,             //关闭门店2级
	      });
	      
	},
	
	
	//-- 关闭选择门店 --
	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,
		 yijian: 1,      //打开拼团购买界面
	  })
	
	},


    go_to:function (e) {
        var url=e.currentTarget.dataset.url;
        getApp().goto(url);
    },
  
    //-- 弹出框的同意的优化,重新获取定位 ---
    agree_pri:function (){
      var th=this;
      var bconfig = th.data.bconfig;
      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();
          },
          fail: function (res) {
            //th.onShow();
            th.data.is_get_local_ok = 1;
            th.get_sto();
            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"
              });
            }

          }
        })
      }
    },
	
	
	
	

})