<?php
class B2cFreight extends B2cBase
{
	/**
	  * @method 添加运费模板
	  * @author 卢
	  * @param   $targetTpl字段数组
	  * @param   $link post过来的数组
	  * @copyright 2017.6.16
	  * @return bool
	  */
	 function addSellerTemplate($targetTpl,$link)
	 {
	 	if(is_array($targetTpl)&&is_array($link))
	 	{	 		
		 	$this->B2CDb->Begin();
		 	if(isset($targetTpl['frt_default'])&&$targetTpl['frt_default']=='Y')
		 	{
		 		$this->Set('sh_freight_tpl',['frt_default'=>'N'],' and frt_shop_id='.$targetTpl['frt_shop_id']);
		 	}
			$res = $this->Add('sh_freight_tpl',$targetTpl);
			$tplId = $res['data'];
			foreach ($link as $k => $v)
			{			
				unset($link[$k]['send_method']);
				if(count($link[$k])==0)
				{
					$targetTplLink=array(
							'ftl_frt_id'=>$tplId,
							'ftl_shipping_method'=>$k,
							'ftl_default'=>'Y',
							'ftl_begin_count'=>0,
							'ftl_begin_money'=>0,
							'ftl_next_count'=>0,
							'ftl_next_money'=>0
							);
		 			$tplLinkId = $this->Add('sh_freight_tpl_link',$targetTplLink);
				}
				else
				{
					foreach ($link[$k] as $i => $j)
					{
					 	if(isset($j['area']))
					 	{
							$targetTplLink=array(
								'ftl_frt_id'=>$tplId,
								'ftl_shipping_method'=>$k,
								'ftl_default'=>'N',
								'ftl_begin_count'=>$j['begin_count'],
								'ftl_begin_money'=>$j['begin_money'],
								'ftl_next_count'=>$j['next_count'],
								'ftl_next_money'=>$j['next_money'],
								'ftl_cities'=>$j['area']
							);
					 		
					 	}
					 	else
					 	{
					 		$targetTplLink=array(
								'ftl_frt_id'=>$tplId,
								'ftl_shipping_method'=>$k,
								'ftl_default'=>'Y',
								'ftl_begin_count'=>$j['num'],
								'ftl_begin_money'=>$j['price'],
								'ftl_next_count'=>$j['addnum'],
								'ftl_next_money'=>$j['addprice']
								);
					 	}
						$tplLinkId = $this->Add('sh_freight_tpl_link',$targetTplLink);
					}			
				}			
			}
			$this->B2CDb->End();
			return LibFc::ReturnData(true, $tplId);
	 	}
	 	return LibFc::ReturnData(false,'参数不正确');
	 }
	 /**
	  * @method 获取模板列表
	  * @author 卢
	  * @param $shopId 店铺ID
	  * @param  $tid 模板ID
	  * @copyright 2017.6.20
	  * @return  bool
	  */
	 function getSellerTemplateList($shopId,$tid='')
	{
		if(LibFc::Int($shopId))
		{
		 	if(empty($tid))
		 	{
		 		$where1=sprintf(' and frt_shop_id=%d order by frt_default desc',$shopId);
		 	}
		 	else if(LibFc::Int($tid))
		 	{
		 		$where1=sprintf(' and frt_shop_id=%d and frt_id=%d',$shopId,$tid);
		 	}
		 	else
		 	{
		 		return LibFc::ReturnData(false,'参数类型不正确');
		 	}
		 	$data=$this->Get('sh_freight_tpl',['*'],$where1);
		 	$frtIdArr=array_column($data['data'], 'frt_id');
		 	if(count($frtIdArr))
		 	{
			 	$where=sprintf(' and ftl_frt_id in (%s) order by ftl_shipping_method,ftl_default desc',implode(',',$frtIdArr));
			 	$result=$this->Get('sh_freight_tpl_link',['*'],$where);
			 	foreach ($result['data'] as $k => $v) 
			 	{
			 		if(!empty($v['ftl_cities']))
		 			{
		 				$city=$this->getParentCity($v['ftl_cities']);
		 				$path=$city['data']['name'];
		 				$parent=$city['data']['parentPath'];
		 			}
		 			else
		 			{
		 				$path='';
		 				$parent='';
		 			}
		 			$result['data'][$k]['path']=$path;
		 			$result['data'][$k]['parentPath']=$parent;
				 	$res[$v['ftl_frt_id']][]=$result['data'][$k];
			 	}
			 	foreach ($data['data'] as $k => $v) 
			 	{
			 		$data['data'][$k]['link']=$res[$v['frt_id']];
			 	}
		 	}
		 	return $data;			
		}
		return LibFc::ReturnData(false,'参数类型不正确');
	}
	 /**
	  * @method 修改运费模板
	  * @author 卢
	  * @param   $targetTpl字段数组
	  * @param   $link post过来的数组
	  * @param   $tplId 模板ID
	  * @param   $shopId 店铺id
	  * @copyright 2017.6.21
	  * @return  bool
	  */
	 function editSellerTemplate($targetTpl,$link,$tplId,$shopId)
	{
		if(is_array($targetTpl)&&is_array($link)&&LibFc::Int($tplId)&&LibFc::Int($shopId))
		{
			$existWhere=sprintf(' and frt_id=%d and frt_shop_id=%d',$tplId,$shopId);
	 		$exist=$this->Get('sh_freight_tpl',['frt_id'],$existWhere);
	 		if(empty($exist['data']))
	 		{
	 			return LibFc::ReturnData(false,'此模板不存在或已删除');
	 		}
			$where1=sprintf(' and ftl_frt_id=%d',$tplId);
		 	$result=$this->Get('sh_freight_tpl_link',['ftl_id'],$where1);
		 	$data=array();
		 	$deleteId=array();
		 	foreach ($result['data'] as $k => $v) 
		 	{
		 		$data[]=$v['ftl_id'];
		 	}
		 	$existMethod=array();
		 	foreach ($link as $k => $v) 
		 	{
		 		$existMethod[]=$link[$k]['send_method'];
		 		unset($link[$k]['send_method']);
		 		$key=array_keys($link[$k]);
		 		$deleteId[$k]=$this->compareTemplateId($key,intval($tplId),intval($k));
		 	}
		 	$this->B2CDb->Begin();
		 	if(count($existMethod)==1)
		 	{
	 			$delMethod=$existMethod[0]>0? 0: 1;
	 			$this->Del('sh_freight_tpl_link',sprintf(' and ftl_frt_id=%d and ftl_shipping_method=%d',$tplId,$delMethod)); 
		 	}
		 	if(isset($targetTpl['frt_default'])&&$targetTpl['frt_default']=='Y')
		 	{
		 		$this->Set('sh_freight_tpl',['frt_default'=>'N'],' and frt_shop_id='.$shopId);
		 	}
		 	$where=sprintf(' and frt_id=%d and frt_shop_id=%d',$tplId,$shopId);
		 	$this->Set('sh_freight_tpl',$targetTpl,$where);
		 	foreach ($link as $k => $v)
			{	
				if(!empty($deleteId[$k]['data']))
			 	{
				 	$deleteWhere=sprintf(' and ftl_id in (%s) and ftl_frt_id=%d',$deleteId[$k]['data'],$tplId);
				 	$this->Del('sh_freight_tpl_link',$deleteWhere);
			 	}				
				if(count($link[$k])==0)
				{
					$targetTplLink=array(
							'ftl_frt_id'=>$tplId,
							'ftl_shipping_method'=>$k,
							'ftl_default'=>'Y',
							'ftl_begin_count'=>0,
							'ftl_begin_money'=>0,
							'ftl_next_count'=>0,
							'ftl_next_money'=>0
							);
		 			$tplLinkId = $this->Add('sh_freight_tpl_link',$targetTplLink);
				}
				else
				{				
					foreach ($link[$k] as $i => $j)
					{
					 	if(isset($j['area']))
					 	{
							$targetTplLink=array(
								'ftl_frt_id'=>$tplId,
								'ftl_shipping_method'=>$k,
								'ftl_default'=>'N',
								'ftl_begin_count'=>$j['begin_count'],
								'ftl_begin_money'=>$j['begin_money'],
								'ftl_next_count'=>$j['next_count'],
								'ftl_next_money'=>$j['next_money'],
								'ftl_cities'=>$j['area']
							);
					 		
					 	}
					 	else
					 	{
					 		$targetTplLink=array(
					 			'ftl_frt_id'=>$tplId,
								'ftl_shipping_method'=>$k,
								'ftl_default'=>'Y',
								'ftl_begin_count'=>$j['num'],
								'ftl_begin_money'=>$j['price'],
								'ftl_next_count'=>$j['addnum'],
								'ftl_next_money'=>$j['addprice']
								);

					 	}
					 	if(!in_array($i, $data))
				 		{
				 			//如果不存在则添加
				 			$tplLinkId = $this->Add('sh_freight_tpl_link',$targetTplLink);
				 		}
				 		else 
				 		{
				 			//如果存在则修改
				 			$where=sprintf(' and ftl_id=%d and ftl_frt_id=%d',$i,$tplId);
				 			$this->Set('sh_freight_tpl_link',$targetTplLink,$where);
				 		}
						
					}			
				}		
			}
			$this->B2CDb->End();
			return LibFc::ReturnData(true,true);		
		}
		return LibFc::ReturnData(false,'参数不正确');

	}
	 /**
	  * @method对比数据库中的ID
	  * @author 卢
	  * @param  $arr 需要与数据库对比的id数组
	  * @param  $tplId 模板id
	  * @param  $method 快递类型
	  * @return   array{[0]=>1,2,3 [1]=>4,5,6}
	  * @copyright 2017.6.21
	  */
	 function compareTemplateId($arr,$tplId,$method)
	 {
	 	if(is_array($arr)&&LibFc::Int($tplId))
	 	{
		 	foreach ($arr as $k => $v) 
		 	{
		 		if($v<=0)
		 		{
		 			unset($arr[$k]);
		 		}
		 	}
		 	$where=sprintf(' and ftl_frt_id=%d and ftl_shipping_method=%d',$tplId,$method);
		 	$result=$this->Get('sh_freight_tpl_link',['ftl_id'],$where);

		 	$data=array();
		 	foreach ($result['data'] as $k => $v)
		 	{
		 		$data[]=$v['ftl_id'];
		 	}
		 	$deleteIdArr=array_diff($data,$arr);
		 	$deleteId=implode($deleteIdArr,',');
		 	return LibFc::ReturnData(true,$deleteId);
	 	}
		return LibFc::ReturnData(false,'参数错误');	 	
	 }
	 /**
	  * @method删除模板
	  * @author 卢
	  * @param  $shopId 店铺id
	  * @param  $tid 模板id
	  * @return   bool
	  * @copyright 2017.6.21
	  */
	 function deleteSellerTemplate($shopId,$tid)
	 {
	 	if(LibFc::Int($shopId)&&LibFc::Int($tid))
	 	{
	 		$existWhere=sprintf(' and frt_id=%d and frt_shop_id=%d',$tid,$shopId);
	 		$exist=$this->Get('sh_freight_tpl',['frt_id'],$existWhere);
	 		if(empty($exist['data']))
	 		{
	 			return LibFc::ReturnData(true,true);
	 		}
		 	$this->B2CDb->Begin();
		 	$where1=sprintf(' and frt_id=%d and frt_shop_id=%d',$tid,$shopId);
		 	$this->Del('sh_freight_tpl',$where1);
		 	$where2=sprintf(' and ftl_frt_id=%d',$tid);
		 	$this->Del('sh_freight_tpl_link',$where2);
		 	$this->B2CDb->End();
		 	return LibFc::ReturnData(true,true);	 		
	 	}
	 	return LibFc::ReturnData(false,'参数错误');
	 }
	 /**
	  * @method修改默认模板
	  * @author 卢
	  * @param  $shopId 店铺id
	  * @param  $tid 模板id
	  * @return   bool
	  * @copyright 2017.6.29
	  */
	 function setTemplateDefault($tid,$shopId)
	 {
	 	if(LibFc::Int($shopId)&&LibFc::Int($tid))
	 	{
		 	$this->B2CDb->Begin();
		 	$this->Set('sh_freight_tpl',['frt_default'=>'N'],' and frt_shop_id='.$shopId);
		 	$this->Set('sh_freight_tpl',['frt_default'=>'Y'],' and frt_id='.$tid.' and frt_shop_id='.$shopId);
		 	$this->B2CDb->End();
		 	return LibFc::ReturnData(true,true);
	 	}
	 	return LibFc::ReturnData(false,'参数错误');
	 }
    /**
    * @method 处理地址，只显示父级
    * @author 卢
    * @param   $path 地址，以逗号分割
    * @return  array([name=>'北京,广东','parentPath'=>'1,2'])
    * @copyright 2017.6.30
    */
    function getParentCity($path)
    {
    	$addr=new YpwAddr();
    	$num=array();
    	$parentName='';
    	$parentPath='';
    	$parentArr=array();
    	$parentNum=array();
    	$where=sprintf(' and pc_id in (%s)',$path);
    	$data=$addr->Get('yp_province_city',['pc_id','pc_pid','pc_name'],$where);
    	$parentArr=array_column($data['data'], 'pc_pid');
    	$parentId=array_filter(array_unique($parentArr));
    	if(count($parentId))
    	{
	    	$res=$addr->get('yp_province_city',['pc_id','pc_pid'],sprintf(' and pc_pid in (%s)',implode(',',$parentId)));
	    	$re=$addr->get('yp_province_city',['pc_name','pc_id'],sprintf(' and pc_id in (%s)',implode(',',$parentId)));
	    	foreach ($res['data'] as $k => $v) 
	    	{
	    		$numRe[$v['pc_pid']][]=$v;
	    	}
	    	$nameReArr=array_column($re['data'],null, 'pc_id');
	    	foreach ($parentId as $k => $v) 
	    	{
	    		$parentNum[$v]['num']=count($numRe[$v]);
	    		$parentNum[$v]['name']=$nameReArr[$v]['pc_name'];
	    		$num[$v]=0;
	    	}
    	}
    	// print_r($parentNum);
    	foreach ($data['data'] as $k => $v) 
    	{
    		if(in_array($v['pc_pid'], $parentId))
    		{
    			$num[$v['pc_pid']]+=1;
    		}
    	}
    	foreach ($parentNum as $k => $v) 
    	{
    		if($num[$k]==$v['num'])
    		{
    			$parentName.=','.$v['name'];
    			$parentPath.=','.$k;
    		}
    		else
    		{
    			$where1=sprintf(' and pc_id in (%s) and pc_pid=%d',$path,$k);
    			$r=$addr->Get('yp_province_city',['pc_id','pc_pid','pc_name'],$where1);
    			foreach ($r['data'] as $i => $j) 
    			{
    				$parentName.=','.$j['pc_name'];
    			}
    		}
    	}
    	$result=array('name'=>trim($parentName,','),'parentPath'=>trim($parentPath,','));
    	return LibFc::ReturnData(true,$result);
    }
    /**
     * @method    获取某个目的地某个产品某个数量的运费
     * @param     [int]               $userId   [用户ID]
     * @param     [int]               $shopId   [店铺ID]
     * @param     [int]               $area     [目标地址]
     * @param     [arr]               $tplIdArr [运费模板ID array('$proId'=>$tplId) 以产品ID为键]
     * @param     [arr]               $numArr   [数量 array('$proId'=>456) 以产品ID为键]
     * @return    [arr]                         [ [is_free] => Array([100031] => N [100032] => Y [100029] => N)[price] => Array([100031] => Array([0] => 10 [1] => 15)[100032] => Array([0] => 0)[100029] => Array([0] => 30))] is_free是否包邮  price[xxx][0] 快递首重价 price[xxx][1] ems首重价 realPrice[xxx][0] 计算后的快递价（是否超重）
     * @author 卢
     * @copyright 2017-08-07
     */
    public function getUserTemplatePrice($userId,$shopId,$area,$tplIdArr,$numArr)
    {
    	if(LibFc::Int($userId)&&LibFc::Int($shopId)&&is_array($tplIdArr)&&is_array($numArr))
    	{
    		foreach ($tplIdArr as $v) 
    		{
    			if(empty($v))
    				return LibFc::ReturnData(false,'参数错误');
    		}
    		//运费模板信息
    		$tplData=$this->get('sh_freight_tpl left join sh_freight_tpl_link on ftl_frt_id=frt_id ',['frt_is_free','ftl_frt_id','frt_valuation_method','ftl_shipping_method','ftl_default','ftl_begin_count','ftl_begin_money','ftl_next_count','ftl_next_money','ftl_cities'],sprintf(' and frt_shop_id=%d and ftl_frt_id in (%s)',$shopId,implode(',', $tplIdArr)));
    		//配件重量信息
    		$proIdArr=array_keys($tplIdArr);
    		// print_r($proIdArr);
    		// die;
    		$B2cProduct=new B2cProduct();
    		$proData=$B2cProduct->getProduct(['pri_weight','pro_id'], sprintf(' and pro_id in (%s)',implode(',',$proIdArr)));
    		$proArr=array_column($proData['data'],null, 'pro_id');
    		$result=array();
    		foreach ($tplIdArr as $k => $v) 
    		{
    			
    			$tag[0]=1;
				$tag[1]=1;
    			foreach ($tplData['data'] as $tpl) 
    			{
    				if($tpl['ftl_frt_id']==$v)
    				{
    					$result['is_free'][$k]=$tpl['frt_is_free'];
    					if($tag[$tpl['ftl_shipping_method']]>1) continue;
    					$path=explode(',', $tpl['ftl_cities']);
    					// print_r($path);		
    					if($tpl['ftl_default']=='N'&&!in_array($area[0], $path)) continue;			
						$result['price'][$k][$tpl['ftl_shipping_method']]=$tpl['ftl_begin_money']; 
						$overWeight=0; 
						$over=0; 						
						if($tpl['frt_is_free']=='N')
						{    	
							//判断是否超重
							if($tpl['frt_valuation_method']>0)
							{
								//按重量算
								$totalNum=$proArr[$k]['pri_weight']>0?$proArr[$k]['pri_weight']*$numArr[$k]:$numArr[$k];
							}
							else
							{
								//按件算
								$totalNum=$numArr[$k];
							}						
    						if($totalNum>$tpl['ftl_begin_count'])
    						{
    							//超重
    							$overWeight=$tpl['ftl_next_count']>0?ceil(($totalNum-$tpl['ftl_begin_count'])/$tpl['ftl_next_count']):0;
    							$over=$totalNum-$tpl['ftl_begin_count'];
    						}
    						$result['realPrice'][$k][$tpl['ftl_shipping_method']]=$overWeight*$tpl['ftl_next_money']+$tpl['ftl_begin_money'];
						}
						else
						{
							if($tpl['frt_is_free']=='D'){
								$result['realPrice'][$k][$tpl['ftl_shipping_method']]=-1;
							}else{
								$result['realPrice'][$k][$tpl['ftl_shipping_method']]=0;
							}
							
						}
						$result['over'][$k][$tpl['ftl_shipping_method']]=$over;
    					if($tpl['ftl_default']=='N'&&in_array($area[0], $path))
    					{
    						$tag[$tpl['ftl_shipping_method']]++;
    					}  
    				}
    			}
    		}
    		return LibFc::ReturnData(true,$result);
    	}
    	return LibFc::ReturnData(false,'参数错误');
    }
    /**
     * @method    获取某个目的地某个套餐某个数量的运费
     * @param     [int]               $userId   [用户ID]
     * @param     [int]               $shopId   [店铺ID]
     * @param     [int]               $area     [目标地址]
     * @param     [arr]               $packTplIdArr [运费模板ID array('$packId'=>$tplId) 以套餐ID为键]
     * @param     [arr]               $numArr   [数量 array('$packId'=>456) 以套餐ID为键]
     * @return    [arr]                         [ [is_free] => Array([100031] => N [100032] => Y [100029] => N)[price] => Array([100031] => Array([0] => 10 [1] => 15)[100032] => Array([0] => 0)[100029] => Array([0] => 30))] is_free是否包邮  price[xxx][0] 快递首重价 price[xxx][1] ems首重价 realPrice[xxx][0] 计算后的快递价（是否超重）
     * @author 卢
     * @copyright 2018-2-6
     */
    public function getPackTplPrice($userId,$shopId,$area,$packTplIdArr,$numArr)
    {
    	if(LibFc::Int($userId)&&LibFc::Int($shopId)&&count($packTplIdArr)&&count($numArr))
		{
			foreach ($packTplIdArr as $v) 
			{
				if(empty($v))
					return LibFc::ReturnData(false,'getPackTplPrice 参数错误');
			}
			//运费模板信息
    		$tplData=$this->get('sh_freight_tpl left join sh_freight_tpl_link on ftl_frt_id=frt_id ',['frt_is_free','ftl_frt_id','frt_valuation_method','ftl_shipping_method','ftl_default','ftl_begin_count','ftl_begin_money','ftl_next_count','ftl_next_money','ftl_cities'],sprintf(' and frt_shop_id=%d and ftl_frt_id in (%s)',$shopId,implode(',', $packTplIdArr)));
    		//获取套餐配件
    		$packProArr=$this->get('bc_product join bc_product_info on pri_pro_id=pro_id 
    			left join bc_product_pack_link on prpl_pro_id=pro_id 
    			left join bc_product_pack on prpl_prpa_id=prpa_id',['pro_id','pri_weight','prpa_id'],sprintf(' and prpa_id in (%s) and pro_shop_id=%d and prpa_btime<=%d and prpa_etime>=%d',implode(',',array_keys($packTplIdArr)),$shopId,time(),time()));
    		// print_r($tplData);
    		if(count($packProArr['data']))
    		{
	    		$proArr=[];
    			foreach ($packProArr['data'] as $v) 
    			{
    				
    				$proArr[$v['prpa_id']]['weight']+=($v['pri_weight']?$v['pri_weight']:1)*$numArr[$v['prpa_id']];//重量
    				$proArr[$v['prpa_id']]['count']+=$numArr[$v['prpa_id']];//数量
    			}
    			$result=[];
    			foreach ($packTplIdArr as $packId => $tplId) 
    			{
    				$tag[0]=1;
					$tag[1]=1;
    				foreach ($tplData['data'] as $tpl)
    				{
    					if($tpl['ftl_frt_id']==$tplId)
    					{
    						$result['is_free'][$packId]=$tpl['frt_is_free'];
    						if($tag[$tpl['ftl_shipping_method']]>1) continue;
	    					$path=explode(',', $tpl['ftl_cities']);
	    					// 非默认运费并且不包括该城市,跳过		
	    					if($tpl['ftl_default']=='N'&&!in_array($area[0], $path)) continue;			
							$result['price'][$packId][$tpl['ftl_shipping_method']]=$tpl['ftl_begin_money']; 
							$overWeight=0; 
							$over=0;
							//不包邮
							if($tpl['frt_is_free']=='N')
							{    	
								//判断是否超重
								if($tpl['frt_valuation_method']>0)
								{
									//按重量算
									$totalNum=$proArr[$packId]['weight']>0?$proArr[$packId]['weight']:1;
								}
								else
								{
									//按件算
									$totalNum=$proArr[$packId]['count'];
								}						
	    						if($totalNum>$tpl['ftl_begin_count'])
	    						{
	    							//超重
	    							$overWeight=$tpl['ftl_next_count']>0?ceil(($totalNum-$tpl['ftl_begin_count'])/$tpl['ftl_next_count']):0;
	    							$over=$totalNum-$tpl['ftl_begin_count'];
	    						}
	    						$result['realPrice'][$packId][$tpl['ftl_shipping_method']]=$overWeight*$tpl['ftl_next_money']+$tpl['ftl_begin_money'];
							}
							else
							{
								$result['realPrice'][$packId][$tpl['ftl_shipping_method']]=0;
							}
							$result['over'][$packId][$tpl['ftl_shipping_method']]=$over;
	    					if($tpl['ftl_default']=='N'&&in_array($area[0], $path))
	    					{
	    						$tag[$tpl['ftl_shipping_method']]++;
	    					}
    					}
    				}
    			}
    			return LibFc::ReturnData(true,$result);
	    		exit();
    		}
    		else
    		{
    			return LibFc::ReturnData(false,'套餐不存在');
    		}
		}
		return LibFc::ReturnData(false,'getPackTplPrice参数错误');
    }
}