<?php
/**
 * 分销团队
 * Class Teams
 * @author 王壮丽 276369046@qq.com
 */
class Teams
{
	/**
     * 标记分销
     * @param $mem_id用户ID
     */
	public function addTeam($mem_id){
		global $db,$ass;
		if($mem_id>0){
			$mem = $ass->one('member','','mem_id="'.$mem_id.'"');
			//如果没有分销值，设置V1分销
			if(!$mem['mem_level']){
				if($ass->update('member',array('mem_level'=>1),'mem_id='.$mem_id)){
				}
			}
		}
	}
    /**
     * 获取
     * @param $userid用户ID
     * @param $parentid介绍人ID
     * @return array
     */
    public function joinTeam($userid,$parentid){
        global $db,$ass;
		$pmem = $ass->one('member','','mem_id="'.$parentid.'"');
		//介绍人如果不是分销人员不能介绍
		if(!$pmem['mem_level']){
		//	return false;
		}
		$mem = $ass->one('member','','mem_id="'.$userid.'"');
		//被介绍人不能是分销人员
		if($mem && !$mem['mem_level']){
			//介绍人不能是被介绍人的下级
			if($ass->number('member_team','parentid='.$userid.' and userid='.$parentid)==0){
				if(!$mem['mem_team']){
					$time = date("Y-m-d H:i:s");
					$depth=1;
					$data=array(
						'userid'	=> $userid,
						'parentid'	=> $parentid,
						'depth'		=> $depth,
						'jointime'	=> $time
					);
					if($ass->insert('member_team',$data)){
						//初始加入标记v1级别 虽然有介绍人，但是还没购买人头费，不能算分销人,分销级别还是0
						if($ass->update('member',array('mem_team'=>$parentid),'mem_id='.$userid)){//,'mem_level'=>1 
							if($pmem['mem_team']){
								$depth++;
								return $this->parentTeam($userid,$pmem['mem_team'],$depth,$time);
							}else{
								return true;
							}
						}
					}
				}
			}
		}
		return false;
    }
    /**
     * 插入
     * @param $userid用户ID
     * @param $parentid介绍人ID
     * @param $depth层级关系
     */
    private function parentTeam($userid,$parentid,$depth,$time){
		global $db,$ass;
		$pmem = $ass->one('member','','mem_id="'.$parentid.'"');
		$mem = $ass->one('member','','mem_id="'.$userid.'"');
		if($ass->number('member_team','parentid='.$userid.' and userid='.$parentid)==0){
			$data=array(
				'userid'	=> $userid,
				'parentid'	=> $parentid,
				'depth'		=> $depth,
				'jointime'	=> $time
			);
			if($ass->insert('member_team',$data)){
				if($pmem['mem_team']){
					$depth++;
					return $this->parentTeam($userid,$pmem['mem_team'],$depth,$time);
				}else{
					return true;
				}
			}
		}
	}
	/*
		关于级别晋升和提成规则
		如果下一级的级别高出或者等于介绍人，则介绍人不拿提成
		每个用户后面增加一个销售金额，这个金额是自己和下级的金额，只有当自己级别高出下级的时候，下级的销售金额才能累计在自己销售额之内
		计算销量的方法，销量=自己销量+所有下级销量,V5是自己直接下级的V5数量，不包括自己
		
		提成计算完之后，重新核算级别，从购买者开始计算级别，向上递归计算介绍人级别，核算级别是直到递归没有介绍人结束
		
		2020-09-25调整规则
		1.先计算提成，在计算销量
		2.计算提成或者销量的时候都是从购买者开始计算，递归介绍人，如果介绍人级别低于自己级别，介绍人没有提成和销量，继续递归介绍人的介绍人，金额是从上个提成的级别开始算起
		3.递归循环提成的时候，传入一个上次提成级别，如果介绍人级别高于自己级别，传递上次提成级别为自己的，不高于，上次提成级别不变
	*/
	//如果有介绍人的订单就要
	public function orderShare($bill_id){
		global $db,$ass;
		$front = $ass->one('front','','bill_id="'.$bill_id.'"');
		if($front){
			//储值卡付款不提成
			if($ass->number('front_pay','pay_glide="'.$front['bill_glide'].'" and pay_type=4')==0){
				//if($front['bill_attr']!='member'){
					$mem = $ass->one('member','','mem_id="'.$front['member_id'].'"');
					//如果是分销人员才会处理订单,规则修改，只要是有分销介绍人就要处理，如果自己不是分销则不处理自己
					if($mem['mem_level']){
						$level = $ass->one('level','','level_id='.$mem['mem_level']);
						$level_id = $level['level_id'];
						//先计算提成,自己的提成是当前级别的
						$smoney = ($front['goods_money']-$this->getOrderCommission($bill_id)) * $level['level_rate']/100;
						if($smoney>0){
							$stage = 'V1-'.$level['level_code'];
							$this->alterFeeChild($mem['mem_id'],$mem['mem_id'],$smoney,$mem['mem_id'],0,$front['bill_glide'],$front['bill_glide'],$front['bill_id'],$front['shop_id'],'分销提成','FX',$front['goods_money'],$stage);
						}
					}else{
						$level_id = 0;
					}
					//分销介绍人提成
					if($mem['mem_team']){
						$smoney = $front['goods_money']-$this->getOrderCommission($bill_id);
						$this->teamShare($mem['mem_id'],$mem['mem_team'],1,$smoney,$front['bill_glide'],$front['bill_glide'],$front['bill_id'],$front['shop_id'],'分销提成',$mem['mem_id'],$level_id);
					}
					if($mem['mem_level'] || $mem['mem_team']){
						//增加销量
						$this->addSales($mem['mem_id'],$mem['mem_id'],$front['goods_money'],$front['shop_id']);
						//处理自己和递归介绍人级别
						$this->teamLevel($mem['mem_id'],$front['shop_id']);
						//获取分销金额
						$fxmoney = $ass->sum('member_feechild','fee_money','fee_money>0 and fee_mode="FX" and fee_bill="'.$front['bill_glide'].'"');
						//修改订单分销提成金额
						if($ass->update('front',array('bill_fxmoney'=>$fxmoney),'bill_id='.$bill_id)){
						}
					}
				//}
			}
		}
	}
	function getOrderCommission($bill_id){
		global $db,$ass;
		$front = $ass->one('front','','bill_id='.$bill_id);
		$commission = 0;
		if($front['bill_payment']=='Y'){
			//储值卡付款不提成
			if($ass->number('front_pay','pay_glide="'.$front['bill_glide'].'" and pay_type=4')==0){
				//合计订单的分享金额 goods_commission
				$sqlc = 'select A.*,B.goods_commission from '.$ass->table('front_child').' as A ';
				$sqlc.= 'inner join '.$ass->table('goods').' as B on A.goods_id=B.goods_id and B.goods_commission>0 ';
				$sqlc.= 'where bill_id='.$bill_id;
				$rstc = $db->query($sqlc);
				while($rowc=$db->fetch_array($rstc)){
					$goods_id			= $rowc['goods_id'];
					$goods_price		= $rowc['goods_price'];
					$goods_number		= $rowc['goods_number'];
					$goods_commission	= $rowc['goods_commission'];
					//代理级别必须存在
					$commission+=$goods_number*$goods_price*$goods_commission/100;
				}
			}
		}
		return $commission;
	}
	//判断计算级别,v5自己的不计算在内，只统计自己下面几个V5
	function teamLevel($mem_id,$shop_id){
		global $db,$ass;
		$mem = $ass->one('member','','mem_id='.$mem_id);
		$v5 = $this->getV5($mem_id);
		//if($mem['mem_level']>=5)$v5++;
		$this->circulationLevel($mem['mem_level'],$mem,$mem['mem_sales'],$v5,$shop_id);
		if($mem['mem_team']){
			$this->teamLevel($mem['mem_team'],$shop_id);
		}
	}
	//获取下级的V5,V5必须是自己直接介绍的
	function getV5($mem_id){
		global $ass;
		$v5 = $ass->number('member','mem_level>=5 and mem_team='.$mem_id);
		return $v5;
	}
	//介绍人获取提成
	public function teamShare($mem_id,$parent_id,$depth,$money,$fee_code,$fee_bill,$fee_sole,$shop_id,$memo,$buy_id,$level_id){
		global $db,$ass;
		$mem = $ass->one('member','','mem_id='.$mem_id);
		$parent = $ass->one('member','','mem_id='.$parent_id);
		//分销介绍人的级别大于自己，才能拿到提成, 大于当前已经提成的级别才能拿到提成，
		if($parent['mem_level']>$level_id){
			if($level_id>0){
				$level = $ass->one('level','','level_id='.$level_id);
			}
			$plevel = $ass->one('level','','level_id='.$parent['mem_level']);
			//提成为自己到直接下线级别差
			if($level_id>0){
				$smoney = $money * ($plevel['level_rate']-$level['level_rate'])/100;
			}else{
				$smoney = $money * $plevel['level_rate']/100;
				$level = $ass->one('level','','level_id>0');
			}
			if($smoney){
				$stage = $level['level_code'].'-'.$plevel['level_code'];
				$this->alterFeeChild($parent_id,$mem_id,$smoney,$buy_id,$depth,$fee_code,$fee_bill,$fee_sole,$shop_id,$memo,'FX',$money,$stage);
				//处理上级提成
				if($parent['mem_team']){
					$depth++;
					$this->teamShare($parent_id,$parent['mem_team'],$depth,$money,$fee_code,$fee_bill,$fee_sole,$shop_id,$memo,$buy_id,$plevel['level_id']);
				}
			}
		}else{
			//处理上级提成
			if($parent['mem_team']){
				$depth++;
				$this->teamShare($parent_id,$parent['mem_team'],$depth,$money,$fee_code,$fee_bill,$fee_sole,$shop_id,$memo,$buy_id,$level_id);
			}
		}
	}
	//增加零钱明细
	public function alterFeeChild($mem_id,$underling,$money,$buy_id,$depth,$fee_code,$fee_bill,$fee_sole,$shop_id,$memo,$mode='FX',$amount=0,$stage=''){
		global $db,$ass;
		$time = date('Y-m-d H:i:s');
		$date = date('Y-m-d');
		if($shop_id>0){
			if($money>0){
				$shop = $ass->one('shop','','shop_id='.$shop_id);
				$comp = $ass->one('company','','comp_id='.$shop['comp_id']);
				$date = date("Y-m-d",strtotime("+".$comp['comp_draw']." day"));
			}
		}
		if($ass->number('member_fee','mem_id='.$mem_id.' and shop_id='.$shop_id)==0){
			$data=array(
				'mem_id'	=> $mem_id,
				'shop_id'	=> $shop_id,
				'fee_last'	=> $time,
			);
			if($ass->insert('member_fee',$data)){
				$fee_money = $money;
				$fee_leave = $money;
			}
		}else{
			$one = $ass->one('member_fee','','mem_id='.$mem_id.' and shop_id='.$shop_id);
			$fee_leave = $one['fee_leave']+$money;
			if($money>0){
				$fee_money = $one['fee_money']+$money;
			}else{
				$fee_money = $one['fee_money'];
			}
		}
		$ret = true;
		if($fee_leave){
			if($ass->number('member_feechild','fee_mem='.$mem_id.' and fee_mode="'.$mode.'" and fee_sole='.$fee_sole.' and fee_code="'.$fee_code.'"')==0){
				$list=array();
				$fee_finish = 'N';
				//如果是减钱，获取正金额的所有fee_finish为N的找金额，按照可提现日期,如果是提现正序查找，如果是使用倒序查找
				if($money<0){
					$rets = $this->useFee($money,$mode,$mem_id,$shop_id);//mode XF零钱消费 TX零钱提现
					if(!$rets['ret']){
						$ret = false;
					}else{
						$list=$rets['list'];
					}
					$fee_finish = 'Y';
				}
				if($ret){
					$data=array(
						'fee_code'	=> $fee_code,
						'fee_bill'	=> $fee_bill,
						'fee_sole'	=> $fee_sole,
						'fee_mode'	=> $mode,//分销
						'fee_time'	=> $time,
						'fee_money'	=> $money,//本次金额
						'fee_leave'	=> $fee_leave,//当前余额（累计）
						'fee_shop'	=> $shop_id,
						'fee_memo'	=> $memo,
						'fee_draw'	=> $date,
						'fee_mem'	=> $mem_id,
						'fee_underling'	=> $underling,
						'fee_buy'	=> $buy_id,
						'fee_finish'=> $fee_finish,
						'fee_depth'	=> $depth,
						'fee_amount'=> $amount,
						'fee_stage'	=> $stage
					);
					if($ass->insert('member_feechild',$data)){
						if($money>0){
							if($mode=='FX'){
								//下级未自己贡献的提成累计在下级头上,自己销量累计在自己头上
								if($mem_id==$underling){
									$mem = $ass->one('member','','mem_id='.$mem_id);//自己直接销售提成mem_myfee
									if($ass->update('member',array('mem_myfee'=>$mem['mem_myfee']+$money),'mem_id='.$mem_id)){
									}
								}else{
									$mem = $ass->one('member','','mem_id='.$underling);//给上家贡献提成mem_contribute
									if($ass->update('member',array('mem_contribute'=>$mem['mem_contribute']+$money),'mem_id='.$underling)){
									}
								}
							}
						}
						$pid = $db->insert_id();
						$fdata=array(
							'fee_money' => $fee_money,
							'fee_leave' => $fee_leave,
							'fee_last'  => $time,
						);
						if($ass->update('member_fee',$fdata,'mem_id='.$mem_id.' and shop_id='.$shop_id)){
							//如果money小于0，计算扣减明细进入日志
							if($list){
								foreach($list as $key =>$line){
									$ldata=array(
										'log_fee'	=> $line['fee_id'],
										'log_money'	=> $line['used'],
										'log_usefee'=> $pid,
										'log_code'	=> $fee_code,
										'log_mode'	=> $mode,
										'log_time'	=> $time,
										'log_bill'	=> $line['fee_bill'],
										'log_shop'	=> $shop_id,
										'log_memo'	=> $line['fee_memo'],
									);
									if($ass->insert('member_feelog',$ldata)){
										$cone = $ass->one('member_feechild','','fee_id='.$line['fee_id']);
										$used = abs($line['used'])+abs($cone['fee_used']);
										$cdata = array('fee_used'=>$used);
										if($used==$cone['fee_money']){
											$cdata['fee_finish'] = 'Y';
										}
										if($ass->update('member_feechild',$cdata,'fee_id='.$line['fee_id'])){
										}
									}
								}
							}
						}
					}
				}
			}
		}
		return $ret;
	}
	//增加销量
	public function addSales($mem_id,$under_id,$money,$shop_id){
		global $db,$ass;
		$add = false;
		$mem = $ass->one('member','','mem_id='.$mem_id);
		$under = $ass->one('member','','mem_id='.$under_id);
		if($mem_id==$under_id){//增加自己的提成
			if($mem['mem_level']>0){
				$add = true;
			}
		}else{
			if($mem['mem_level']>$buy['mem_level']){
				$add = true;
				$under_id = $mem['mem_id'];//下级中级别较高的
			}
		}
		if($add){
			$mem_sales = $mem['mem_sales']+$money;
			if($ass->update('member',array('mem_sales'=>$mem_sales),'mem_id='.$mem_id)){
			}
			
		}
		if($mem['mem_team']){
			$this->addSales($mem['mem_team'],$under_id,$money,$shop_id);
		}
	}
	
	//可能一次销售金额很大，跨过几个级别
	function circulationLevel($level_id,$mem,$mem_sales,$v5,$shop_id){
		global $db,$ass;
		if($level_id>0){
			$level = $ass->one('level','','level_id>'.$level_id.' and level_v5<='.$v5.' and level_sales<='.$mem_sales);
			//如果销量大于下一级别，判断v5是否满足
			if($level){
				if($ass->update('member',array('mem_level'=>$level['level_id'],'mem_v5'=>$v5),'mem_id='.$mem['mem_id'])){
					$this->circulationLevel($level['level_id'],$mem,$mem_sales,$v5,$shop_id);
				}	
			}
		}
	}

	/*
	 *根据金额获取零钱明细
	 */
	function useFee($usemoney,$mode,$mem_id,$shop_id){
		global $db,$ass;
		$date = date("Y-m-d");
		$sql = 'select * from '.$ass->table('member_feechild').' where fee_finish="N"';
		$sql.= ' and fee_money>0 and fee_mode="TC" and fee_shop='.$shop_id.' and fee_mem='.$mem_id;
		if($mode=='TX'){
			$sql.= ' and fee_draw<="'.$date.'" order by fee_draw asc';
		}else if($mode=='XF'){//零钱消费
			$sql.= ' order by fee_draw desc';
		}
		$rst = $db->query($sql);
		$i=0.00;
		$leave=abs($usemoney);
		$arr=array();
		while($row=$db->fetch_array($rst)){
			$money = $row['fee_money'] - $row['fee_used'];
			if($leave<=$money){
				$used = -$leave;
				$leave = 0;
			}else{
				$used = -$money;
				$leave = $leave-$money;
			}
			$arr[]=array(
				'fee_id'	=> $row['fee_id'],
				'fee_bill'	=> $row['fee_bill'],
				'used'		=> $used,
				'fee_memo'	=> $row['fee_memo']
			);
			if($leave==0){
				break;
			}
		}
		if($leave>0){
			$ret = false;
		}else{
			$ret = true;
		}
		return array('ret'=>$ret,'list'=>$arr);
	}

	//获取分享佣金
	function goodsSpreader($bill_id){
		global $db,$ass;
		$date = date('Y-m-d');
		$time = date('Y-m-d H:i:s');
		$front = $ass->one('front','','bill_id='.$bill_id);
		if($front['bill_payment']=='Y'){
			//储值卡付款不提成
			if($ass->number('front_pay','pay_glide="'.$front['bill_glide'].'" and pay_type=4')==0){
				if($front['bill_spreader']>0){
					//合计订单的分享金额 goods_commission
					$sqlc = 'select A.*,B.goods_commission from '.$ass->table('front_child').' as A ';
					$sqlc.= 'inner join '.$ass->table('goods').' as B on A.goods_id=B.goods_id and B.goods_commission>0 ';
					$sqlc.= 'where bill_id='.$bill_id;
					$rstc = $db->query($sqlc);
					$commission = 0;
					while($rowc=$db->fetch_array($rstc)){
						$goods_id			= $rowc['goods_id'];
						$goods_price		= $rowc['goods_price'];
						$goods_number		= $rowc['goods_number'];
						$goods_commission	= $rowc['goods_commission'];
						//代理级别必须存在
						$commission+=$goods_number*$goods_price*$goods_commission/100;
					}
					if($commission){
						if($ass->update('front',array('bill_commission'=>$commission),'bill_id='.$bill_id)){
							//客户零钱增加
							$this->alterFeeChild($front['bill_spreader'],$front['bill_spreader'],$commission,$front['member_id'],0,$front['bill_glide'],$front['bill_glide'],$front['bill_id'],$front['shop_id'],'商品分享提成','TC',$front['goods_money'],'分享佣金');
						}
					}
				}
			}
		}
	}

	//分销介绍人提成
	public function goodsTeamShare($bill_id){
		global $db,$ass;
		$date = date('Y-m-d');
		$time = date('Y-m-d H:i:s');
		$front = $ass->one('front','','bill_id='.$bill_id);
		//储值卡付款不提成
		if($ass->number('front_pay','pay_glide="'.$front['bill_glide'].'" and pay_type=4')==0){
			$mem = $ass->one('member','','mem_id="'.$front['member_id'].'"');
			if($front['bill_payment']=='Y'){
				//如果有分销介绍人才能提成
				if($mem['mem_team']>0){
					$isok = true;
					if($front['bill_attr']=='member'){
						$pmem = $ass->one('member','','mem_id='.$mem['mem_team']);
						if(!$pmem['mem_level']){
							$isok = false;
						}
					}
					if($isok){
						//合计订单的分享金额 goods_commission
						$sqlc = 'select A.*,B.goods_commission from '.$ass->table('front_child').' as A ';
						$sqlc.= 'inner join '.$ass->table('goods').' as B on A.goods_id=B.goods_id and B.goods_commission>0 ';
						$sqlc.= 'where bill_id='.$bill_id;
						$rstc = $db->query($sqlc);
						$commission = 0;
						while($rowc=$db->fetch_array($rstc)){
							$goods_id			= $rowc['goods_id'];
							$goods_price		= $rowc['goods_price'];
							$goods_number		= $rowc['goods_number'];
							$goods_commission	= $rowc['goods_commission'];
							//代理级别必须存在
							$commission+=$goods_number*$goods_price*$goods_commission/100;
						}
						if($commission){
							if($ass->update('front',array('bill_commission'=>$commission),'bill_id='.$bill_id)){
								//客户零钱增加
								$this->alterFeeChild($mem['mem_team'],$mem['mem_team'],$commission,$front['member_id'],0,$front['bill_glide'],$front['bill_glide'],$front['bill_id'],$front['shop_id'],'商品介绍人提成','TC',$front['goods_money'],'分销介绍人提成');
							}
						}
					}
				}
			}
		}
	}

	//酒销售增加分销金额和分销提成
	public function wineTeamShare($sell_id,$mem_id,$money){
		global $db,$ass;
		$sell = $ass->one('nfc_sell','','sell_id="'.$sell_id.'"');
		if($sell){
			$mem = $ass->one('member','','mem_id="'.$mem_id.'"');
			//如果是分销人员才会处理订单
			if($mem['mem_level']){
				$level = $ass->one('level','','level_id='.$mem['mem_level']);
				//先计算提成,自己的提成是当前级别的
				$smoney = $money * $level['level_rate']/100;
				$this->alterFeeChild($mem['mem_id'],$mem['mem_id'],$smoney,$mem['mem_id'],0,$sell['sell_code'],$sell['sell_code'],$sell_id,$sell['sell_shop'],'酒销售提成',$amount=0,$stage='');
				//分销介绍人提成
				if($mem['mem_team']){
					$this->teamShare($mem['mem_id'],$mem['mem_team'],1,$money,$sell['sell_code'],$sell['sell_code'],$sell_id,$sell['sell_shop'],'酒销售提成');
				}
				//增加自己销量,处理级别
				$this->addSales($mem['mem_id'],$money,$sell['nfc_shop']);
			}
		}
	}

	//计算订单实际销售价格
	public function orderTrueSell($bill_id){
		global $db,$ass;
		$front = $ass->one('front','','bill_id="'.$bill_id.'"');
		if($front){
			$all_disc = 1;
			$isyj = false;
			if($front['bill_fxmoney']>0){
				if($front['goods_money']){
					$all_disc = ($front['goods_money']-$front['bill_fxmoney'])/$front['goods_money'];
				}
			}
			if($front['bill_commission']>0){
				$isyj = true;
			}
			if($front['bill_fxmoney']>0 || $front['bill_commission']>0){
				$sqlc = 'select A.*,B.goods_commission from '.$ass->table('front_child').' as A ';
				$sqlc.= 'inner join '.$ass->table('goods').' as B on A.goods_id=B.goods_id ';
				$sqlc.= 'where bill_id='.$bill_id;
				$rstc = $db->query($sqlc);
				while($rowc=$db->fetch_array($rstc)){
					$goods_id			= $rowc['goods_id'];
					$goods_price		= $rowc['goods_price'];
					$goods_line			= $rowc['goods_line'];
					$goods_commission	= $rowc['goods_commission'];
					if($isyj){
						$disc = ($all_disc - $goods_commission/100);
					}else{
						$disc = $all_disc;
					}
					if($ass->update('front_child',array('goods_truesell'=>$goods_price*$disc),'bill_id='.$bill_id.' and goods_line='.$goods_line)){
					}
				}
			}
		}
	}
}