// packageA//pages/distribution/main/main.js
const app =  getApp();
let self = null, os = app.globalData.setting;
var regeneratorRuntime = require('../../utils/runtime.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
	  buy_goods:null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	    self = this;//保存全局指针
		if(app.globalData.userInfo) {
			self.setData({
				userInfo: app.globalData.userInfo,
			});
		}else{
		    getApp().goto("/packageE/pages/togoin/togoin") //跳到非tabbar页
		}	
		wx.setNavigationBarTitle({
		  title: "我的分销",
		});
	
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
	  var self=this;
	  // 广告banner
	  app.request.promiseGet("/api/weshop/ad/page", {
	    data: {
	  		pid: 401,
	        enabled: 1,
	  		store_id: app.globalData.setting.stoid,
	    }
	  }).then(res => {
	    if(res.data.code == 0 && res.data.data) {
	        let item = res.data.data.pageData[0];
	  		if(item && item.ad_code) {
	  			self.setData({
	  				ad_img: item.ad_code,
	  			});
	  		};         
	    };
	  });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
        getApp().check_can_share();
		if (typeof this.getTabBar === 'function' && this.getTabBar()) {
			this.getTabBar().setData({
				active: 2
			})
		};
		
	    var self=this,userinfo=app.globalData.userInfo;
		if(!app.globalData.userInfo){
			 return false;
		}			
		//-- 会员实时的信息获取 --
		getApp().promiseGet("/api/weshop/users/get/" + userinfo.store_id + "/" + userinfo.user_id,{}).then(res=>{
			      if(res.data.code!=0){	  
					  wx.showToast({
					    title: "获取会员失败",
					    icon: 'none',
					    duration: 2000
					  });	
					  return false;
				  }
		
			      userinfo=res.data.data;				  
			      self.setData({
			      	userInfo: userinfo,
			      	imghost: app.globalData.setting.imghost,					
			      });					  
				  app.globalData.userInfo=userinfo;
			      wx.setStorageSync("userinfo",userinfo);	
				  //-- 获取分销的内容 --			
				  self.show_dis();						 
			})
			wx.removeStorageSync('total');
			wx.removeStorageSync('newListTotal');

			
  },
  
  //-- 优化小程序没有开启或者过期没有必要再调用程序 ---
  show_dis:async function(){
	  var isok=1,self=this;
	  await getApp().promiseGet("/api/weshop/storeDistribut/get/"+os.stoid,{}).then(rs=>{
	  	  var dis=rs.data.data;	
	  	  if( dis && dis.switch==0){
	  		   self.setData({err_word:"商家暂时未开启分销，敬请期待"});
			   isok=0;
	  	  }
	  				  
	  })	
		  
	  if(!isok)	return false; 
	  await getApp().promiseGet("/store/storemoduleendtime/page?store_id=" +os.stoid + "&type=2",{}).then(rs=>{
	  	 if(rs.data.code==0){
	  	 	  var arr = rs.data.data.pageData;
	  	 	  if (arr.length > 0) {
	  	 		   var item=arr[0];
	  	 		   if(item.is_sy==0){
	  	 			   var now = Date.parse(new Date());now = now / 1000;
	  	 			   if(item.end_time<now) {
						   self.setData({err_word:"分销功能已过期，请联系商家进行升级"});isok=0;
					   } 					   
	  	 		   }
	  	 	  }else{
	  			  self.setData({err_word:"请联系商家进行购买分销功能"});
				  isok=0;
	  		  } 
	  	 } 					  
	  })
	  if(!isok)	return false; 
	  
	  //如果不是分销会员的话
	  if(!app.globalData.userInfo['is_distribut']){
		  
		    var res=null;
			await app.request.promiseGet('/api/weshop/users/distribut/getIsDistribut', {
				data: {
					storeId: self.data.userInfo.store_id,
					userId: self.data.userInfo.user_id,
					first_leader: self.data.userInfo.first_leader,
				},
				isShowLoading: true,
			}).then(function(res1) {
				res=res1;
			});
			
			if(res && res.data.code == 0) {
				var data={
					fenxiao: res.data.data,
				};
				var goods=null;
				var isall_pass=1;
				for(var i in  res.data.data){
					if(!res.data.data[i].pass){ isall_pass=0; }				
					if(res.data.data[i].type==3 && res.data.data[i].conditonRemark){
						 goods={is_buy:1,url:'/pages/index/index/index'};
						 if(res.data.data[i].goods_id){
							goods.url='/pages/goods/goodsInfo/goodsInfo?goods_id='+res.data.data[i].goods_id; 
						 }																						 
						 break;
					}					
					if(res.data.data[i].type==2){
						 if(!res.data.data[i].inviter && getApp().globalData.first_leader){
							 await app.request.promiseGet("/api/weshop/users/get/" + os.stoid+"/"+getApp().globalData.first_leader,{}).then(res=>{
								 if(res.data.code==0){
									  var user= res.data.data;
									  if(user.is_distribut==1){
											data.fenxiao[i].inviter=user.mobile;									
									  }
								 }
							 })		
						 }
					}								
				}	
				if(goods){
					data.buy_goods=goods;
				}												
				self.setData(data);
				//如果全部都更新了通过的话
				if(isall_pass){			
					wx.showToast({
					  title: "全部满足成为分销商",
					  icon: 'none',
					  duration: 2000
					});	
						
					if(app.globalData.userInfo)	{
						//-- 会员的分销的内容要进行存储 --
						app.globalData.userInfo.is_distribut=1;
						wx.setStorageSync("userinfo",app.globalData.userInfo);					
						setTimeout(function(){
							self.getDis_data();
							self.setData({
								userInfo: app.globalData.userInfo,
							});
						},2000)	
					}
															
				}
			} 			
			else{
				wx.showToast({
				  title: res.data.msg,
				  icon: 'none',
				  duration: 2000
				});	
				setTimeout(function(){
					getApp().goto("/pages/user/index/index");
				},1500)
				
			}
			
	  }else{
	  	 self.getDis_data()
	  }	
	  		  
  },
  
  //-- 获取会员分销的金额的内容 --
  getDis_data:function(){   
	  var self=this;
	  let url = '/api/weshop/users/distribut/getMoney';	
	   // 请求数据
	   app.request.get(url + '/' + this.data.userInfo.store_id + '/' + this.data.userInfo.user_id, {
	   		  success: function(res) {		
	   			  if(res.data.code == 0) {  
	   					self.setData({
	   						data: res.data.data,
	   					});
	   				} 
	   		  },	   
	   	});
  },

  /**
   * 用户点击右上角分享
   */
   onShareAppMessage: function () {   	  getApp().globalData.no_clear=1

  },
	
	/**
	 * 点击跳转
	 */
	goto(e) {
		let url = '';
		if(e.target.dataset.url) {
			url = e.target.dataset.url;
		} else {
			url = e.currentTarget.dataset.url;
		}
		console.log(url);
		app.goto(url);
	},

	/**
	 * 获取输入框
	 */
	getInput(e) {
		this.setData({
			inputValue: e.detail.value,
		});
	},

	/**
	 * 验证
	 */
	verify(e) {
		let pass = e.target.dataset.pass;
		let index = e.target.dataset.index;
		let mobile = 0;
		var th=this;
		var item=this.data.fenxiao[index];
		
		var inv=item.inviter;
		if(!this.data.inputValue) this.data.inputValue=inv;
		if(this.data.inputValue) {
			mobile = this.data.inputValue;
			if(!pass) {
				app.request.put('/api/weshop/users/distribut/updateUserRecommender', {
				  data: {
				    storeId: self.data.userInfo.store_id,
				    userId: self.data.userInfo.user_id,
				    mobile: mobile,
				  },
				  success: function (res) {  	
					  var showtxt=res.data.msg;     
										  
					  if(!res.data.data){
						  wx.showToast({
						    title: showtxt,
						    icon: 'none',
						    duration: 1500
						  }); 
						  return false;
					  }						  
											  
					  if(res.data.data.indexOf('已成为分销商')!=-1){					  
						  showtxt="成功成为分销商";
						  var txt="fenxiao["+index+"].pass";
						  var txt2="data.is_distribut";
						  var txt3="userInfo.is_distribut";						  
						  if(getApp().globalData.userInfo) getApp().globalData.userInfo.is_distribut=1;
						  
						   
						  setTimeout(function(){
							  th.setData({[txt]:1,[txt2]:1,[txt3]:1})
							  th.getDis_data();
						  },1500)
			  
					  }
					  
	  
					  if(res.data.data.indexOf('验证成功')!=-1){
						  var txt="fenxiao["+index+"].pass";
						  th.setData({[txt]:1})						  
					  }
					  if(res.data.data.indexOf('绑定上下级关系成功')!=-1){
						  var txt="fenxiao["+index+"].pass";
						  th.setData({[txt]:1})						  
					  }
					  
					  wx.showToast({
					    title: showtxt,
					    icon: 'none',
					    duration: 1500
					  });
										 				
				  }
				});
				
			}
		} else {
			wx.showToast({
			  title: '手机号码不能为空',
			  icon: 'none',
			  duration: 2000
			});
		};
		
	},
	
	go_login(){
		 getApp().goto("/packageE/pages/togoin/togoin") //跳到非tabbar页
	}
})