<?php
/**
  * @method 品牌管理
  * @author soul
  * @copyright 2017-10-14
  */
class B2cBrand extends B2cBase
{
	/**
	 * @method    添加配件
	 * @param     [str]     $brandName [品牌名称]
	 * @param     [arr]     $partArr   [配件ID  数组]
	 * @param     [int]     $seq       [排序 默认为999]
	 * @return    [arr]    ['status'=>true,'data'=>1]  【返回新添加的品牌ID】
	 * @author 卢
	 * @copyright 2017-10-14
	 */
	public function addBrand($brandName,$partArr,$seq=999)
	{
		if(is_array($partArr)&&$brandName&&LibFc::Int($seq))
		{
			$keywordArr=LibFc::keyword($brandName);
			$keywordArr[]=LibFc::GetInitial($brandName);
			$this->B2CDb->Begin();
			//品牌表
			$res = $this->add('bc_probrand',['prb_name'=>$brandName,'prb_seq'=>$seq,'prb_initial'=>LibFc::GetInitial($brandName),'prb_keyword'=>implode(',',$keywordArr)]);
			$prb_id = $res['data'];
			//品牌配件分类关联表
			foreach ($partArr as $partId) 
			{
				$this->add('bc_probrand_part',['prp_prb_id'=>$prb_id,'prp_part_id'=>$partId]);
			}
			$this->B2CDb->End();
			return LibFc::ReturnData(true, $prb_id);
		}
		return LibFc::ReturnData(false,'参数不正确');
	}
	/**
	 * @method    获取所有品牌
	 * @param   [str]  [默认为取所有品牌]
	 * @return    [arr]       [[0] => Array([prb_id] => 8830056 [prb_name] => 宝马 [prb_seq] => 20 [prb_initial] => BM [part] => Array([22] => 气缸垫 [23] => 气缸盖垫片修理包 [24] => 发动机垫片修理包 [25] => 气门室盖垫 ))....]
	 * @author 卢
	 * @copyright 2017-10-14
	 */
	public function getBrand($where='')
	{
		$res=$this->get('bc_probrand',['prb_id','prb_name','prb_seq','prb_initial','prb_keyword'],$where.' order by prb_seq asc');
		if(count($res['data']))
		{
			$brandId=array_column($res['data'], 'prb_id');
			if(count($brandId))
			{
				$partData=$this->get('bc_probrand_part left join bc_part on part_id=prp_part_id',['part_name','prp_part_id','prp_prb_id'],sprintf(' and prp_prb_id in (%s)',implode(',',$brandId)));
				if(count($partData['data']))
				{
					foreach ($partData['data'] as $part) 
					{
						$data[$part['prp_prb_id']][$part['prp_part_id']]=$part['part_name'];
					}
					foreach ($res['data'] as $k => $brand) 
					{
						$res['data'][$k]['part']=$data[$brand['prb_id']];
					}
				}
			}
		}
		return $res;
	}
	/**
	 * @method    修改配件
	 * @param     [str]     $brandName [品牌名称]
	 * @param     [int] [品牌ID]
	 * @param     [arr]     $partArr   [配件ID  数组]
	 * @param     [int]     $seq       [排序 默认为空]
	 * @return    [arr]    ['status'=>true,'data'=>1]  【返回修改的品牌ID】
	 * @author 卢
	 * @copyright 2017-10-14
	 */
	public function editBrand($brandName,$brandId,$partArr,$seq='')
	{
		if(is_array($partArr)&&$brandName&&LibFc::Int($brandId))
		{
			$partArr=array_filter($partArr,'LibFc::Int');
			$keywordArr=LibFc::keyword($brandName);
			$keywordArr[]=LibFc::GetInitial($brandName);
			$this->B2CDb->Begin();
			//品牌表
			$this->set('bc_probrand',['prb_name'=>$brandName,'prb_seq'=>$seq,'prb_initial'=>LibFc::GetInitial($brandName),'prb_keyword'=>implode(',',$keywordArr)],sprintf(' and prb_id=%d',$brandId));
			$this->del('bc_probrand_part',sprintf(' and prp_prb_id =%d',$brandId));
			//品牌配件分类关联表
			foreach ($partArr as $partId) 
			{
				$this->add('bc_probrand_part',['prp_prb_id'=>$brandId,'prp_part_id'=>$partId]);
			}
			$this->B2CDb->End();
			return LibFc::ReturnData(true,$brandId);
		}
		return LibFc::ReturnData(false,'参数不正确');
	}
	/**
	 * @method    删除配件品牌
	 * @param     [int|arr]     品牌ID
	 * @return    [arr]         ['status'=>true,'data'=>true]
	 * @author 卢
	 * @copyright 2017-10-16
	 */
	public function delBrand($brandArr)
	{
		if(!empty($brandArr))
		{
			$brandIds=is_array($brandArr)?$brandArr:[(int)$brandArr];
			$brandIds=array_filter($brandIds,'LibFc::Int');
			//删除品牌表
			$this->B2CDb->Begin();
			$this->del('bc_probrand',sprintf(' and prb_id in (%s)',implode(',', $brandIds)));
			$this->del('bc_probrand_part',sprintf(' and prp_prb_id in (%s)',implode(',', $brandIds)));
			$this->B2CDb->End();
			return LibFc::ReturnData(true,true);
		}
		return LibFc::ReturnData(false,'参数不正确');
	}
	/**
	 * @method    根据分类ID获取品牌
	 * @param     [int]         $partId [分类ID]
	 * @return    [arr]                 ['status'=>true,'data'=>[0=>['prb_id'=>123,'prb_name'=>XXX,'prb_seq'=>10,'prb_initial'=>XXX]]]
	 * @author 卢
	 * @copyright 2017-10-16
	 */
	public function getBrandByPart($partId)
	{
		if(LibFc::Int($partId))
		{
			$res=$this->get('bc_probrand left join bc_probrand_part on prb_id=prp_prb_id',['prb_id','prb_name','prb_seq','prb_initial'],sprintf(' and prp_part_id=%d',$partId));
			return $res;
		}
		return LibFc::ReturnData(false,'getBrandByPart参数不正确');
	}



	/**
	 * @method    绑定店铺配件品牌
	 * @param     [int]       $shopId    [店铺ID]
	 * @param     [str]       $brandName [品牌名称]
	 * @param     [int]       $seq       [排序]
	 * @return   [arr]		['status'=>true,'data'=>2]配件id
	 * @author 卢
	 * @copyright 2017-11-17
	 */
	public function setShopBrand($shopId,$dataArr)
	{
		if(LibFc::Int($shopId)&&is_array($dataArr))
		{
			foreach ($dataArr['prbId'] as $k => $v) 
			{
				if(!$v)
				{
					$addNameArr[]=LibFc::Escape($dataArr['shopBrandName'][$k]);//新添加的品牌
					continue;
				}
				$prbArr[]=$v;//原来的品牌id
				$prbNameArr[]=LibFc::Escape($dataArr['shopBrandName'][$k]);//原来的品牌名称
				$lnkBrand[$v]=LibFc::Escape($dataArr['shopBrandName'][$k]);
			}
			// print_r($lnkBrand);
			// die;
			$oriArr=[];//已经存在的品牌id，仅需要绑定
			$oriNameArr=[];//不存在的品牌名称，需要增加和绑定
			$delArr=[];//需解绑的id
			if(count($addNameArr))
			{
				//检查是否已经存在
				$oriBrandNameData=$this->get('bc_probrand',['prb_id','prb_name'],sprintf(" and prb_name in ('%s')",implode("','",$addNameArr)));
				$oriBrandNameArr=array_combine(array_column($oriBrandNameData['data'], 'prb_id'), array_column($oriBrandNameData['data'], 'prb_name'));
				foreach($addNameArr as $k=>$v)
				{
					if(in_array($v, $oriBrandNameArr))
					{
						//已经存在的品牌，仅需要绑定
						$oriArr[]=array_search($v, $oriBrandNameArr);
					}
					else
					{
						//不存在的品牌，需要增加和绑定
						$oriNameArr[]=$v;
					}
				}
			}
			if(count($prbNameArr))
			{
				//判读是否修改了。如果修改了就更改绑定
				$oriEditData=$this->get('bc_probrand left join sh_probrand_link on sprl_prb_id=prb_id',['prb_id','prb_name'],sprintf(' and sprl_shop_id=%d',$shopId));
				$oriEditArr=array_combine(array_column($oriEditData['data'], 'prb_id'), array_column($oriEditData['data'], 'prb_name'));
				$proLinkArr=$oriNameArr=array_unique(array_merge($oriNameArr,array_diff($prbNameArr, $oriEditArr)));//需绑定的品牌名称(包括已存在bc_probrand和不存在的品牌)
				if(count($oriNameArr))
				{
					foreach ($oriNameArr as $value) 
					{
						if($lnkBrand&&($keyId=array_search($value, $lnkBrand))!==false)
						{
							$linkIdArr[]=[$keyId=>$brandId];//[旧ID=>新ID]
						}
					}
					$exitData=$this->get('bc_probrand',['prb_id','prb_name'],sprintf(" and prb_name in ('%s')",implode("','",$oriNameArr)));
					$exitArr=array_combine(array_column($exitData['data'], 'prb_id'), array_column($exitData['data'], 'prb_name'));
					$oriNameArr=array_diff($oriNameArr, $exitArr);//需添加和绑定的品牌名称,bc_probrand不存在的
					$oriArr=array_merge($oriArr,array_keys($exitArr));//需绑定的品牌ID，bc_probrand存在的
				}
				$delArr=array_keys(array_diff($oriEditArr,$prbNameArr));//需解绑的id
			}
			// print_r($proLinkArr);
			// die;
			$this->B2CDb->Begin();
			
			// die;
			$linkIdArr=[];
			//增加
			if(count($oriNameArr))
			{
				foreach($oriNameArr as $k=>$v)
				{
					$keywordArr=LibFc::keyword($v);
					$keywordArr[]=LibFc::GetInitial($v);				
					$res=$this->add('bc_probrand',['prb_name'=>$v,'prb_initial'=>LibFc::GetInitial($v),'prb_keyword'=>implode(',',$keywordArr)]);
					$brandId = $res['data'];
					$oriArr[]=$brandId;
					//同步修改配件品牌
					if($lnkBrand&&($keyId=array_search($v, $lnkBrand))!==false)
					{
						$linkIdArr[$keyId]=$brandId;
					}
				}
			}
			//绑定
			if(count($oriArr))
			{
				$result=$this->get('bc_probrand',['prb_id','prb_name'],sprintf(' and prb_id in (%s)',implode(',',$oriArr)));
				$nameArr=array_column($result['data'], null,'prb_id');
				foreach ($oriArr as $k => $v) 
				{
					$target=['sprl_shop_id'=>$shopId,'sprl_prb_id'=>$v];
					if(array_search($v, $dataArr['prbId'])!==false)
					{
						$key=array_search($v, $dataArr['prbId']);
						$target['sprl_seq']=$dataArr['seq'][$key];
					}
					if(array_search($nameArr[$v]['prb_name'], $dataArr['shopBrandName'])!==false)
					{
						$key=array_search($nameArr[$v]['prb_name'], $dataArr['shopBrandName']);
						$target['sprl_seq']=(empty($dataArr['seq'][$key])?999:$dataArr['seq'][$key]);
					}
					$res=$this->add('sh_probrand_link',$target);
					//除了增加的，新添加的//同步修改配件品牌
					if(in_array($v, array_values($linkIdArr))) 
						continue;
					if(count($exitArr)&&in_array($v, array_keys($exitArr)))
					{
						$keyId=array_search($exitArr[$v], $lnkBrand);//旧ID
						$linkIdArr[$keyId]=$v;
					}
				}
			}
			//同步更新配件品牌
			if(count($linkIdArr))
			{
				foreach ($linkIdArr as $old => $new) 
				{
					$this->set('bc_product',['pro_prb_id'=>$new],sprintf(' and pro_shop_id=%d and pro_prb_id=%d',$shopId,$old));
				}
			}
			//解绑
			if(count($delArr))
			{
				$res=$this->del('sh_probrand_link',sprintf(' and sprl_shop_id=%d and sprl_prb_id in (%s)',$shopId,implode(',',$delArr)));
				$this->set('bc_product',['pro_prb_id'=>0],sprintf(' and pro_shop_id=%d and pro_prb_id in (%s)',$shopId,implode(',',$delArr)));
			}
			$this->B2CDb->End();
			return LibFc::ReturnData(true,true);
		}
		return LibFc::ReturnData(false,'setShopBrand参数不正确');
	}
	/**
	 * @method    修改店铺配件品牌绑定
	 * @param     [int]        $shopId  [店铺ID]
	 * @param     [arr]        $dataArr [品牌ID]
	 * @return    [arr]                 [status=>true,'data'=>true]
	 * @author 卢
	 * @copyright 2017-11-17
	 */
	public function editShopBrand($shopId,$dataArr)
	{
		if(LibFc::Int($shopId)&&is_array($dataArr))
		{
			$oriData=$this->get('sh_probrand_link',['sprl_prb_id'],sprintf(' and sprl_shop_id =%d',$shopId));
			$oriArr=array_column($oriData['data'], 'sprl_prb_id');
			//取交集为修改的
			$editArr=array_intersect($oriArr,$dataArr);
			//差集为增加
			$addArr=array_diff($dataArr, $oriArr);
			//删除的
			$delArr=array_diff($oriArr, $dataArr);
			$this->B2CDb->Begin();
			if(count($addArr))
			{
				foreach ($addArr as $k=>$v) 
				{
					$this->add('sh_probrand_link',['sprl_shop_id'=>$shopId,'sprl_prb_id'=>$v]);
				}
			}
			if(count($delArr))
			{
				$this->del('sh_probrand_link',sprintf(' and sprl_prb_id in (%s) and sprl_shop_id=%d',implode(',', $delArr),$shopId));
			}
			$this->B2CDb->End();
			return LibFc::ReturnData(true,true);
		}
		return LibFc::ReturnData(false,'editShopBrand参数不正确');
	}
	/**
	 * @method    发布配件时绑定店铺配件品牌
	 * @param     [int]       $shopId    [店铺ID]
	 * @param     [str]       $brandName [品牌名称]
	 * @param     [int]       $seq       [排序]
	 * @return   [arr]		['status'=>true,'data'=>2]品牌id
	 * @author 卢
	 * @copyright 2017-11-17
	 */
	public function addShopBrand($shopId,$brandName,$seq='')
	{
		if(LibFc::Int($shopId)&&!empty($brandName))
		{
			//检查是否已经存在
			$oriBrandData=$this->get('bc_probrand',['prb_id'],sprintf(" and prb_name ='%s'",LibFc::Escape($brandName)),true);
			$brandId=$oriBrandData['data']['prb_id'];
			if(!count($oriBrandData['data']))
			{
				//不存在增加
				$keywordArr=LibFc::keyword($brandName);
				$keywordArr[]=LibFc::GetInitial($brandName);
				$this->B2CDb->Begin();
				$brandIdData = $this->add('bc_probrand',['prb_name'=>$brandName,'prb_initial'=>LibFc::GetInitial($brandName),'prb_keyword'=>implode(',',$keywordArr)]);
				$brandId=$brandIdData['data'];
				//绑定店铺
				$target=['sprl_shop_id'=>$shopId,'sprl_prb_id'=>$brandId];
				if($seq) $target['sprl_seq']=$seq;
				$this->add('sh_probrand_link',$target);
				$this->B2CDb->End();
			}
			//判断是否绑定了店铺
			$oriLink=$this->get('sh_probrand_link',['count(1) count'],sprintf(' and sprl_shop_id=%d and sprl_prb_id=%d',$shopId,$brandId),true);
			if(!$oriLink['data']['count'])
			{
				//未绑定 绑定店铺
				$target=['sprl_shop_id'=>$shopId,'sprl_prb_id'=>$brandId];
				if($seq) $target['sprl_seq']=$seq;
				$this->add('sh_probrand_link',$target);
			}
			return LibFc::ReturnData(true,$brandId);
		}
		return LibFc::ReturnData(false,'setShopBrand参数不正确');
	}
}