<?php
/**
  * @method 跑街令 店铺操作
  * @author soul
  * @copyright 2018/7/23
  */
class PjlShop extends PjlBase
{
	public function __construct()
	{
		parent::__construct();
		LibFc::useMainDb();
	}
	/**
	  * @method 申请店铺（第一步：身份、店铺名称、logo、经营范围（品牌、零件）、地址、电话； 第二步：营业执照及法人信息；第三步店铺简介与门面图）
	  * @param  $uid 用户ID
	  * @param  $dataArr ['shop_style'=>, 'shop_name'=>, 'shop_pct_ids','shop_addr', 'shop_tel'.....]
	  * @author liao
	  * @copyright 2018/07/23
	  * @return ["status"=> bool(true), "data"=> $shopId, "code"=>""]
	  */
	public function addShop($uid, $dataArr)
	{
		if (LibFc::Int($uid) && !empty($dataArr) && is_array($dataArr))
		{
			//先存 后编辑
			// 检验店铺是否已经存在
			$res = $this->get('pl_shop',['count(*) count'],sprintf('and shop_id = %s',$uid),true);
			if ($res['data']['count'] > 0) return LibFc::ReturnData(true, '店铺已存在！','hasShop');

			$newArr = $this->checkShopData($uid, $dataArr);
			$newArr['shop_id'] = $uid;
			$newArr['shop_status'] = 1;
			//申请入驻时间
			$newArr['shop_apply_time'] = time();

			if(!empty($newArr['shop_b2c_shop_id']))
			{
				$newArr['shop_checkby'] = '{"name":"系统","result":1,"remark":"商城店铺","time":'.time().'}';
				$newArr['shop_status'] = 2;
			}

			$this->PjlDb->Begin();

			$PjlUser = new PjlUser();
			$PjlUser->initUser($uid);

			//建立新的店铺
			$this->add('pl_shop', $newArr);
			$this->add('pl_shop_user', ['shu_pu_uid'=>$newArr['shop_id'], 'shu_shop_id'=>$newArr['shop_id'], 'shu_atime'=>time()]);
			$gArr = [
				'ug_style'=>'openShop',
				'ug_des'=>'注册成为供应商'
			];
			$PjlUser->changeGrowth($uid, $gArr);

			$this->PjlDb->End();
			return LibFc::ReturnData(true, $newArr['shop_id']);
		}
		return LibFc::ReturnData(false, 'addShop 参数不正确！');
	}


	/*
	 * 检验店铺的数据
	 */
	protected function checkShopData($uid,$dataArr)
	{
		if (empty($dataArr) || !is_array($dataArr))
			return LibFc::ReturnData(false, '参数不正确！');
		$newArr = [];
		foreach ($dataArr as $key => $value) 
		{
			switch ($key) 
			{
				case 'shop_pu_id':
					if (!empty($value) && !LibFc::Int($value))
					{
						return LibFc::ReturnData(false, '店主ID格式不正确！');
					}
					$newArr['shop_pu_id'] = $value;
					break;
				case 'shop_style':
					if (empty(LibFc::Escape($value)))
					{
						return LibFc::ReturnData(false, '店铺身份不能为空！');
					}
					$newArr['shop_style'] = $value;
					break;
				case 'shop_logo':
					$newArr['shop_logo'] = $value;
					break;
				case 'shop_name':
					if (!empty($value))
					{
						//公司名称唯一
						$res = $this->get('pl_shop',['count(*) count'],sprintf("and shop_id != %s and shop_name = '%s'", $uid, LibFc::Escape($value)),true);
						if ($res['data']['count'] > 0)
						{
							return LibFc::ReturnData(false, '公司名称已被使用！');
						}
					}
					$newArr['shop_name'] = $value;
					break;
				case 'shop_pct_ids':
					$pctIdArr = [];
					if (!empty($value))
					{
						$pctIdArr = array_filter(explode(',', $value));
						if (empty($pctIdArr)) return LibFc::ReturnData(false, '公司地址不正确！');
						foreach ($pctIdArr as $pv) 
						{
							if (!LibFc::Int($pv))
							{
								return LibFc::ReturnData(false, '公司地址不正确！');
							}
						}
					}
					$newArr['shop_pct_ids'] = implode(',', $pctIdArr);
					break;
				case 'shop_addr':
					$newArr['shop_addr'] = $value;
					break;
				case 'shop_tel':
					$phoneArr = [];
					if (!empty($value))
					{
						//判断电话格式
						$phoneArr = array_filter(array_map('trim',explode(',', $value)));
						//为空则有误
						if (empty($phoneArr)) return LibFc::ReturnData(false, '电话不正确！');
						$maPhone = '/^1\d{10}$/';
						$maTel = '/^([0-9]{3,4}-)?[0-9]{7,8}$/';
						foreach ($phoneArr as $pv) 
						{
							if (!preg_match($maPhone, $pv) && !preg_match($maTel, $pv))
							{
								return LibFc::ReturnData(false, '电话不正确！');
							}
						}
					}
					$newArr['shop_tel'] = implode(',', $phoneArr);
					break;
				case 'shop_info':
					$newArr['shop_info'] = $value;
					break;
				case 'shop_img':
					$shopImgArr = [];
					if (!empty($value))
					{
						$shopImgArr = array_filter(explode(',', $value));
						if (count($shopImgArr) > 5)
						{
							return LibFc::ReturnData(false, '公司门面图过多，最多为5张！');
						}
					}
					$newArr['shop_img'] = implode(',', $shopImgArr);
					break;
				case 'shop_license':
					$newlicArr = [];
					if (!empty($value))
					{
						//验证法人信息  是json数组
						$licArr = json_decode($value,true);
						if (empty($licArr)) return LibFc::ReturnData(false, '法人信息不正确！');
						// 法人信息{license:营业执照  realname:姓名 idcard:身份证号码, idcardimg0:身份证正面  idcardimg1:身份证反面 idcardimg2:手持身份证}
						$arr = ['license', 'realname', 'idcard', 'idcardimg0', 'idcardimg1', 'idcardimg2'];
						foreach ($licArr as $lk => $lv) 
						{
							if (empty($lv)) continue;
							switch ($lk) 
							{
								case 'idcard':
									$maID = '/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/';
									if (!preg_match($maID, trim($lv)))
									{
										return LibFc::ReturnData(false, '法人身份证号码不合法！');
									}
									$newlicArr[$lk] = $lv;
									break;
								
								default:
									if (in_array($lk, $arr))
									{
										$newlicArr[$lk] = $lv;
									} else
									{
										return LibFc::ReturnData(false, '法人信息不正确！');
									}
									break;
							}
						}
					}
					$newArr['shop_license'] = !empty($newlicArr) ? json_encode($newlicArr,JSON_UNESCAPED_UNICODE) : '';
					break;
				case 'shop_scope':
					$newArr['shop_scope'] = $value;
					break;
				case 'shop_idcard':
					$value = trim($value);
					if ($value !== '' &&!preg_match('/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/',$value))
					{
						return LibFc::ReturnData(false, '身份证号码不合法！');
					}
					$newArr['shop_idcard'] = $value;
					break;
				case 'shop_b2c_shop_id':
					$newArr['shop_b2c_shop_id']=(int) $value;
					break;
				default:
					$newArr[$key]=$value;
					break;
			}
		}
		return $newArr;
	}
	
	/**
	  * @method 编辑店铺基本信息
	  * @param  $shopId 店铺ID
	  * @param  $dataArr ['shop_img'=>.....]  按照提供的字段进行必要的数据校验
	  * @author liao
	  * @copyright 2018/07/23
	  * @return ["status"=> bool(true), "data"=> "", "code"=>""]
	  */
	public function setShopBase($shopId, $dataArr)
	{
		if (LibFc::Int($shopId) && !empty($dataArr) && is_array($dataArr))
		{
			$res = $this->get('pl_shop',['*'],sprintf(' and shop_id = %s',$shopId),true);
			if (empty($res['data'])) return LibFc::ReturnData(false, '店铺不存在！');
			$shopData = $res['data'];

			if(!in_array($dataArr['shop_status'],['-1','0','1','2'])) return LibFc::ReturnData(false, '参数不正确！');
			$newArr = $this->checkShopData($shopId, $dataArr);

			$newArr['shop_status'] = $dataArr['shop_status'];
			$this->set('pl_shop', $newArr, sprintf('and shop_id = %s',$shopId));
			return LibFc::ReturnData(true, $shopId);
		}
		return LibFc::ReturnData(false, 'setShopBase 参数不正确！');
	}


	/**
	  * @method 店铺审核
	  * @param  $shopId 店铺ID
	  * @author $status -1审核不通过  2审核通过
	  * @author $checkArr [name=>审核人, time=>审核时间 result=>0|1 remark=>审核意见]
	  * @copyright 2018/07/23
	  * @return ["status"=> bool(true), "data"=> "", "code"=>""]
	  */
	public function checkShopOpen($shopId, $status, $checkArr)
	{
		if(!in_array($status, [-1,2])) return LibFc::ReturnData(false, '店铺状态不正确！');
		$res = $this->get('pl_shop',['*'], sprintf(' and shop_id = %d', $shopId),true);
		if (empty($res['data'])) return LibFc::ReturnData(false, '店铺不存在！');
		$shopData = $res['data'];
		$setArr = ['shop_status'=>$status, 'shop_checkby'=>$checkArr];
		$setArr['shop_checkby']['time'] = time();
		$setArr['shop_checkby']['result'] = $status == 2? 1 : 0;
		$setArr['shop_checkby'] = json_encode($setArr['shop_checkby'], JSON_UNESCAPED_UNICODE);
		$this->set('pl_shop', $setArr, sprintf(' and shop_id = %s', $shopData['shop_id']));
		return LibFc::ReturnData(true, true);
	}
	/**
	 * @method    setShopMap
	 * @param     [int]     	$shopId [店铺id]
	 * @param     [array]       $mapArr [经营名称]
	 * @author     liao
	 * @copyright 2018-08-06
	 * @return ["status"=> bool(true), "data"=> "true", "code"=>""]
	 */
	public function setShopMap($shopId,$mapArr)
	{
		if (LibFc::Int($shopId) && is_array($mapArr) && !empty($mapArr))
		{
			$mapArr = array_unique(array_filter($mapArr,'LibFc::Int'));
			if (!empty($mapArr))
			{
				// 更新插入
				$res = $this->get('pl_shop_mpart',['cp_mpa_id'],sprintf('and cp_shop_id = %s',$shopId));
				$oldArr = array_column($res['data'], 'cp_mpa_id');

				$inArr = array_diff($mapArr,$oldArr);
				$delArr = array_diff($oldArr, $mapArr);
				$this->PjlDb->Begin();
				if (!empty($delArr))
				{
					$this->del('pl_shop_mpart',sprintf('and cp_shop_id = %s and cp_mpa_id in (%s)',$shopId,implode(',', $delArr)));
				}

				if (!empty($inArr))
				{
					foreach ($inArr as $value) 
					{
						$this->add('pl_shop_mpart',['cp_shop_id'=>$shopId,'cp_mpa_id'=>$value]);
					}
				}
				$this->PjlDb->End();
				return LibFc::ReturnData(true, true);
			}
		}
		return LibFc::ReturnData(false,'setShopMap 参数不正确！');

	}


	/**
	  * @method 编辑店铺的经营品牌
	  * @param  $shopId 店铺ID
	  * @param  $brandIdArr [111,22,333]  空数组表示清空
	  * @author liao
	  * @copyright 2018/07/23
	  * @return ["status"=> bool(true), "data"=> "true", "code"=>""]
	  */
	public function setShopBrand($shopId, $brandIdArr)
	{
		if (LibFc::Int($shopId))
		{
			//判断过滤
			if (!empty($brandIdArr))
			{
				$brandIdArr = array_filter($brandIdArr, 'LibFc::Int');
				//如果为空则是数据不正常
				if (empty($brandIdArr)) return LibFc::ReturnData(false,'店铺的申请品牌不正确！');
				//唯一
				$brandIdArr = array_unique($brandIdArr);
			} else 
			{
				//为空则全部删除  返回
				$this->del('pl_shop_brand',sprintf(' and cb_shop_id = %s',$shopId));
				return LibFc::ReturnData(true, true);
			}

			// 获取原有的品牌 作更新插入
			$oldBrand = $this->get('pl_shop_brand',['cb_brand_id'],sprintf(' and cb_shop_id = %s',$shopId));
			$oldBrand = array_column($oldBrand['data'], 'cb_brand_id');

			$inBrand = array_diff($brandIdArr, $oldBrand);
			$delBrand = array_diff($oldBrand, $brandIdArr);
			
			//开启事务
			$this->PjlDb->Begin();
			//先删除原有的数据
			if(!empty($delBrand))
			{
				$this->del('pl_shop_brand',sprintf(' and cb_shop_id = %s and cb_brand_id in (%s)',$shopId,implode(',', $delBrand)));
			}
			//brandIdArr 不为空则入库
			if (!empty($inBrand))
			{
				//入库
				foreach ($inBrand as $value) 
				{
					$this->add('pl_shop_brand',['cb_shop_id'=>$shopId,'cb_brand_id'=>$value]);
				}
			}
			$this->PjlDb->End();
			return LibFc::ReturnData(true, true);
		}
		return LibFc::ReturnData(false,'setShopBrand 参数不正确！');
	}


	/**
	  * @method 编辑店铺的经营分类
	  * @param  $shopId 店铺ID
	  * @param  $partArr ["刹车片", ....]  空数组表示清空
	  * @author liao
	  * @copyright 2018/07/23
	  * @return ["status"=> bool(true), "data"=> "true", "code"=>""]
	  */
	public function setShopPart($shopId, $partArr)
	{
		if (LibFc::Int($shopId))
		{
			if (!empty($partArr))
			{
				//过滤 特殊字段   去空  
				$partArr = array_filter(array_map('LibFc::Escape', $partArr));
				//为空则是数据不正常
				if (empty($partArr)) return LibFc::ReturnData(false,'店铺的经营分类不正确！');
				//唯一
				$partArr = array_unique($partArr);
			} else
			{
				//为空则全部删除
				$this->del('pl_shop_part',sprintf(' and cp_shop_id = %s',$shopId));
				return LibFc::ReturnData(true, true);
			}
			$oldPart = $this->get('pl_shop_part',['cp_part_name'],sprintf(' and cp_shop_id = %s',$shopId));
			$oldPart = array_column($oldPart['data'], 'cp_part_name');

			$inPart = array_diff($partArr, $oldPart);
			$delPart = array_diff($oldPart, $partArr);
			//开启事务
			$this->PjlDb->Begin();
			//先删除原有的数据
			if (!empty($delPart))
			{
				$this->del('pl_shop_part',sprintf(" and cp_shop_id = %s and cp_part_name in ('%s')",$shopId,implode("','", $delPart)));
			}

			//partArr 不为空则入库
			if (!empty($inPart))
			{
				//入库
				foreach ($inPart as $value) 
				{
					$this->add('pl_shop_part',['cp_shop_id'=>$shopId,'cp_part_name'=>$value]);
				}
			}
			$this->PjlDb->End();
			return LibFc::ReturnData(true, true);
		}
		return LibFc::ReturnData(false,'setShopPart 参数不正确！');
	}


	/**
	  * @method 店铺添加子账号
	  * @param  $shopId 店铺ID
	  * @param  $uid 宜配会员ID
	  * @param  $dataArr ['shu_position'=>职位, 'shu_name'=>'对此员工的称呼', 'shu_remark', 'shu_rules']
	  * @author liao
	  * @copyright 2018/7/25
	  * @return ["status"=> bool(true), "data"=>'', "code"=>""]
	  */
	public function addShopUser($shopId, $uid, $dataArr)
	{
		if (LibFc::Int($shopId) && LibFc::Int($uid) && is_array($dataArr) && !empty($dataArr))
		{
			// 判断店铺是否存在
			$res = $this->get('pl_shop',['count(*) count'],sprintf('and shop_id = %s',$shopId),true);
			if ($res['data']['count'] < 1)
				return LibFc::ReturnData(false,'店铺不存在！');

			// 判断用户是否存在
			$res = $this->get('pl_user',['count(*) count'],sprintf('and pu_uid = %s',$uid),true);
			if ($res['data']['count'] < 1)
				return LibFc::ReturnData(false,'用户不存在！');
			
			//判断子账号是否存在
			$res = $this->get('pl_shop_user',['count(*) count'],sprintf('and shu_pu_uid = %s and shu_shop_id = %s', $uid, $shopId),true);
			if ($res['data']['count'] > 0)
				return LibFc::ReturnData(false,'子账号已存在！');
			$newArr = [];
			$newArr['shu_pu_uid'] = $uid;
			$newArr['shu_shop_id'] = $shopId;
			foreach ($dataArr as $key => $value) 
			{
				switch ($key) 
				{
					case 'shu_position':
						if (empty($value))
							return LibFc::ReturnData(false,'子账号职位不能为空！');
						$newArr['shu_position'] = $value;
						break;
					case 'shu_name':
						if (empty($value))
							return LibFc::ReturnData(false,'子账号称呼不能为空！');
						$newArr['shu_name'] = $value;
						break;
					case 'shu_remark':
						if (!empty($value))
							$newArr['shu_remark'] = $value;
						break;
					case 'shu_rules':
						if (!empty($value))
						{
							$ruleArr = array_unique(array_filter(explode(',', $value)));
							if (empty($ruleArr))
								return LibFc::ReturnData(false,'子账号权限不正确！');
							$newArr['shu_rules'] = implode(',', $ruleArr);
						}
						break;
				}
			}
			$newArr['shu_atime'] = time();
			$this->add('pl_shop_user',$newArr);
			return LibFc::ReturnData(true,true);
		}
		return LibFc::ReturnData(false,'addShopUser 参数不正确！');
	}


	/**
	  * @method 修改店铺子账号信息
	  * @param  $shopId 店铺ID
	  * @param  $uid 宜配会员ID
	  * @param  $dataArr ['shu_position'=>职位, 'shu_name'=>'对此员工的称呼', 'shu_remark', 'shu_rules']
	  * @author liao
	  * @copyright 2018/7/25
	  * @return ["status"=> bool(true), "data"=>'', "code"=>""]
	  */
	public function setShopUser($shopId, $uid, $dataArr)
	{
		if (LibFc::Int($shopId) && LibFc::Int($uid) && is_array($dataArr) && !empty($dataArr))
		{
			//判断店铺子账号是否存在
			$res = $this->get('pl_shop_user',['count(*) count'],sprintf('and shu_pu_uid = %s and shu_shop_id = %s', $uid, $shopId),true);
			if ($res['data']['count'] > 0)
			{
				$newArr = [];
				foreach ($dataArr as $key => $value) 
				{
					switch ($key) 
					{
						case 'shu_status':
							if (empty($value))
								return LibFc::ReturnData(false,'子账号状态不正常！');
							$newArr['shu_status'] = $value == '1' ? '1' : '-1';
							break;
						case 'shu_position':
							if (empty($value))
								return LibFc::ReturnData(false,'子账号职位不能为空！');
							$newArr['shu_position'] = $value;
							break;
						case 'shu_name':
							if (empty($value))
								return LibFc::ReturnData(false,'子账号称呼不能为空！');
							$newArr['shu_name'] = $value;
							break;
						case 'shu_remark':
								$newArr['shu_remark'] = $value;
							break;
						case 'shu_rules':
							$ruleArr = [];
							if (!empty($value))
							{
								$ruleArr = array_unique(array_filter(explode(',', $value)));
								if (empty($ruleArr))
									return LibFc::ReturnData(false,'子账号权限不正确！');
							}
							$newArr['shu_rules'] = implode(',', $ruleArr);
							break;
					}
				}
				$this->set('pl_shop_user',$newArr,sprintf('and shu_pu_uid = %s and shu_shop_id = %s', $uid, $shopId));
				return LibFc::ReturnData(true,true);
			} else
			{
				return LibFc::ReturnData(false,'子账号不存在！');
			}
		}
		return LibFc::ReturnData(false,'setShopUser 参数不正确！');
	}
	/**
	 * @method    更新店铺关注品牌
	 * @param     [int]          $shopId   [店铺ID]
	 * @param     array           $brandArr [品牌Id]
	 * @return    [type]                    [description]
	 * @author 卢
	 * @copyright 2018-08-28
	 */
	function updateShopBrand($shopId,$brandArr=[])
	{
		if(LibFc::Int($shopId))
		{
			$res=$this->get('pl_shop_brand',['cb_brand_id'],sprintf(' and cb_shop_id=%d',$shopId));
			$exitArr=array_column($res['data'], 'cb_brand_id');
			$addArr=array_diff($brandArr, $exitArr);
			$delArr=array_diff($exitArr, $brandArr);
			$this->PjlDb->Begin();
			if(!empty($addArr))
			{
				foreach ($addArr as $v) 
				{
					$this->add('pl_shop_brand',['cb_shop_id'=>$shopId,'cb_brand_id'=>$v]);
				}
			}
			if(!empty($delArr))
			{
				$this->delShopBrand($shopId,$delArr);
			}
			$this->PjlDb->End();
			return LibFc::ReturnData(true,true);
		}
		return LibFc::ReturnData(false,'updateShopBrand 参数不正确！');
	}
	/**
	 * @method    删除店铺关注品牌
	 * @param     [int]       $shopId [店铺ID]
	 * @param     [int|arr]       $brand  [品牌id]
	 * @return    [bool]               [description]
	 * @author 卢
	 * @copyright 2018-08-28
	 */
	function delShopBrand($shopId,$brand)
	{
		if(!empty($brand)&&LibFc::Int($shopId))
		{
			$brandArr=is_array($brand)?array_filter($brand,'LibFc::Int'):[(int)$brand];
			if(!empty($brandArr))
			{
				$res=$this->del('pl_shop_brand',sprintf(' and cb_brand_id in(%s) and cb_shop_id=%d',implode(',',$brandArr),$shopId));
				return $res;
			}
		}
		return LibFc::ReturnData(false,'delShopBrand 参数不正确！');
	}
	/**
	 * @method    更新店铺关注地区
	 * @param     [int]        $shopId  [店铺id]
	 * @param     array         $dataArr [1,2,3] //新的地区id 二级地区
	 * @author 卢
	 * @copyright 2018-09-10
	 */
	function updateShopPct($shopId,$dataArr=[])
	{
		if(LibFc::Int($shopId))
		{
			$res=$this->get('pl_shop_pct',['spc_pc_id'],sprintf(' and spc_shop_id=%d',$shopId));
			$exitArr=array_column($res['data'], 'spc_pc_id');
			$addArr=array_diff($dataArr, $exitArr);
			$delArr=array_diff($exitArr, $dataArr);
			$this->PjlDb->Begin();
			if(!empty($addArr))
			{
				foreach ($addArr as $v) 
				{
					$this->add('pl_shop_pct',['spc_shop_id'=>$shopId,'spc_pc_id'=>$v]);
				}
			}
			if(!empty($delArr))
			{
				$this->delShopPct($shopId,$delArr);
			}
			$this->PjlDb->End();
			return LibFc::ReturnData(true,true);
		}
		return LibFc::ReturnData(false,'updateShopPct 参数不正确！');
	}
	/**
	 * @method    删除店铺关注地区
	 * @param     [int ]     $shopId  [店铺id]
	 * @param     [arr]     $dataArr [2,3,4]  待删除的地区 第二级
	 * @return    [type]              [description]
	 * @author 卢
	 * @copyright 2018-09-10
	 */
	function delShopPct($shopId,$dataArr)
	{
		if(!empty($dataArr)&&LibFc::Int($shopId))
		{
			$dataArr=is_array($dataArr)?array_filter($dataArr,'LibFc::Int'):[(int)$dataArr];
			if(!empty($dataArr))
			{
				$res=$this->del('pl_shop_pct',sprintf(' and spc_pc_id in(%s) and spc_shop_id=%d',implode(',',$dataArr),$shopId));
				return $res;
			}
		}
		return LibFc::ReturnData(false,'delShopPct 参数不正确！');
	}
	/**
	 * @method    更新店铺关注分类
	 * @param     [int]         $shopId  [店铺Id]
	 * @param     array          $dataArr [1,2,3]  新的分类ID
	 * @return    [type]                  [description]
	 * @author 卢
	 * @copyright 2018-09-10
	 */
	function updateShopPart($shopId,$dataArr=[])
	{
		if(LibFc::Int($shopId))
		{
			$res=$this->get('pl_shop_part',['shp_part_id'],sprintf(' and shp_shop_id=%d',$shopId));
			$exitArr=array_column($res['data'], 'shp_part_id');
			$addArr=array_diff($dataArr, $exitArr);
			$delArr=array_diff($exitArr, $dataArr);
			$this->PjlDb->Begin();
			if(!empty($addArr))
			{
				foreach ($addArr as $v) 
				{
					$this->add('pl_shop_part',['shp_shop_id'=>$shopId,'shp_part_id'=>$v]);
				}
			}
			if(!empty($delArr))
			{
				$this->delShopPart($shopId,$delArr);
			}
			$this->PjlDb->End();
			return LibFc::ReturnData(true,true);
		}
		return LibFc::ReturnData(false,'updateShopPart 参数不正确！');
	}
	/**
	 * @method    删除店铺关注分类
	 * @param     [int ]     $shopId  [店铺id]
	 * @param     [arr]     $dataArr [2,3,4]  待删除的地区 第二级
	 * @return    [type]              [description]
	 * @author 卢
	 * @copyright 2018-09-10
	 */
	function delShopPart($shopId,$dataArr)
	{
		if(!empty($dataArr)&&LibFc::Int($shopId))
		{
			$dataArr=is_array($dataArr)?array_filter($dataArr,'LibFc::Int'):[(int)$dataArr];
			if(!empty($dataArr))
			{
				$res=$this->del('pl_shop_part',sprintf(' and shp_part_id in(%s) and shp_shop_id=%d',implode(',',$dataArr),$shopId));
				return $res;
			}
		}
		return LibFc::ReturnData(false,'delShopPart 参数不正确！');
	}
	/**
	 * @method    添加店铺日志
	 * @param     [int]     $shopId  [店铺id]
	 * @param     [arr]     $dataArr ['log_txt'=>xxxx]
	 * @author 卢
	 * @copyright 2018-09-10
	 */
	function addLog($shopId,$dataArr)
	{
		if(LibFc::Int($shopId)&&!empty($dataArr))
		{
			$dataArr['log_shop_id']=$shopId;
			$dataArr['log_pu_uid']=mvc::$cfg['LOGUSER']['uid'];
			$dataArr['log_username']=mvc::$cfg['LOGUSER']['uname'];
			$dataArr['log_atime']=time();
			$dataArr['log_ip']=mvc::$cfg['LOGUSER']['ip'];
			$this->add('pl_log',$dataArr);
			return LibFc::ReturnData(true,true);
		}
		return LibFc::ReturnData(false,'addLog 参数不正确！');
	}
	/**
	 * @method    获取店铺近成交金额
	 * @param     [arr]    $shopIds   [店铺id]
	 * @param     [int]    $time   [时限]
	 * @author    liao
	 * @copyright 2018-01-09
	 * @return
	 */
	public function getShopBusiness($shopIds,$time=0)
	{
		// 校验店铺ID
		if(empty($shopIds) || !is_array($shopIds))
			return LibFc::ReturnData(false,'getShopBusiness 参数错误！');
		// 过滤数组
		$shopIds = array_filter($shopIds,"LibFc::Int");

		if(empty($shopIds)) return LibFc::ReturnData(false,'getShopBusiness 参数格式错误！');

		// 限定时间段销售额
		$timeWhere = $time > 0 ? sprintf(" and ord_coplete_time > %d ",$time) : "";

		// 获取time时间段内completed的订单金额总额度
		$where = sprintf(" and ord_shop_id in (%s) and ord_status='completed' ". $timeWhere, implode(',', $shopIds));
		$res = $this->get("pl_order",['ord_money','ord_freight_money','ord_id','ord_shop_id'], $where);
		$res = $res['data'];
		// 获取每间店铺总商品金额
		$ordSum = array();
		$freightSum = array();
		$godSum = array();
		// 获取所有订单ID
		$orderIdArray = array();

		foreach ($res as $k => $v)
		{
			$ordSum[$v['ord_shop_id']] += $v['ord_pay_money'];
			$freightSum[$v['ord_shop_id']] += $v['ord_freight_money'];
			$orderIdArray[] = $v['ord_id'];
		}

		$realSalMoney = array();
		// 获取店铺实际支付金额
		foreach ($shopIds as $k => $v)
		{
			$realSalMoney[$v] = $ordSum[$v]-$freightSum[$v];
		}

		// 如果订单都是空的那么退款金额必然为空
		if(empty($orderIdArray)) return LibFc::ReturnData(true,$realSalMoney);

		// 获取每个店铺对应的退款金额
		$res = $this->get("pl_refund_pact",['sum(rep_money) refund_count','rep_shop_id'],sprintf(" and rep_ord_id in (%s) and rep_type !=2 and rep_status = 'refunded' group by rep_shop_id ",implode(',', $orderIdArray)));
		$res = $res['data'];
		$tmp = array();
		foreach ($res as $k => $v)
		{
			$tmp[$v['rep_shop_id']] = $v['refund_count'];
		}
		// 去除退还的金额
		foreach ($realSalMoney as $k => $v)
		{
			$realSalMoney[$k] = sprintf("%.2f",$realSalMoney[$k])-sprintf("%.2f",$tmp[$k]);
		}
		// 卖家销售额
		return LibFc::ReturnData(true,$realSalMoney);
	}





	/**
	 * @method 同步附近配件商的附近的地址和发现的地址
	 * @author soul
	 * @copyright 2020/1/3
	 */
	public function updateShopAddr($shopId)
	{
		$shopId = (int) $shopId;
		$OthPct = new OthPct();
		$this->PjlDb->Begin();

		//是否有商铺
		$res = $this->get('pl_shop', ['shop_id', 'shop_pu_id', 'shop_pct_ids', 'shop_addr', 'shop_tel', 'shop_license'], sprintf(" and shop_id=%d", $shopId), true);
		if(!empty($res['data']))
		{
			$shopArr = $res['data'];
			$res = $this->get('pl_shop_addr', ['sha_id'], sprintf(" and sha_shop_id=%d and sha_main = 1", $shopId), true);
			if(empty($res['data']))
			{
				$shopArr['shop_license'] = json_decode($shopArr['shop_license'], true);
				$setArr = [
					'sha_shop_id'=>$shopId,
					'sha_pct_ids'=>$shopArr['shop_pct_ids'],
					'sha_main'=>1,
					'sha_tel'=>$shopArr['shop_tel'],
					'sha_name'=>$shopArr['shop_license']['realname'],
					'sha_addr'=>$shopArr['shop_addr'],
					'sha_atime'=>time(),
					'sha_etime'=>time()
				];
				
				//经纬度
				$res = $OthPct->formatAddrInfo($setArr['sha_addr'], $setArr['sha_pct_ids']);
				$pct = $res['data'];
				if(count($pct['pctids']) >= 2 && $pct['lng'])
				{
					$setArr['sha_lng'] = $pct['lng'];
					$setArr['sha_lat'] = $pct['lat'];
				}
			
				$YpwBase = new YpwBase();
				$res = $YpwBase->get('yp_user',['u_real_name', 'u_mobile'], sprintf(" and u_id =%d", $shopArr['shop_pu_id']), true);
				$userArr = $res['data'];
				if(empty($setArr['sha_tel'])) $setArr['sha_tel'] = $userArr['u_mobile'];
				//if(empty($setArr['sha_name'])) $setArr['sha_name'] = $userArr['u_real_name'];

				$this->add('pl_shop_addr', $setArr);
			}

			//同步发现地址
			$this->del('pl_around_shop', sprintf(" and ars_shop_id=%d and ars_sha_id not in (select sha_id from pl_shop_addr where sha_shop_id=%d)", $shopId, $shopId));

			$res = $this->get('pl_around_shop', ['ars_sha_id'], sprintf(" and ars_shop_id=%d", $shopId));
			$hasArr = array_column($res['data'], 'ars_sha_id');

			//更新尚未有经纬度的地址
			$res = $this->get('pl_shop_addr JOIN pl_shop ON shop_id = sha_shop_id', ['*'], sprintf(" and sha_shop_id=%d", $shopId));
			$cArr = $res['data'];
			foreach($cArr as $v)
			{
				if($v['sha_lng'] < 1)
				{
					$res = $OthPct->formatAddrInfo($v['sha_addr'], $v['sha_pct_ids']);
					$pct = $res['data'];
					if(count($pct['pctids']) >= 2 && $pct['lng'])
					{
						$set = [
							'sha_lng'=>$pct['lng'],
							'sha_lat'=>$pct['lat'],
						];
						$this->set('pl_shop_addr', $set, ' and sha_id='.$v['sha_id']);
						$v = array_merge($v, $set);
					}
				}
				
				$aroundArr = [
					'ars_uid'=>$v['shop_pu_id'],
					'ars_shop_id'=>$v['shop_id'],
					'ars_style'=>$v['shop_style'],
					'ars_name'=>$v['shop_name'],
					'ars_contacts'=>$v['sha_name'],
					'ars_tel'=>$v['sha_tel'],
					'ars_pct_ids'=>$v['sha_pct_ids'],
					'ars_lng'=>$v['sha_lng'],
					'ars_lat'=>$v['sha_lat'],
					'ars_addr'=>$v['sha_addr'],
					'ars_scope'=>$v['shop_scope'],
					'ars_sha_id'=>$v['sha_id']
				];
				if(in_array($v['sha_id'], $hasArr))
				{
					$this->set('pl_around_shop', $aroundArr, sprintf(" and ars_shop_id=%d  and ars_sha_id=%d", $shopId, $v['sha_id']));
				}
				else
				{
					$this->add('pl_around_shop', $aroundArr);
				}
			}
		}
		
		//维修厂
		$res = $this->get('pl_repair', ['shopr_id', 'shopr_pu_id', 'shopr_name', 'shopr_pct_ids', 'shopr_addr', 'shopr_tel', 'shopr_lng', 'shopr_lat', 'shopr_youhui'], sprintf(" and shopr_id=%d", $shopId), true);
		if(!empty($res['data']))
		{
			$shopArr = $res['data'];
			if($shopArr['shopr_lng'] < 1)
			{
				$res = $OthPct->formatAddrInfo($shopArr['shopr_addr'], $shopArr['shopr_pct_ids']);
				$pct = $res['data'];
				if(count($pct['pctids']) >= 2)
				{
					$set = [
						'shopr_lng'=>$pct['lng'],
						'shopr_lat'=>$pct['lat'],
					];
					$this->set('pl_repair', $set, ' and shopr_id='.$shopArr['shopr_id']);
					$shopArr = array_merge($shopArr, $set);
				}
			}
			
			$aroundArr = [
				'ars_uid'=>$shopArr['shopr_pu_id'],
				'ars_shopr_id'=>$shopArr['shopr_id'],
				'ars_style'=>'维修厂',
				'ars_name'=>$shopArr['shopr_name'],
				'ars_tel'=>$shopArr['shopr_tel'],
				'ars_pct_ids'=>$shopArr['shopr_pct_ids'],
				'ars_lng'=>$shopArr['shopr_lng'],
				'ars_lat'=>$shopArr['shopr_lat'],
				'ars_addr'=>$shopArr['shopr_addr'],
				'ars_scope'=>$shopArr['shopr_youhui']
			];

			$res = $this->get('pl_around_shop', ['ars_id'], sprintf(" and ars_shopr_id=%d", $shopId));
			if(!empty($res['data']))
			{
				$this->set('pl_around_shop', $aroundArr, sprintf(" and ars_shopr_id=%d", $shopId));
			}
			else
			{
				$this->add('pl_around_shop', $aroundArr);
			}
		}
		$this->PjlDb->End();
		return LibFc::ReturnData(true);
	}

	
	/**
	  * @method 开通群聊机器人或者同步微信群聊机器人的状态
	  * @param  $shopId 店铺ID
	  * @return ["status"=> bool(true), "data"=> $wr_id, "code"=>""]
	  */
	public function autoSetWxrobot($shopId)
	{
		$wr_id = 0;
		$now = time();
		$res = $this->get('pl_shop', ['shop_id', 'shop_status', 'shop_name', 'shop_vip_etime'], sprintf(" and shop_id=%d", $shopId), true);
		if(empty($res['data'])) return LibFc::ReturnData(true, $wr_id);
		$shopInfo = $res['data'];
		
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('wx_robot', ['*'], sprintf(" and wr_uid=%d and wr_type='wxgr' and wr_totype='pjlshop'", $shopInfo['shop_id']), true);
		$wrArr = $res['data'];
		$this->PjlDb->Begin();
		//开通
		if(empty($wrArr)){
			if($shopInfo['shop_status'] == 2 && $shopInfo['shop_vip_etime'] > $now){
				//找最少群的官方token
				$table = 'wx_robot_token JOIN wx_robot ON wr_wrt_id = wrt_id';
				$res = $B2cBase->get($table, ['wrt_id'], " and wrt_pjlshop = 1 GROUP BY wrt_id ORDER BY sum(wr_room_max) limit 1", true);
				$tokenInfo = $res['data'];

				$add = [
					'wr_name'=>$shopInfo['shop_name'],
					'wr_wrt_id'=>$tokenInfo['wrt_id'],
					'wr_uid'=>$shopInfo['shop_id'],
					'wr_type'=>'wxgr',
					'wr_totype'=>'pjlshop',
					'wr_btime'=>$now,
					'wr_etime'=>$shopInfo['shop_vip_etime'],
					'wr_room_max'=>3,
					'wr_vin_fileds'=>'mod3_engine,mod3_kw,mod3_cc,mod3_transmission,mod3_drive,mod3_year',
					'wr_othcof'=>'numpjl,itemprice,itemquality',
				];
				$res = $B2cBase->add('wx_robot', $add);
				$wr_id = $res['data'];
				$this->noticeShopRobot($shopId);
			}else{//店铺异常
				return LibFc::ReturnData(true, $wr_id);
			}
		}else{
			//已有更新
			$wr_id = $wrArr['wr_id'];
			$set = [];
			if($shopInfo['shop_status'] != 2 && $wrArr['wr_status'] == 1) $set['wr_status'] = -1;
			if($shopInfo['shop_status'] == 2 && $wrArr['wr_status'] != 1) $set['wr_status'] = 1;
			if($shopInfo['shop_vip_etime'] != $wrArr['wr_etime']) $set['wr_etime'] = $shopInfo['shop_vip_etime'];
			if($set) $B2cBase->set('wx_robot', $set, sprintf(" and wr_id=%d", $wr_id));
		}
		$this->PjlDb->End();
		return LibFc::ReturnData(true, $wr_id);
	}
	
	/**
	  * @method 添加推送商家机器人消息
	  * @param  $shopId 店铺ID
	  * @return ["status"=> bool(true), "data"=> $tmh_id, "code"=>""]
	  */
	public function noticeShopRobot($shopId)
	{
		$tmtype = 'pjlrobot';
		$res = $this->get('ts_msg_tpl', ['*'], " and tm_type='{$tmtype}' and tm_status = 1", true);
		$tsTplArr = $res['data'];
		if(empty($tsTplArr)) return LibFc::ReturnData(true);
		$msg = $tsTplArr['tm_tpl'];
		$unikey = $tmtype;
		$tsArr = [
			'tmh_u_id'=>$shopId,
			'tmh_tm_id'=>$tsTplArr['tm_id'],
			'tmh_unikey'=>$unikey,
			'tmh_para'=>'[]',
			'tmh_msg'=>$msg,
			'tmh_atime'=>time(),
			'tmh_add_u_id'=>8
		];
		$res = $this->add('ts_msg_history', $tsArr);
		$tmh_id = $res['data'];
		$AdsTj = new AdsTj();
		$AdsTj->runTsTask([$tmh_id]);
		return LibFc::ReturnData(true, $tmh_id);
	}


	public function initPjlRepair($shoprId)
	{
		if(!$shoprId) return LibFc::ReturnData(false,'参数错误');
		
		$res = $this->get('pl_repair',['*'],sprintf(" AND shopr_id=%d",$shoprId),true);
		//先检测pl_repair是否已经审核
		if($res['data']['shopr_status']!=2)
		{
			return LibFc::ReturnData(true,'维修厂未审核');
		}
		$repairArr = $res['data'];
		//再检测rep_worker是否存在wo_shopr_id
		$res = $this->get('rep_worker',['count(*) as counts'],sprintf(" AND wo_shopr_id=%d",$shoprId),true);
		
		//如果不存在，初始化rep_worker、rep_option_link
		if($res['data']['counts']<=0)
		{
			$this->PjlDb->Begin();

			//初始化worker
			$workerData = [
				'wo_shopr_id'=>$repairArr['shopr_id'],
				'wo_uid'=>$repairArr['shopr_id'],
				'wo_status'=>1,
				'wo_name'=>$repairArr['shopr_name']??'',
				'wo_tel'=>$repairArr['shopr_tel']??'',
				'wo_addr'=>$repairArr['shopr_addr']??'',
				'wo_atime'=>time(),
				'wo_etime'=>time()
			];
			$this->add('rep_worker',$workerData);
			//初始化option_link
			$res = $this->get('rep_option_link',['*']," AND opl_shopr_id=8");
			$newArr = $res['data'];

		
			if($newArr)
			{	
				$arr = [];
				//已存在的数据
				$oldres = $this->get('rep_option_link',['opl_from_opl_id'],sprintf(" AND opl_shopr_id=%d AND opl_from_opl_id>0",$shoprId));
				$oldArr = $oldres['data'];
				$existArr = array_column($oldArr,'opl_from_opl_id');
				foreach ($newArr as $val) 
				{
					if(!in_array($val['opl_id'],$existArr))
					{
						$val['opl_from_opl_id'] = $val['opl_id'];
						$val['opl_shopr_id'] = $shoprId;
						$val['opl_cfg'] = json_encode([]);
						$val['opl_atime'] = time();
						$val['opl_etime'] = time();
						unset($val['opl_id']);
						$arr[] = $val;
					}
				}
				if($arr)
				{
					$this->addAny('rep_option_link',array_keys($arr[0]),$arr);
				}
			}
			
			$this->PjlDb->End();
		}

		return LibFc::ReturnData(true);
	}
}