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



Page({
  data: {
    gid: "",
    stoid: o.stoid,
    url: o.url,
    resourceUrl: o.resourceUrl,
    iurl: o.imghost,
    defaultAvatar: o.resourceUrl + "/static/images/user68.jpg",
    data: null,
    openSpecModal: !1,
    openPromModal: !1,
    supportPageScroll: !1,

    //联系电话
    mobile: '',
    bconfig:null,
    sales_rules:1,

    t_time:null,
	card_field:"",
	dp_price:0,
	cut_price:0,
	open_ind_store:1,
	goodsInputNum:1,
	g_buy_num: null,
	sele_collocation:null,

		room_id:0,  //房间号
		is_coupon: 1, //搭配促销禁用 
  },

  //------初始化加载----------
  onLoad: function(t) {
       var goods_id=t.goods_id;
	   var room_id=t.room_id;
	   this.setData({gid:goods_id});
	   
      //群id
      if(t && t.groupchat_id){
        getApp().globalData.groupchat_id=t.groupchat_id
      }
	   if(room_id) this.data.room_id=room_id; //房间号要存起来
	   var ee=this,th=ee,that=ee;
       var  first_leader=t.first_leader;
	   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
			  }
		  })
	   }


	   //----获取系统参数,并判断等级价格-----
	   getApp().getConfig2(function(e) {	     
	     var json_d = JSON.parse(e.switch_list);
	     ee.setData({
	        store_config: e,
		    bconfig: e,
	      	sys_switch:json_d,
	        is_closecoupon: json_d.is_closecoupon,
	     	is_newsales_rules:json_d.is_newsales_rules,
			sales_rules:e.sales_rules, appoint_pick_keyid: json_d.appoint_pick_keyid
	     });
	     //------几人评价-------
	     //计算等级价相关
	     var swithc_list=e.switch_list;
	     var sw_arr=JSON.parse(swithc_list);
	     //---如果后台又开等级卡的开关---
	     if(sw_arr.rank_switch && sw_arr.rank_switch=="2"){
	     	  th.data.rank_switch=true;
	      }
	   });


	   
  },

  //检测有没有导购分享的门店
  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();
		})
	},

  //---展示---
  onShow: function() {

      getApp().check_can_share();
	  var ee=this,th=ee,that=ee;

	  //先获取一下导购的门店
	  this.check_guide(()=> {
		  //获取用户的默认门店
		  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})

			  var appd = getApp().globalData;
			  var w_time = setInterval(function () {
				  if (that.data.is_get_local_ok == 0) return false;
				  if (!that.data.data) return false;
				  clearInterval(w_time);
				  var distance = null;
				  var e = JSON.parse(JSON.stringify(ee));

				  if (th.data.data) var g_distr_type = th.data.data.distr_type;
				  e.is_no_dis = 0;
				  if (e.distr_type != 0 && g_distr_type != 0 && e.distr_type != g_distr_type) {
					  e.is_no_dis = 1;
				  }

				  //如果有开启近距离的话,同时距离优不一样了
				  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 (res.data.code == 0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length) {
								  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)
		  });
	  })

	  var gid = this.data.gid,i = getApp().request;
	ee.data.g_buy_num = new Map();
		this.wait_for_store_config();
		clearTimeout(ot);
    var ot = setTimeout(function () {
    	i.get("/api/weshop/goods/get/" + o.stoid + "/" + ee.data.gid, {
    		failRollback: !0,
    		success: function (t) {
    			if (t.data.code == 0) {
    				if (t.data.data.is_on_sale != 1) {
    					wx.showModal({
    						title: '商品已经下架',
    						showCancel: !1,
    						complete: function () {
    							wx.navigateBack();
    						}
    					});
    				}

    				var timestamp = Date.parse(new Date());
    				timestamp = timestamp / 1000;
    				if (t.data.data.on_time > timestamp) {
    					wx.showModal({
    						title: '商品还未上架',
    						showCancel: !1,
    						complete: function () {
    							wx.navigateBack();
    						}
    					});
    				}

    				if (t.data.data.down_time > 0) {
    					if (t.data.data.down_time < timestamp) {
    						wx.showModal({
    							title: '商品已经到期下架',
    							showCancel: !1,
    							complete: function () {
    								wx.navigateBack();
    							}
    						});
    					}
    				}

    				t.data.data.on_time = ut.formatTime(t.data.data.on_time, 'yyyy-MM-dd hh:mm:ss');
    				var txt = (t.data.data.shop_price / t.data.data.market_price * 10).toFixed(2);
    				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;
    				if (t.data.data.goods_content == null) t.data.data.goods_content = "";

    				//计算商品的规格
    				var gg = "";
    				if (t.data.data.goods_spec == "null" || t.data.data.goods_spec == null) t.data.data.goods_spec = "";
    				if (t.data.data.goods_color == "null" || t.data.data.goods_color == null) t.data.data.goods_color = "";

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


						
    				    if (!ee.data.collocationList) {
						var user_id=getApp().globalData.user_id || 0;
    					/*---获取活动的重表---*/
    					//调用接口判断订单优惠，
    					getApp().request.promiseGet("/api/weshop/goods/getGoodsPromListNew/" + os.stoid + "/" + ee.data.gid + "/2"+"/"+user_id, {}).then(res => {
    						if (res.data.code == 0) {

								var r_data = res.data.data;

								th.data.is_coupon = r_data.collocationPromList.is_coupon;


								t.data.data.prom_id=r_data.collocationPromList.id;

    							th.loop_promise(0, r_data.collocationList, function () {

									var set_data=JSON.parse(JSON.stringify(r_data.collocationList));

									//如果是线上的时候，过滤掉线上库存未0的商品
									if(th.data.sales_rules==1){
										set_data=set_data.filter(function (e){
											return e.store_count>0;
										})
									}

									//设置搭配购是否使用优惠卷
    								ee.setData({
    									collocationGoods: r_data.collocationPromList,
    									collocationList: set_data,
    								})
    							})
    						}
    					})
    				}


					//--看一下有没有开启等级卡---
					if (ee.data.rank_switch) {
						//---回调卡的列表---
						th.getPlusCardType(function (ob) {
							var user = getApp().globalData.userInfo;
							if (user) {
								if (user.card_field && user['card_expiredate']) {
									var str = user['card_expiredate'].replace(/-/g, '/');
									var end = new Date(str);
									end = Date.parse(end) / 1000;
									var now = ut.gettimestamp();
									//--- 判断是等级会员，且在有效期范围内 ---
									if (user.card_field && now < end) {
										var card_name = ob.name_map.get(user.card_field);
										if (card_name && card_name.length > 5) card_name = card_name.substring(0, 5);
										th.setData({
											card_field: user.card_field,
											card_name: card_name
										});
										if (t.data.data[user.card_field] > 0) t.data.data.shop_price = t.data.data[user.card_field];
									}
								}
							}
							ee.setData({
								data: t.data.data,
							});
						})
					} else {
						ee.setData({
							data: t.data.data,
						});
					}



    				    //获取统一条形码,普通商品和优惠促销的商品
    					//默认门店要拿下门店库存
    					if (!getApp().is_virtual(t.data.data) && !t.data.data.whsle_id && that.data.sales_rules >= 2) {
    						//--等待某个值只运行---,这里有可能因为导航的时间太久，而不能计算门店库存
    						getApp().waitfor2(that, "wait_for_user_store", "fir_def_store", function () {



    							if (th.data.fir_def_store && th.data.fir_def_store.pickup_id) {
    								var lock = 0,plist = null;
									var lock_rq={
										store_id: os.stoid,wareId: ee.data.data.goods_id,
										storageId: that.data.fir_def_store.pickup_id,pageSize: 1000
									}

									//-- 指定门店销售的时候 --
									if(that.data.sales_rules == 3){
										lock_rq.appoint_pick_keyid = encodeURIComponent(th.data.appoint_pick_keyid);
										delete lock_rq.storageId
									}

    								//先读取门店的lock,采用链式写法，少用await
    								getApp().request.promiseGet("/api/weshop/order/ware/lock/page", {
    									data:lock_rq
    								}).then(res => {
    									if (res.data.code == 0 && res.data.data.total > 0) {
    										for (var i in res.data.data.pageData)
    											lock += res.data.data.pageData[i].outQty
    									}

										var dw_rq={
											storageNos: that.data.fir_def_store.pickup_no,
											wareIds: encodeURIComponent(th.data.data.erpwareid),
											storeId: os.stoid,pageSize: 2000
										}
										if(that.data.sales_rules == 3){
											dw_rq.storageIds = encodeURIComponent(th.data.appoint_pick_keyid)
											delete dw_rq.storageNos
										}

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


    									if (res.data.code == 0 && res.data.data.total > 0) {
    										plist = res.data.data.pageData[0];
    									}
    									if (plist && plist.CanOutQty - lock > 0) {
    										that.data.fir_def_store.CanOutQty = plist.CanOutQty - lock;
    									} else {
    										that.data.fir_def_store.CanOutQty = 0;
    									}
    									//--给门店赋值线下库存--
    									th.setData({
    										def_pick_store: that.data.fir_def_store
    									});
    									//获取门店
    									ee.get_sto();
    								})
    							} else {
    								//--获取门店--
    								ee.get_sto();
    							}
    						})
    					} else {
    						//获取门店
    						ee.get_sto();
    					}


    			}
    		}
			});
			clearTimeout(ot);
    }, 1000)
  },
	
  onUnload: function() {},
  onHide: function() {
     clearInterval(this.data.t_time);
  },
  //--滚动到顶部--
  doScrollTop: function() {
    wx.pageScrollTo({
      scrollTop: 0
    });
  },
  //------------加入购物车--------------
  addCart: function(t) {
      var th = this;
	  if(this.data.lding) return false;
	  th.setData({lding:1})
      th.add_cart_func(t);

  },
  //加入购物的函数
  add_cart_func: function(t) {
    var i = getApp().request;
    if (oo.user_id == null) {
		th.setData({lding:0})
      return s.my_warnning("还未登录！", 0, this);
    }
    var e = this,
      th = e,
      a = 0,
      o = this.data.data;
      a = o.goods_id;
    //----------添加到购物车时，要判断限购数量，--------
    e.get_buy_num(o, async function(ee) {
      //---判断商品是否超出限购---
      if (th.data.g_buy_num != null && th.data.data.viplimited > 0) {
        if (th.data.goodsInputNum + th.data.g_buy_num.get(th.data.data.goods_id) > th.data.data.viplimited) {
          wx.showModal({
            title: '提示',
            content: '超出商品限购'
          });
		  th.setData({lding:0})
          return false;
        }
      }
      //---判断商品是否超出活动限购---
      if (th.data.prom_buy_num != -1 && th.data.prom_buy_limit > 0) {
        if (th.data.goodsInputNum + th.data.prom_buy_num > th.data.prom_buy_limit) {
          wx.showModal({
            title: '提示',
            content: '超出商品活动限购'
          });
		  th.setData({lding:0})
          return false;
        }
      }

      if (th.data.goodsInputNum <= 0){
		  th.setData({lding:0})
		  return s.my_warnning("商品数量不能为0", 0, th);
	  }
      if (th.data.sto_sele_name == null || th.data.sto_sele_name == undefined)
        this.setData({
          sto_sele_name: ""
        });
      if (th.data.sto_sele_name == ""){
		  th.setData({lding: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_type: 5,
		prom_id:th.data.collocationGoods.id
      };

		//---是不是从收藏夹出来的---
		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;
			}
		}

        //如果有导购ID的话
		if(newd['guide_id'] && th.data.sele_collocation){
             for(var jj in th.data.sele_collocation ){
				 th.data.sele_collocation[jj]['guide_id']=newd['guide_id'];
				 th.data.sele_collocation[jj]['guide_type']=newd['guide_type'];
			 }
		}
		
		//-- 如果有房间号的时候 --
		if(th.data.room_id){
			newd['room_id']=th.data.room_id;
			for(var nn in th.data.sele_collocation ){
				th.data.sele_collocation[nn]['room_id']=newd['room_id'];
			}
		}
		

      //-----如果是秒杀，团购，积分购,拼团-----
      // if (th.data.data.prom_type != 5) {
		//   th.setData({lding:0})
		//  return s.my_warnning("商品不是搭配活动！", 0, th);
      // }else{

		//---如果是线下门店销售的时候---
		if(th.data.sales_rules>=2){

			var pick=th.get_pick_from_list(th.data.sto_sele_id)

			var dw_rq={storageNos:pick.pickup_no,wareIds:encodeURIComponent(th.data.data.erpwareid),storeId:os.stoid,pageSize:2000};
			if(th.data.sales_rules == 3){
				dw_rq.storageIds = encodeURIComponent(th.data.appoint_pick_keyid)
				delete dw_rq.storageNos
			}

			//---通过接口获取门店的线下库存信息--
			getApp().request.get("/api/weshop/goods/getWareStorages",{
				  data:dw_rq,
				  success:function(res){
					 if(res.data.code==0){																	 
						   if(res.data.data.pageData.length>0){
							    var CanOutQty=res.data.data.pageData[0].CanOutQty;
								if(CanOutQty<e.data.goodsInputNum){
									 th.setData({lding:0})
									 return s.my_warnning("库存不足！", 0, th);	
								}

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

							    //-- 指定门店销售的时候 --
							    if(th.data.sales_rules == 3){
								   lock_rq.appoint_pick_keyid = encodeURIComponent(th.data.appoint_pick_keyid);
								   delete lock_rq.storageId
							    }
								//在调一次接口,读取商品的预出库的数量，lock
								getApp().request.get("/api/weshop/order/ware/lock/page",{
									data:lock_rq,
									success:function(res_data){
										 if(res_data.data.code==0 &&  res_data.data.data.total>0){
											   var lock=0;
											   for(var i in res_data.data.data.pageData){
												   lock+=res_data.data.data.pageData[i].outQty;
											   }
											  											  											  
											  if(CanOutQty<=lock){
												   th.setData({lding:0})
												   return s.my_warnning("库存不足！", 0, th);	
											  }
											  th.add_cart_next(e,t,a,o,newd,CanOutQty-lock);  
										 }else{
											 th.add_cart_next(e,t,a,o,newd,CanOutQty);  
										 }
									}
								})														
						    }else{
							    th.setData({lding:0})
								return s.my_warnning("库存不足！", 0, th);	
							} 
					    
					   }				
				  }
			})			
		}else{
			if (o.store_count <= 0) {
				th.setData({lding:0})
				return s.my_warnning("库存已为空！", 0, th);
			}
			if (o.store_count <e.data.goodsInputNum) {
				th.setData({lding:0})
				return s.my_warnning("库存不足！", 0, th);
			}
			th.add_cart_next(e,t,a,o,newd);  //加入购物车下一步
		}

      // }
    })
  },

  //---加入购物车的最后一步---
	add_cart_next(e, t, a, o, newd, CanOutQty) {
		var th = this;
		//---如果商品不是积分购和拼团,要判断一个是否要进行等级价的判断------
		if (o.prom_type != 1 && o.prom_type != 6) {
			var conf = th.data.bconfig;
			if (conf.switch_list && getApp().globalData.userInfo['card_field']) {
				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['pick_name'] = th.data.sto_sele_name;
		//newd['pick_dis'] = th.data.sto_sele_distr;

		this.check_sele_collocation(function (collocationGoods) {
			var is_ok = 1;
			if (th.data.sales_rules > 1) {

				for (let j = 0; j < collocationGoods.length; j++) {
					var item = collocationGoods[j];
					if (item.CanOutQty<=0) {
						is_ok=0;
						wx.showToast({
							title: item.goods_name+ "库存不足",
							icon: 'none',
							duration: 2000
						})

						break;
					}
				}
			}

			if(!is_ok){
				th.setData({lding:0})
				return false;
			}
			//newd["collocation_goods"] = collocationGoods;
			//newd["is_coupon"] = th.data.is_coupon;
			th.buyNow(newd,collocationGoods);
		})

	},

  //----------立即购买-----------
  buyNow:async function(e,collocationGoods) {
    //s.set_b_now(e);
    // wx.redirectTo({
    //   url: "/packageE/pages/cart/cart2/cart2?is_bnow=1&goods_id=" + e.goods_id,
    // });
	console.log(1111);
    console.log(e);
    console.log(collocationGoods);
	var th=this;

	  //----其他就按照公众号的购物车立即购买形式来修改，先看会员在购物车中是否加入了该商品,立即购买的-----
	  var res=await getApp().request.promiseGet("/api/weshop/cart/page", {
		  data: {
			  store_id: os.stoid,
			  user_id: oo.user_id,
			  state: 1
		  }
	  })

	  //-------如果购物车中有相关的数据---------
	  if (res.data.code == 0 && res.data.data.total > 0) {
		  for (let j in res.data.data.pageData) {
			  let item_j = res.data.data.pageData[j];
			  var url = '/api/weshop/cart/del/' + os.stoid + '/' + item_j.id;
			  getApp().request.delete(url, {});
		  }
	  }

	  //-- 推迟一下，因为删除没有那么快 --
	  setTimeout(async () => {
		  e.state = 1;
		  e.selected=1;
		  var dp_rs= await getApp().request.promisePost("/api/weshop/cart/save", {
			  data: e,
		  });

		  if(!dp_rs || dp_rs.data.code!=0){
			  return false;
		  }

		  for (let j = 0; j <collocationGoods.length ; j++) {
			  var c_gd=collocationGoods[j];
			  var save_data = {
				  goods_id: c_gd.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: c_gd.goods_price,
				  member_goods_price: c_gd.goods_price,
				  goods_name: c_gd.goods_name,
				  goods_sn: c_gd.goods_sn,
				  sku: c_gd.sku,
				  prom_type: 5,
				  prom_id:e.prom_id,
				  is_collocation:1,
				  state:1,
				  selected:1
			  };
			  await getApp().request.promisePost("/api/weshop/cart/save", {
				  data: save_data,
			  });
		  }
		  setTimeout(()=>{ th.setData({lding:0}) },500);

		  getApp().goto("/packageE/pages/cart/cart2/cart2?state=1");



	  }, 500)
  },

  //----------增加购买数量-----------
  addCartNum: function(t) {
    this.checkCartNum(this.data.goodsInputNum + 1);
  },
  //----------减少购买数量-----------
  subCartNum: function(t) {
    this.checkCartNum(this.data.goodsInputNum - 1);
  },
  //----------输入框输入购买数量-----------
  inputCartNum: function(t) {
    this.checkCartNum(Number(t.detail.value));
  },

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

      //--判断商品是否超出限购--
      if (th.data.g_buy_num != null && th.data.data.viplimited > 0) {
		  
		var gd_buy_num=th.data.g_buy_num.get(th.data.data.goods_id);
		  
        if (t + gd_buy_num > th.data.data.viplimited) {
          wx.showModal({
            title: '超出商品限购',
          });
		  
		  var num= th.data.data.viplimited-gd_buy_num;
		  if(num<=0) num=1
		  th.setData({goodsInputNum:num})	
          return false;
        }
      }

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

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

        if (t > redis_num) {
          wx.showModal({
            title: '超出商品活动库存',
          });		  
		  th.setData({goodsInputNum:redis_num})	  
          return false;
        }

      }

      var e = th.data.data.store_count;
	  if(th.data.sales_rules>=2){
		  if(!th.data.def_pick_store){
			   wx.showModal({ title: '请选择门店', });
			   return false;
		  }else{
			  e=th.data.def_pick_store.CanOutQty;		 
		  }		  
	  }
	  
	  //库存不足，不增加
	  if(e<t){ wx.showModal({ title: '库存不足', }); 
	          if(e<0) e=0;    
			  th.setData({ goodsInputNum: e });   return false;
		}		 		  		 
	  t > e || 0 == e ? t = e : t < 1 && (t = 1);
	  th.setData({ goodsInputNum: t });
	       
    })
  },

  closeSpecModal: function() {
  	var th=this;
    this.setData({
      openSpecModal: !1,
      openSpecModal_pt: !1
    });
  },
  openSpecModel: function(t) {
	var th = this;
    this.setData({
      store: 0,
      choice_sort_store: 0,
      sort_store: 0,
    })
    //--先判断会员状态--
    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 collocationList=this.data.collocationList;
	  this.data.sele_collocation=null;
	  for(var i in collocationList){
		  if(collocationList[i].sele){
			   collocationList[i].goods_num=1;
			   collocationList[i].prom_type=5;
			   collocationList[i].prom_id=th.data.data.prom_id;
			   collocationList[i].goods_price=collocationList[i].price;
			   collocationList[i].is_collocation=1;
			   if(!th.data.sele_collocation) th.data.sele_collocation=new Array();
			   th.data.sele_collocation.push(collocationList[i]);
			   
			   var the_dis_t=collocationList[i].distr_type;
			   //如果有默认门店的判断门店匹配情况
			   if(th.data.def_pick_store && th.data.def_pick_store.distr_type!=0 && the_dis_t!=0 && the_dis_t!=th.data.def_pick_store.distr_type ){
				   th.data.def_pick_store.is_no_dis=1;
				   th.setData({def_pick_store:th.data.def_pick_store});
			   }else{
			   	 if(th.data.def_pick_store){
                     th.data.def_pick_store.is_no_dis=0;
                     th.setData({def_pick_store:th.data.def_pick_store});
				 }

			   }
		  }
	  }
	  if(!th.data.sele_collocation){
		  return s.my_warnning("请选择搭配商品！", 0, th);
	  }


    this.setData({
      openSpecModal: !0,
    });
  },
  closePromModal: function() {
    this.setData({
      openPromModal: !1
    });
  },

  openPromModal: function() {
    this.setData({
      openPromModal: !0
    });
  },

  //--点击分享事件---
  onShareAppMessage: function(t) {
      getApp().globalData.no_clear=1
	  var curPage=this;
	  var pagePath = curPage.route; //当前页面url
	  if (pagePath.indexOf('/') != 0) {
		  pagePath = '/' + pagePath;
	  }
	  if(getApp().globalData.user_id){
		  if(pagePath.indexOf("?")>0){
			  pagePath+="&goods_id="+this.data.gid+" &first_leader="+getApp().globalData.user_id;
		  }else{
			  pagePath+="?goods_id="+this.data.gid+"&first_leader="+getApp().globalData.user_id;
      }
           //群id分享
           if (getApp().globalData.groupchat_id) {
            pagePath+="&groupchat_id="+getApp().globalData.groupchat_id
          }
	  }else{
      if(pagePath.indexOf("?")>0){
        pagePath+="&groupchat_id="+getApp().globalData.groupchat_id
      }else{
        pagePath+="?groupchat_id="+getApp().globalData.groupchat_id
      }

    }

	  console.log("111");
	  console.log(pagePath);

    return {
      title: "搭配购",
      path: pagePath,
    }

  },

  //-----图片失败，默认图片-----
  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) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ;
  },

  //-----图片失败，默认图片-----
  bind_bnerr2: function(e) {

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

  //---------拿出门店分类和门店------------
  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.data) return false;

        var dd = null,
		c_list=th.data.collocationList,
        i = getApp().request;
        var g_distr_type = th.data.data.distr_type;
		var collocationList=th.data.collocationList;
	
		//获取所有的门店
		if(g_distr_type==0 && collocationList ){
			for(var i in collocationList){
				  if(collocationList[i].sele && collocationList[i].distr_type>0){
					  g_distr_type=collocationList[i].distr_type;
				  }
			}		  
		}
	   
      if (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,
          pageSize: 2000
        }
      }
      //如果有距离的话
      if (th.data.lat != null) {
        dd.lat = th.data.lat;
        dd.lon = th.data.lon;
      }
      clearInterval(timer_get);
      //----------获取门店----------------
      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 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) {
            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(th.data.sales_rules>=2 && !th.data.is_newsales_rules && th.data.prom_type!=1 && th.data.prom_type!=6){
			  setTimeout(function(){
				   th.deal_pickup_dline(e);
			  },800)			 
		  }else{
			  setTimeout(function(){
			      th.deal_pickup(e);  //--普通门店排版--
			  },800)
		  }      
		}
      })
    }, 200)
  },
  
  //------------处理门店---------------
  deal_pickup(e){
	  var th=this;
	  //单总量超出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
	      })
	    }
	}
	    
  },
  //------------处理线下门店库存--------
  deal_pickup_dline(e){
	  var pkno=[],th=this;
	  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);
	  }	  
	  var pkno_str=pkno.join(",");
	  var o_plist=e.data.data.pageData;
	  var new_list=[];
	  var is_find_def_store=0;
	  
	  var lock=[];

	  var lock_rq={store_id:os.stoid,wareId:th.data.data.goods_id,pageSize:1000};
      //-- 指定门店销售的时候 --
	  if(th.data.sales_rules == 3){
		  lock_rq.appoint_pick_keyid = encodeURIComponent(th.data.appoint_pick_keyid);
		  delete lock_rq.storageId
	  }

	  //先读取门店的lock,采用链式写法，少用await
	  getApp().request.promiseGet("/api/weshop/order/ware/lock/page",{
		  data:lock_rq
	  }).then(res=>{
		  if(res.data.code==0 && res.data.data.total>0){
			  lock=res.data.data.pageData
		  }


		  var dw_rq={storageNos:pkno_str,wareIds:encodeURIComponent(th.data.data.erpwareid),storeId:os.stoid,pageSize:2000};
		  if(th.data.sales_rules == 3){
			  dw_rq.storageIds = encodeURIComponent(th.data.appoint_pick_keyid)
			  delete dw_rq.storageNos
		  }
		  //---通过接口获取门店的线下库存信息--
		  return  getApp().request.promiseGet("/api/weshop/goods/getWareStorages",{
		      data:dw_rq
	      })
	  }).then(res=>{
		  if (res.data.code == 0) {
			  if (res.data.data.pageData && res.data.data.pageData.length) {
				  var plist = res.data.data.pageData;
				  var def_pick_store = th.data.def_pick_store;
				  var g_distr_type=null;
				  if(th.data.data)  g_distr_type=th.data.data.distr_type;

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

					  } 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]);
									  //如果找到默认门店
									  if (th.data.fir_def_store && n_item.StorageNo == th.data.fir_def_store.pickup_no) {
										  th.data.fir_def_store.CanOutQty = n_item.CanOutQty - lock_num;
										  if (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;
									  }
								  }
								  break;
							  }
						  }
					  }
				  }

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

				  if (th.data.fir_def_store && !is_find_def_store && th.data.fir_def_store.pickup_id) {
					  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);
					  }
				  }


				  //---把数组组装进去---
				  th.deal_pickup(em);
			  } else {
				  th.setData({def_pick_store: null, all_sto: null, only_pk: null})
			  }
		  } else {
			  th.setData({def_pick_store: null, all_sto: null, only_pk: null})
		  }
	  })	  	  
  },

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

  //----------取货门店被点击的效果------
  getmendian: function(t) {
    this.setData({
      ismend: 1,
    });
  },
  //----------隐藏取货门店，选取门店----------
  hidemend: function(e) {
    var pid = e.target.dataset.p_id;
    var pname = e.target.dataset.p_name;
    var p_distr_t = e.target.dataset.p_dis;
    this.setData({
      ismend: 0,
      is_sec_mend: 0,
      sto_sele_id: pid,
      sto_sele_name: pname,
      sto_sele_distr: p_distr_t
    });
  },
  //------显示取货2级----------
  show_sec: function(t) {
    var index = t.target.dataset.index;
    var item = this.data.all_sto[index];
    this.setData({
      is_sec_mend: 1,
      sec_sto: item
    });
  },
  //------隐藏取货门店2级----
  hide_sec_mend: function() {
    this.setData({
      is_sec_mend: 0,
    });
  },

  //加载更多是靠这个函数
  onReachBottom: function() {

  },
  //--------检查是搭配促销活动是不是结束-------
  async check_prom(gid, prom_type, prom_id) {

  },

  //-------------获取购买数量的总函数----------------
  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 (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.goodsbuynum,
                    });
                    "function" == typeof func && func();
                  }
                }
              });
            } else {
              map.set(gd.goods_id, g_buy_num);
              th.setData({
                g_buy_num: map
              });
              "function" == typeof func && func();
            }
          }
        }
      });
    }
  },

  //--跳转到商品详情页面--
  go_goods: function(e) {
    var gid = e.currentTarget.dataset.gid;
    var url = "/pages/goods/goodsInfo/goodsInfo?goods_id=" + gid;
    getApp().goto(url);
  },

  // 选择门店
  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 ind=ee.currentTarget.dataset.ind;
    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();
    }
	
	if(ind!=undefined && ind!=null ){
		this.setData({
		  open_ind_store: ind,
		  store: 1,
		  openSpecModal: !1,
		  openSpecModal_pt: !1
		})
	}else{
		this.setData({
		  store: 1,
		  openSpecModal: !1,
		  openSpecModal_pt: !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
	  })
	}

  },
  
  //选择更多门店
  more_store: function() {
    this.setData({
      sort_store: 1
    });
  },

  //---选择分类门店---
  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
    })

  },
  
  //如果开启线下库存，已经急速库存才会使用
  async check_the_pick(item,func){
	  var th=this;
	  var goodsinfo=th.data.data;
	  var erpwareid=goodsinfo.erpwareid;
	  var plist=null;
      var lock=0;
	  
	  //---如果是活动的时候,或者是虚拟商品的时候---
	  if(th.data.prom_type==1 || th.data.prom_type==6 || getApp().is_virtual(goodsinfo)){
	     func(); return false;  		 
	  }
	      
	  if(this.data.sales_rules<2){
		  func();
	  }else{


		  // var lock_rq={store_id:os.stoid,wareId:goodsinfo.goods_id,storageId:item.pickup_id,pageSize:1000};
		  // //-- 指定门店销售的时候 --
		  // if(th.data.sales_rules == 3){
			//   lock_rq.appoint_pick_keyid = encodeURIComponent(th.data.appoint_pick_keyid);
			//   delete lock_rq.storageId
		  // }
		 	//
		  // //先读取门店的lock
		  // await getApp().request.promiseGet("/api/weshop/order/ware/lock/page",{
		  // 		  data:lock_rq
		  // }).then(res=>{
		  // 		  if(res.data.code==0 && res.data.data.total>0){
			// 		  for(var i in res.data.data.pageData )
		  // 			      lock+=res.data.data.pageData[i].outQty;
		  // 		  }
		  // })
		  //
		  // var dw_rq={storageNos:item.pickup_no,wareIds:encodeURIComponent(erpwareid),storeId:os.stoid,pageSize:2000};
		  // if(th.data.sales_rules == 3){
			//   dw_rq.storageIds = encodeURIComponent(th.data.appoint_pick_keyid)
			//   delete dw_rq.storageNos
		  // }
		  //
		  // //读取线下的门店库存
		  // await getApp().request.promiseGet("/api/weshop/goods/getWareStorages",{
		  // 		  data:dw_rq
		  // }).then(res=>{
		  // 		  if(res.data.code==0 && res.data.data.total>0){
		  // 			  plist=res.data.data.pageData[0];
		  // 		  }
		  // })
		  //
		  // if(plist && plist.CanOutQty-lock>0){
			//      item.CanOutQty=plist.CanOutQty-lock;
		  //    	 func();
			// 	 return false;
		  // }
		  // getApp().my_warnning(item.pickup_name+"库存不足！", 0, th);

		  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();

		  });

				   
	  }
  },

  //确定def_pick为选择的门店
  sure_pick: function(e) {
    var th = this;
    var item = null;
    var openindstore = 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;

	
	//--回调函数的用法--
	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
		  });
		  
		  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: 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;
	
	//先设置之前,要判断是不是有库存
	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,
		      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,
		    })
		  }
	})
  },

  wait_for_store_config: function() {
    var th = this;
    th.data.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(th.data.t_time);
    }, 500)
  },

  //-- 根据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;
			}
	   }	   
   },
  
   //---  获取卡类列表 ---
   getPlusCardType: function (func) {
      var storid = os.stoid;
      var th = this;
      getApp().request.promiseGet("/api/weshop/plus/vip/mem/bership/list?" + "storeId=" + storid, {}).then(res => {

        if(res.data.code!=0 || !res.data.data){
           var ob={"card_list":[],"name_map":''};
           func(ob);
           return false;
        }

        var plusCard = res.data.data;
        var arr = [1219, 2089, 3031];
        var new_arr = new Array();
   		  var card_name_map=new Map();
        for (var i = 0; i < plusCard.length; i++) {
   			var name="card"+plusCard[i].CorrPrice.toLowerCase();
   			card_name_map.set(name,plusCard[i].CardName);
        }
   
   		  var ob={"card_list":plusCard,"name_map":card_name_map};
   		  func(ob);
      })
    },
		
	//递归获取商品
	loop_promise:  function(x,arr,func){
		 var th=this;
		 var g_data=null;
		  getApp().request.promiseGet("/api/weshop/goods/get/" + o.stoid + "/" + arr[x].goods_id, {}).then(res => {
              if(res.data.code==0 && res.data.data){
				  g_data=res.data.data;
				  if(g_data){
					  arr[x].goods_spec=g_data.goods_spec;
					  arr[x].goods_color=g_data.goods_color;
					  arr[x].original_img=g_data.original_img;
					  arr[x].shop_price=g_data.shop_price;
					  arr[x].store_count=g_data.store_count;
				  }
			  }

			  if(x==arr.length-1){
				  func(arr);	 //循环再最后
			  }else{
				  ++x;
				  th.loop_promise(x,arr,func);
			  }
		 })

	},


	//线下的时候判断库存
	async check_sele_collocation(func){
	    var th=this;
		var pick =this.get_pick_from_list(th.data.sto_sele_id);
        var collocationGoods= this.data.sele_collocation;
		if(this.data.sales_rules>1){
			for (let j = 0; j < collocationGoods.length; j++) {

				var goodsinfo=collocationGoods[j];
				var sales_rules = this.data.sales_rules;
				var lock_rq = {
					store_id: os.stoid,
					wareId: goodsinfo.goods_id,
					pageSize: 1000
				};

				if (sales_rules == 2) {
					lock_rq.storageId =pick.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 = pick.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;
				}
				collocationGoods[j].CanOutQty=CanOutQty;
			}
		}
		func(collocationGoods);
	},

	//图片失败，默认图片
	bind_bnerr3: function(e) {
	     	var _errImg = e.target.dataset.errorimg;
			var _errObj = {};
			_errObj[_errImg] = "/public/images/default_goods_image_240.gif";
			this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ;
	},
	//判断来个商品的配送的方式是不是一致
	check_men_dian(g1,g2){
		if(g1.distr_type!=0 && g2.distr_type!=0 && g1.distr_type!=g2.distr_type){
			return 0;
		}
		return 1;
	},

	set_sele:async function (e) {
		 var th=this;
		 var index=e.currentTarget.dataset.ind;
		 var set=e.currentTarget.dataset.set;
		 var text="collocationList["+index+"].sele";
		 
		 //判断门店匹配不匹配
		 var click_item=this.data.collocationList[index];
		 var c_list=this.data.collocationList;
		 if(set==1){
			 //-- 选择的商品的门店配送方式和主商品比较 --
			 if(!th.check_men_dian(click_item,th.data.data)){
				 wx.showToast({
					 title: "商品的配送方式不一致",
					 icon: 'none',
					 duration: 2000
				 })
				 return false;
			 }
			 //-- 判断从商品 --
			 for(var ij in this.data.collocationList){
				  if(this.data.collocationList[ij].sele){
					  if(!th.check_men_dian(click_item,this.data.collocationList[ij])){
					  				 wx.showToast({
					  					 title: "商品的配送方式不一致",
					  					 icon: 'none',
					  					 duration: 2000
					  				 })
					  				 return false;
					  }
				  }
			 }

			 //判断搭配商品的限购
			 var gd= await getApp().request.promiseGet("/api/weshop/goods/get/" + os.stoid + "/" + click_item.goods_id, {});
			 if(gd && gd.data.code==0 && gd.data.data && gd.data.data.viplimited>0){

				 gd=gd.data.data;
				 var g_buy_num=0;

				 //----获取商品购买数----
				 var buyed=await getApp().request.promiseGet("/api/weshop/ordergoods/getUserBuyGoodsNum", {
					 data: {
						 store_id: os.stoid,
						 user_id: getApp().globalData.user_id,
						 goods_id: gd.goods_id, isnew: 1,
						 timetype: gd.viplimited_timetype
					 }
				 })

				 if(buyed && buyed.data.code==0){
					 g_buy_num = buyed.data.data.goodsbuynum;
				 }

				 if(g_buy_num>=gd.viplimited){
					 wx.showToast({
						 title: "搭配商品超出限购",
						 icon: 'none',
						 duration: 2000
					 })
					 return false;
				 }

			 }


		 }



		 	
		 var ob={};
		 ob[text]= parseInt(set);
		 this.setData(ob);

		 var price=parseFloat(this.data.collocationList[index].price);
		 var cut_pirce=this.data.collocationList[index].shop_price-price;
		 if(set==1){
			 this.data.dp_price=parseFloat(this.data.dp_price)+price;
			 this.data.cut_price=this.data.cut_price+cut_pirce;
		 }else{
			 this.data.dp_price=parseFloat(this.data.dp_price)-price;
			 this.data.cut_price=this.data.cut_price-cut_pirce;
		 }		 
		 price=price.toFixed(2);		 		 
		 cut_pirce=cut_pirce.toFixed(2);		 		 
		 this.setData({dp_price: this.data.dp_price,cut_price:this.data.cut_price});
	},

	go_goods:function (e) {
		var gid=e.currentTarget.dataset.gid;
		var url="/pages/goods/goodsInfo/goodsInfo?goods_id="+gid;
		getApp().goto(url);
	},

    // 返回按钮
    returns: function () {
        this.setData({
            sort_store: 0,
            choice_sort_store: 0
        });
    },

	//统一一下获取线下库存的函数
	async check_CanOutQty(goodsinfo, item, func,pickup_id) {

		var sales_rules = this.data.sales_rules;

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

		if (sales_rules == 2) {
			lock_rq.storageId =item?item.pickup_id: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);

	},


});
