<?php
/**
  * @method 店铺类
  * @author 卢
  * @copyright 2017/7/22
  */
class B2cShop extends B2cBase
{

	/**
	  * @method 后台配置项目
	  * @author soul
	  * @copyright 2017/7/29
	  * @return 
	  */
	public function allConfigName()
	{
		$arr = [
			//目录后台车型显示列
			'modelFileds' => [
				'brand_name'=>['name'=>'品牌', 'show'=>1, 'w'=>'80px'],	
				'make_name'=>['name'=>'生产商', 'show'=>1, 'w'=>'90px'],	
				'mod1_name'=>['name'=>'车系', 'show'=>1, 'w'=>'80px'],	
				'mod2_name'=>['name'=>'车代', 'show'=>1, 'w'=>'100px'],	
				'mod2_year'=>['name'=>'车代年', 'show'=>1, 'w'=>'60px'],	
				'mod3_name'=>['name'=>'车型', 'show'=>1, 'w'=>'200px'],	
				'mod3_year'=>['name'=>'车型年', 'show'=>1, 'w'=>'60px'],	
				'sparts'=>['name'=>'配件类别', 'show'=>1, 'w'=>'140px'],	
				'mod3_engine'=>['name'=>'发动机', 'show'=>1, 'w'=>'80px'],	
				'mod3_kw'=>['name'=>'功率', 'show'=>1, 'w'=>'40px', 'sort'=>'float'],	
				'mod3_cc'=>['name'=>'排量', 'show'=>1, 'w'=>'40px', 'sort'=>'float'],	
				'mod3_fuel'=>['name'=>'燃料', 'show'=>1, 'w'=>'40px'],	
				'mod3_transmission'=>['name'=>'变速器', 'show'=>1, 'w'=>'60px'],	
				//'mod3_body'=>['name'=>'车身形式', 'show'=>1, 'w'=>'80px'],	
				'mod3_front_brake'=>['name'=>'前制动器', 'show'=>1, 'w'=>'60px'],	
				'mod3_rear_brake'=>['name'=>'后制动器', 'show'=>1, 'w'=>'60px'],	
				'mod3_parking_brake'=>['name'=>'驻车制动', 'show'=>1, 'w'=>'60px'],	
				'mod3_drive'=>['name'=>'驱动方式', 'show'=>1, 'w'=>'60px'],
			]
		];
		return LibFc::ReturnData(true, $arr);
	}


	
	/**
	  * @method 后台配置项目
	  * @author soul
	  * @copyright 2017/7/29
	  * @return 
	  */
	public function setUserConfig($uid, $config)
	{
		$uid = (int) $uid;
		if($uid > 0 && is_array($config))
		{
			$res = $this->get('sh_user_config', ['suc_config'], sprintf(" and suc_uid=%d", $uid), true);
			if(!empty($res['data']))
			{
				$has = json_decode($res['data']['suc_config'], true);
				foreach($has as $filed=>$val)
				{
					if(!isset($config[$filed])) $config[$filed] = $val;
				}
				$this->set('sh_user_config', ['suc_config'=>json_encode($config)], sprintf(" and suc_uid=%d", $uid));
			}
			else
			{
				$this->add('sh_user_config', ['suc_uid'=>$uid, 'suc_config'=>json_encode($config)]);
			}
		}
		return LibFc::ReturnData(true, true);
	}


	/**
	  * @method 后台配置项目
	  * @author soul
	  * @copyright 2017/7/29
	  * @return 
	  */
	public function getUserConfig($uid)
	{
		$uid = (int) $uid;
		$res = $this->allConfigName();
		$arr['name'] = $res['data'];
		$arr['user'] = [];
		
		//用户已有配置
		$res = $this->get('sh_user_config', ['suc_config'], sprintf(" and suc_uid=%d", $uid), true);
		if(!empty($res['data'])) $arr['user'] = json_decode($res['data']['suc_config'], true);

		return LibFc::ReturnData(true, $arr);
	}






	/**
	  * @method 获取店铺的平均分
	  * @author soul
	  * @copyright 2017/7/29
	  * @return 
			成功 ["status"=>true, "data"=>['DESCRIBE'=>4.9555, 'SERVICE'=>5.000, 'LOGISTICS'=>4.8565]]  
	  */
	public function getShopAverage()
	{
		return $this->get('sh_shop', ['avg(shop_describe_score) `describe`, avg(shop_service_score) `service`, avg(shop_logistics_score) logistics'], '', true);
	}
	/**
	  * @method 获取店铺的最高分
	  * @author liao
	  * @copyright 2017/8/1
	  * @return 
			成功 ["status"=>true, "data"=>['DESCRIBE'=>4.9555, 'SERVICE'=>5.000, 'LOGISTICS'=>4.8565]]  
	  */
	public function getShopHighest()
	{
		return $this->get('sh_shop', ['max(shop_describe_score) `describe`, max(shop_service_score) `service`, max(shop_logistics_score) logistics'], '', true);
	}
	/**
	 * @method    获取店铺的信息 评分|logo|名称
	 * @param     [int]      $shopId  [店铺id]
	 * @author     廖
	 * @copyright 2017-08-21
	 * @return    ["status"=>true, "data"=>['logo'=>xxx, 'SERVICE'=>xxx, 'LOGISTICS'=>xxx,...]]  
	 */
	public function getShopInfo($shopId)
	{
		if(LibFc::Int($shopId))
		{
			$fileArr = ['shop_id','shop_uid', 'ub_username','shop_logo','shop_name','shop_reg_time','shop_pct_ids','shop_describe_score','shop_service_score','shop_logistics_score','shop_domain','shop_apply_tatus', 'shop_show_b2c', 'shop_show_app', 'shop_show_super', 'shop_show_pjl', 'shop_zbnum', 'shop_smainnum'];
			$re = $this->get('sh_shop left join us_user_base on ub_uid = shop_uid', $fileArr, ' and shop_id='.$shopId, true);
			return $re;
		}else
		{
			return LibFc::ReturnData(false, '参数错误');
		}
	}

	/**
	 * @method    获取店铺信息
	 * @param     [int|arr]    $shopIds  [店铺id]
	 * @param     [arr]        $fileArr  [需要获取的参数]
	 * @param     [string]     $order    [排序条件]
	 * @author     xu
	 * @copyright 2018-04-16
	 * @return    ["status"=>true, "data"=>[['logo','SERVICE','LOGISTICS'...],[...]]  
	 */
	public function getShopMsg($shopIds , $fileArr = [] ,$order='')
	{
		// 参数
		if(empty($shopIds))
			return LibFc::ReturnData(false, 'getShopMsg店铺ID为空');
		$ids = is_array($shopIds) ? array_filter($shopIds,'LibFc::Int') : [LibFc::Int($shopIds)];
		if(empty($ids))
			return LibFc::ReturnData(false, 'getShopMsg店铺ID格式不正确');
		$fileArr = empty($fileArr) ? ['*'] :$fileArr;
		// 执行
		$where =  sprintf(' and shop_id in (%s)',implode(',', $ids)).$order;
		$res = $this->get('sh_shop left join us_user_base on ub_uid = shop_uid', $fileArr , $where);
		$res = array_column($res['data'], null ,'shop_id');
		// 顺序
		$data = array();
		foreach ($ids as $v) {
			$data[] = $res[$v];
		}
		// 返回
		return LibFc::ReturnData(true,$data);		
	}


	/**
	 * @method    获取店铺橱窗推荐
	 * @param     [int|arr]    $shopIds  [店铺id]
	 * @param     [arr]        $num  [需要获取的商品条数]
	 * @author     xu
	 * @copyright 2018-04-16
	 * @return    ["status"=>true, "data"=>[['proid','propic'...],[...]]  
	 */
	public function getShopRecomonPro($shopIds , $num = 4)
	{
		// 参数
		if(empty($shopIds) || !LibFc::Int($num))
			return LibFc::ReturnData(false, '参数错误');
		$ids = is_array($shopIds) ? array_filter($shopIds,'LibFc::Int') : [LibFc::Int($shopIds)];
		if(empty($ids))
			return LibFc::ReturnData(false, '参数错误');
		// 执行
		$data = array();
		$proIds = array();
		foreach ($ids as $id) {
			$temp = ['pro_id','pro_promotion_price','pro_promotion_btime','pro_promotion_etime','pro_name','pro_shop_id','pro_sale_price'];
			$where = sprintf("and pro_shop_id =%d and pro_status=1 and pro_count>0 order by pro_promoted desc, pro_sold_count desc, pro_id desc limit %d",$id,$num);
			$res = $this->get('bc_product', $temp, $where);
			$proIds = array_merge($proIds,array_column($res['data'], 'pro_id'));
			$data[$id]  = $res['data'];
		}
		// 商品主图
		$B2cProduct = new B2cProduct();
		$res = $B2cProduct->getProductPic($proIds);
		foreach ($data as $shopId => $v) {
			foreach ($v as $kk => $pro) {
				$data[$shopId][$kk] = array_merge(empty($res['data'][$pro['pro_id']])?[]:current($res['data'][$pro['pro_id']]),$pro);
			}
		}
		// 返回
		return LibFc::ReturnData(true,$data);		
	}







	/**
	 * @method   自动增加店铺会员等级（默认关闭）;在开通店铺的时候需要调用一下这个接口
	 * @param     [int]      $shopId  [店铺id]
	 * @author     xu
	 * @copyright 2017-09-23
	 * @return    ["status"=>true, "data"=>[''logo'=>xxx, 'SERVICE'=>xxx, 'LOGISTICS'=>xxx,...']]  
	 */
	public function autoAddmemberLevel($shopId)
	{

		// 参数
		if(!LibFc::Int($shopId))
			return LibFc::ReturnData(false, 'shopId 参数错误！');
		
		// 校验
		$res = $this->get('sh_member',['mem_id'],sprintf(" and mem_shop_id=%d ",$shopId));
		if(!empty($res['data']))
			return LibFc::ReturnData(true, true);

		//执行
		$this->B2CDb->Begin();
		for ($i=0; $i < 4; $i++)
		{
			$temp = array(
				'mem_shop_id' => $shopId,
				'mem_mel_id' => $i+1,
				'mem_status' => 1,
				'men_manjian' => 0
			);
			$this->add('sh_member',$temp);
		}
		$this->B2CDb->End();


		return LibFc::ReturnData(true, true);
	}
	/**
	 * @method    装修模板备份 //同一个页面最多保留5个不同的版本，同一个页面的配置信息和前一个版本一样则不处理
	 * @param     [arr]        $dataArr [自定义配置]
	 * @param     [int]        $shopId  [店铺ID]
	 * @param     [str]        $view    [index 首页 item 详情页]
	 * @param     [arr]        $dehInfo [备份名称以及备注]
	 * @return   ['status'=>true,'data'=>true]
	 * @author 卢
	 * @copyright 2017-10-10
	 */
	public function addShopDesign($dataArr,$shopId,$view,$dehInfo)
	{
		if(is_array($dataArr)&&LibFc::Int($shopId)&&!empty($view)&&is_array($dehInfo))
		{
			$data=json_encode($dataArr,JSON_UNESCAPED_UNICODE);
			//查数据库条数和对比是否版本一样
			$res=$this->get('sh_design_history',['deh_id','deh_config','deh_page'],sprintf(" and deh_shop_id=%d and deh_page='%s' order by deh_atime asc",$shopId,LibFc::Escape($view)));
			//uid
			$uidData=$this->get('sh_shop',['shop_uid'],sprintf(' and shop_id=%d',$shopId),true);
			$targetArr=[
				'deh_shop_id'=>$shopId,
				'deh_uid'=>$uidData['data']['shop_uid'],
				'deh_page'=>$view,
				'deh_config'=>$data,
				'deh_atime'=>time(),
				'deh_name'=>$dehInfo['bakName'],
				'deh_remark'=>$dehInfo['bakRemark']
			];
			$this->B2CDb->Begin();
			if(count($res['data']))
			{
				//判断版本是否相同
				foreach ($res['data'] as $config) 
				{
					if($config['deh_config']==LibFc::Escape($data))
					{
						$this->B2CDb->End();
						return LibFc::ReturnData(true, true);
					}
				}
				//版本不同
				if(count($res['data'])>4)
				{
					$dehId=$res['data'][0]['deh_id'];
					$this->del('sh_design_history',sprintf(' and deh_id=%d',$dehId));
				}
			}
			$result=$this->add('sh_design_history',$targetArr,['deh_config']);
			$this->B2CDb->End();
			return $result;
		}
		return LibFc::ReturnData(false, '参数不正确');
	}
	/**
	 * @method    把提交的表单内容整理成config数组
	 * @param     [int]           $shopId  [店铺ID]
	 * @param     [str]           $view    [index 首页  item 详情页]
	 * @param     [arr]           $dataArr [表单内容]
	 * @return    [arr]                    [Array([public] => Array([top] => Array([0] => Array([module] => shopInfo[config] => Array([title] => 宜配佐佐木旗舰店[titleShow] => 1))...]
	 * @author 卢
	 * @copyright 2017-10-10
	 */
	public function editDesignConfig($shopId,$view,$dataArr,$isPrev=false)
	{
		if(LibFc::Int($shopId)&&!empty($view)&&is_array($dataArr))
		{
			//系统模快
			$sysModule=$sysModuleArr=include(mvc::$cfg['ROOT_SHOP_SYS'].'module.config.php');
			// print_r($sysModuleArr);
			//店铺页面配置
			$pageConfigAll =include(mvc::$cfg['ROOT'].'shop/'.$shopId.'/page.config.php');
			$pageConfing = $pageConfigAll[$view.'/index'];
			// print_r($pageConfing);
			//头部和底部公共模块配置
			$pageConfing['modules']['top'] = $pageConfigAll['public']['top'];
			$pageConfing['modules']['foot'] = $pageConfigAll['public']['foot'];
			$inArr=['top','fullt','left','right','fullb','foot','middle'];
			$data=[];
			//头部信息
			foreach ($pageConfing['modules']['top'] as $location => $config) 
			{
				if($config['module']=='shopInfo')
				{
					$data['public']['top'][]=$pageConfing['modules']['top'][$location];
					break;
				}
			}
			$data['tplName']=$dataArr['tplName'];
			$data[$view.'/index']['title']=$pageConfing['title'];
			$data[$view.'/index']['layout']=explode('/', $pageConfing['layout'])[0].'/'.$dataArr['type'].'.php';
			foreach ($dataArr as $location => $config) 
			{
				if(in_array($location, $inArr))
				{
					foreach ($config as $v) 
					{
						$pageConfig=json_decode($v,true);
						// print_r($pageConfig);
						switch ($location) 
						{
							case 'top':
							case 'foot':
								if($pageConfig['module']=='banner'&&$pageConfig['config']['type']=='customize'&&!$isPrev)
								{
									if(LibFc::Int($pageConfig['config']['data']['sartId'])&&$pageConfig['config']['data']['sartId']>0)
									{
										if(isset($pageConfig['config']['data']['info'])&&$pageConfig['config']['data']['info'])
										{
											$re = $this->Set('sh_article',['sart_txt'=>$pageConfig['config']['data']['info'],'sart_last_time'=>time()],sprintf(' and sart_id=%d and sart_shop_id=%d',$pageConfig['config']['data']['sartId'],$shopId),['sart_txt']);
										}
										
									}
									else
									{
										$newId = $this->Add('sh_article',['sart_shop_id'=>$shopId,'sart_name'=>'banner','sart_txt'=>$pageConfig['config']['data']['info'],'sart_add_time'=>time()],['sart_txt']);
										$pageConfig['config']['data']['sartId'] = $newId['data'];
									}
									unset($pageConfig['config']['data']['info'],$pageConfig['bannerUeditor']);
								}
								// print_r($pageConfig);
								$data['public'][$location][]=$pageConfig;
								// print_r($data['public'][$location]);
								break;							
							default:
								if($pageConfig['module']=='custom'&&isset($pageConfig['config']['articleTxt'])&&!$isPrev)
								{
									$target = array(
										'sart_txt' => $pageConfig['config']['articleTxt'],
										'sart_name' => $pageConfig['config']['title'],
										'sart_shop_id' => $shopId,
									);
									// print_r($target);
									if(LibFc::Int($pageConfig['config']['articleId'])&&((int)$pageConfig['config']['articleId'])>0)
									{
										$target['sart_last_time']=time();
										$this->set('sh_article',$target,sprintf(" and sart_id=%d ",$pageConfig['config']['articleId']),['sart_txt']);
									}
									else
									{
										$target['sart_add_time']=time();										
										$result = $this->add('sh_article',$target,['sart_txt']);
										$target['sart_id'] = $result['data'];
										$pageConfig['config']['articleId']=$result['data'];
									}
									unset($pageConfig['config']['articleTxt']);
								}
								$data[$view.'/index']['modules'][$location][]=$pageConfig;
								break;
						}
					}
				}
			}
			$data['public']['foot']=isset($data['public']['foot'])?$data['public']['foot']:[];
			return LibFc::ReturnData(true, $data);
		}
		return LibFc::ReturnData(false, '参数不正确');
	}
	/**
	 * @method    修改店铺售出配件数量
	 * @param     [int]              $shopId [店铺ID]
	 * @param     [int]              $num    [增加|减少数量]
	 * @param     boolean             $isAdd  [增加 true 减少 false]
	 * @return    [type]                      [status=>true,data=>true]
	 * @author 卢
	 * @copyright 2017-10-11
	 */
	public function updateShopSoldCount($shopId,$num,$isAdd=true)
	{
		if(LibFc::Int($shopId)&&LibFc::Int($num))
		{
			$where=sprintf(' and shop_id=%d',$shopId);
			//判断加减
			$num=$isAdd?'+'.$num:'-'.$num;
			$target['shop_sold_count']='#@shop_sold_count'.$num;
			$res=$this->set('sh_shop',$target,$where);
			return $res;
		}
		return LibFc::ReturnData(false, 'updateShopSoldCount参数不正确');
	}
	/**
	 * @method    添加部门
	 * @param     [int]        $shopId  [店铺ID]
	 * @param     [arr]        $dataArr [添加的子段数组]
	 * @return   [arr]			['status'=>true,'data'=>123]【添加成功的部门ID】
	 * @author 卢
	 * @copyright 2017-10-24
	 */
	public function addDepartment($shopId,$dataArr)
	{
		if(LibFc::Int($shopId)&&is_array($dataArr))
		{
			$targetArr=[
				'wod_shop_id'=>$shopId,
				'wod_pid'=>$dataArr['wod_pid'],
				'wod_name'=>$dataArr['wod_name']
			];
			if(isset($dataArr['wod_seq']))
			{
				$targetArr['wod_seq']=$dataArr['wod_seq'];
			}
			$data = $this->add('sh_worker_department',$targetArr);
			$B2cLog = new B2cLog();
			$temp = array(
				'log_shop_id'=>$shopId,
				'log_category'=>'0',
				'log_txt'=>"添加部门ID:{$data['data']}",
				'log_dataid'=>$data['data']
			);
			$B2cLog->addFastLog($temp);
			return LibFc::ReturnData(true, $data['data']);
		}
		return LibFc::ReturnData(false, 'addDepartment参数不正确');
	}


	/**
	 * @method   获取店铺会员等级信息
	 * @param    [int]        $shopId  [店铺ID]
	 * @return   [arr]			['status'=>true,'data'=>arr]
	 * @author   xu
	 * @copyright 2018-04-13
	 */
	public function getMemberSetting($shopId)
	{
		if(!LibFc::Int($shopId))
			return LibFc::ReturnData(false, 'getMemberSetting参数不正确');
		// 执行
		$table='sh_member left join sh_member_level on mem_mel_id=mel_id';
		$where=' and mem_shop_id='.$shopId.' order by mel_id asc';
		$temp = $this->get($table,["sh_member.*,sh_member_level.*, mem_discount as_mem_discount"],$where);
		foreach($temp['data'] as $k=>$v)
		{
			$temp['data'][$k]['as_mem_discount'] = sprintf("%.2f", $v['as_mem_discount']); 
		}
		// 返回
		return LibFc::ReturnData(true, $temp['data']);
	}

	/**
	 * @method    修改部门
	 * @param     [int]         $shopId  [店铺ID]
	 * @param     [arr]         $dataArr [需要入库的子段数组]
	 * @param     [str]         $where   [where条件]
	 * @return    [arr]                  ['status'=>true,'data'=>true]
	 * @author 卢
	 * @copyright 2017-10-24
	 */
	public function editDepartment($shopId,$dataArr,$where)
	{
		if(LibFc::Int($shopId)&&is_array($dataArr))
		{
			foreach ($dataArr as $k=> $v) 
			{
				$targetArr[$k]=$v;
			}
			$this->set('sh_worker_department',$targetArr,$where);
			return LibFc::ReturnData(true, true);
		}
		return LibFc::ReturnData(false, 'editDepartment参数不正确');
	}
	/**
	 * @method    店铺职员管理
	 * @param     [int]    $shopId   [店铺id]
	 * @param     [int]    $nowPage  [当前页]
	 * @param     [int]    $perPage  [一页数量]
	 * @param     [int]    $toTal    [总量]
	 * @author     廖
	 * @copyright 2017-10-20
	 * @return
	 */
	public function getWorker($shopId,$nowPage,$perPage,$total,$basewhere)
	{
		if(LibFc::Int($shopId) && LibFc::Int($nowPage) && LibFc::Int($perPage) && LibFc::Int($total))
		{
			$where = $basewhere.sprintf(' and wor_shop_id=%d order by wor_status desc limit %d,%d',$shopId, ($nowPage-1)*$perPage, $perPage);
			$table = 'sh_worker left join sh_worker_department on wor_wod_id=wod_id left join sh_worker_job on wor_woj_id=woj_id';
			$res = $this->Get($table,['wor_shop_id,wor_uid,wor_status,wor_wod_id,wor_atime,wor_woj_id,wor_rule_ids,wod_name,woj_name,wor_real_name,wor_name'], $where);
			if(!empty($res['data']))
			{
				$allArrUserId = array();
				$rule = '';
				foreach($res['data'] as $key=>$value)
				{
					if(LibFc::Int($value['wor_uid'])) $allArrUserId[] = $value['wor_uid'];
					if($value['wor_rule_ids'] !='')
					{
						$res['data'][$key]['rule'] = array_flip(explode(',',trim($value['wor_rule_ids'],',')));
					}
					if($value['wor_rule_ids'] !='') $rule .=','. $value['wor_rule_ids'];
				}
				//把所有的权限id拿出来一起查询
				$ruleArr = array_unique(explode(',',trim($rule,',')));
			}
			//获取名称
			if(!empty($allArrUserId))
			{
				$userArr = $this->get('us_user_base',['ub_uid','ub_username'],sprintf(' and ub_uid in (%s)',implode(',', $allArrUserId)));
				if(!empty($userArr['data']))
				{
					$user = array();
					foreach ($userArr['data'] as $key => $value) 
					{
						$user[$value['ub_uid']] = $value['ub_username'];
					}
				}
			}
			//获取详细权限名称
			if(!empty($ruleArr))
			{
				foreach ($ruleArr as $key => $value) 
				{
					if($value =='')
					{
						unset($ruleArr[$key]);
					}
				}
				if(!empty($ruleArr))
				{
					$ruleData = $this->get('sh_rule',['rule_id','rule_name'],sprintf(" and rule_id in ('%s')",implode("','", $ruleArr)));
					$rule = array_column($ruleData['data'], 'rule_name','rule_id');
				}
			}
			// print_r($res['data']);die;
			//整合数据
			if(!empty($res['data']))
			{
				// return $res['data'];die;
				foreach($res['data'] as $key=>$value)
				{
					//插入权限
					if(!empty($value['rule']))
					{
						foreach ($value['rule'] as $rk => $rv) 
						{
							$res['data'][$key]['rule'][$rk] = $rule[$rk];
						}
					}
					//插入名字
					$res['data'][$key]['workerName'] = $user[$value['wor_uid']];
				}
			}
			return $res['data'];
		}
	}



	/**
	 * @method    获取店铺近30天的成交金额
	 * @param     [arr]    $shopIds   [店铺id]
	 * @param     [int]    $time   [时限]
	 * @author     xu
	 * @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 ?sprintf(" and ord_completed_time > %d ",$time) : "";

		// 获取time时间段内completed的订单金额总额度
		$where = sprintf(" and ord_shop_id in (%s) and ord_status='completed' ".$timeWhere,implode(',', $shopIds));
		$res = $this->get("or_order",['ord_pay_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];
			$realSalMoney[$v] = $ordSum[$v];
		}

		// 如果订单都是空的那么退款金额必然为空
		if(empty($orderIdArray)) return LibFc::ReturnData(true,$realSalMoney);

		// 获取每个店铺对应的退款金额
		$res = $this->get("or_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    获取店铺的在售商品数量
	 * @param     [arr]    $shopIds   [店铺id]
	 * @author     xu
	 * @copyright 2018-04-08
	 * @return
	 */
	public function getShopProNums($shopIds,$limitSelling=0)
	{
		// 校验店铺ID
		if(empty($shopIds) || !is_array($shopIds) || empty($shopIds = array_filter($shopIds,'LibFc::Int')))
			return LibFc::ReturnData(false,'参数错误！');
		$B2cBase = new B2cBase();
		$where = sprintf("and pro_shop_id in (%s)",implode(',',$shopIds));
		if($limitSelling) $where .= " and pro_status=1";
		$res = $B2cBase->get('bc_product',['count(*) nums','pro_shop_id'],$where.' group by pro_shop_id');
		$data = array_column($res['data'], 'nums' ,'pro_shop_id');
		// 返回
		return LibFc::ReturnData(true,$data);
	}

	/**
	  * @method 设置店铺的收款人信息及微信绑定
	  * @param  $shopId  int  店铺ID
	  * @param  $accbArr  array  [11=>['acb_name'=>'', 'acb_idcard'=>'', ['accs']=>[1,2,3..]....]....]
	  * @author soul
	  * @copyright 2017/6/5
	  * @return 
	  * 成功 ["status"=>true, "data"=>true ]
	  * 失败 ["status"=>false, "data"=>失败原因 ]
	  */
	public function setMoneyAccountBind($shopId, $accbArr)
	{
		$shopId = (int) $shopId;
		if($shopId < 1 || !is_array($accbArr))
		{
			return LibFc::ReturnData(false, 'setMoneyAccountBind 提供的参数不正确');
		}

		$res = $this->getFieldUniVal('sh_account_bind', 'acb_id', sprintf(" and acb_shop_id=%d", $shopId));
		$oldAcbArr = $res['data'];

		$res = $this->get('sh_account', ['acc_id', 'acc_acb_id'], sprintf(" and acc_shop_id=%d", $shopId));
		$accArr = [];
		foreach($res['data'] as $v)
		{
			$accArr[$v['acc_acb_id']][] = $v['acc_id'];
		}
		
		//检测数据
		foreach($accbArr as $k=>$v)
		{
			if(!LibFc::Int($k))
			{
				unset($accbArr[$k]);
				continue;
			}
			if($k > 0 && !in_array($k, $oldAcbArr))
			{
				unset($accbArr[$k]);
				continue;
			}
			else if($k < 0 && (strlen($v['acb_name']) < 2 || !preg_match('/^\d{17}[\d|x]|\d{15}$/', $v['acb_idcard'])))
			{
				unset($accbArr[$k]);
				continue;
			}
			$accbArr[$k] = $v;
		}
		
		$this->B2CDb->Begin();

		$delAcbArr = array_diff($oldAcbArr, array_keys($accbArr));
		if(!empty($delAcbArr))
		{
			$this->del('sh_account_bind', sprintf(" and acb_shop_id=%d and acb_id in (%s)", $shopId, implode(',', $delAcbArr)));
			$this->del('sh_account', sprintf(" and acc_shop_id=%d and acc_acb_id in (%s)", $shopId, implode(',', $delAcbArr)));
		}
		
		foreach($accbArr as $k=>$v)
		{
			if($k > 0)
			{
				//绑定的微信号 只删除，不增加编辑
				if(isset($v['accs']))
				{
					foreach($v['accs'] as $kk=>$vv)
					{
						$v['accs'][$kk] = (int) $vv;
					}
				}
				else
				{
					$v['accs'] = [];
				}
				if(isset($accArr[$k]))
				{
					$delAcArr = array_diff($accArr[$k], $v['accs']);
					if(!empty($delAcArr))
					{
						$this->del('sh_account', sprintf(" and acc_shop_id=%d and acc_acb_id=%d and acc_id in (%s)", $shopId, $k, implode(',', $delAcArr)));
					}
				}
			}
			else
			{
				unset($v['accs']);
				$v['acb_atime'] = time();
				$v['acb_shop_id'] = $shopId;
				$res = $this->add('sh_account_bind', $v);
				$v['acb_id'] = $res['data'];
			}
		}
		$this->B2CDb->End();
		return LibFc::ReturnData(true, true);
	}



	/**
	  * @method 添加微信提现账号
	  * @param  $dataArr  array  ['acc_shop_id'=>''...]
	  * @author soul
	  * @copyright 2017/6/5
	  * @return 
	  * 成功 ["status"=>true, "data"=>true ]
	  * 失败 ["status"=>false, "data"=>失败原因 ]
	  */
	public function addTiXianAccount($dataArr)
	{
		if(!isset($dataArr['acc_type']) || empty($dataArr['acc_shop_id']) || empty($dataArr['acc_acb_id']))
		{
			return LibFc::ReturnData(false, 'addTiXianAccount 提供的参数不正确');
		}
		$dataArr['acc_shop_id'] = (int) $dataArr['acc_shop_id'];
		$dataArr['acc_acb_id'] = (int) $dataArr['acc_acb_id'];
		
		//校验收款人姓名 身份证
		$res = $this->get('sh_account_bind', ['acb_id'], sprintf(" and acb_shop_id=%d and acb_id=%d", $dataArr['acc_shop_id'], $dataArr['acc_acb_id']), true);
		if(empty($res['data']))return LibFc::ReturnData(false, 'addTiXianAccount 提供的acc_acb_id参数不正确！');
		$error = true;
		switch($dataArr['acc_type'])
		{
			case 0:
				if(empty($dataArr['acc_weixin_unionid']) || empty($dataArr['acc_weixin']) || empty($dataArr['acc_weixin_oppenid']))
					return LibFc::ReturnData(false, '提供的微信账号参数不正确！');
				$res = $this->get('sh_account', ['acc_id'], sprintf(" and acc_shop_id=%d and acc_weixin_unionid='%s'", $dataArr['acc_shop_id'], LibFc::Escape($dataArr['acc_weixin_unionid'])), true);
				if(!empty($res['data'])) return LibFc::ReturnData(false, '该微信收款账号已绑定，请勿重复绑定！');
				$error = false;
			break;
			case 1:
				if(!filter_var($dataArr['acc_alipay_account'], FILTER_VALIDATE_EMAIL) && !preg_match('/^1\d{10}$/', $dataArr['acc_alipay_account']))
					return LibFc::ReturnData(false, '提供的支付宝账号格式不正确！');
					
				$res = $this->get('sh_account', ['acc_id'], sprintf(" and acc_shop_id=%d and acc_alipay_account='%s'", $dataArr['acc_shop_id'], LibFc::Escape($dataArr['acc_alipay_account'])), true);
				if(!empty($res['data'])) return LibFc::ReturnData(false, '该支付宝收款账号已绑定，请勿重复绑定！');
				$error = false;
			break;
			case 2:
				if(empty($dataArr['acc_bank_name']) || empty($dataArr['acc_bank_open']))
					return LibFc::ReturnData(false, '开户银行名称、所属开户支行必填！');

				if(!preg_match('/^\d{8,30}$/', $dataArr['acc_bank_card']))
					return LibFc::ReturnData(false, '提供的银行卡卡号格式不正确！');
					
				$res = $this->get('sh_account', ['acc_id'], sprintf(" and acc_shop_id=%d and acc_bank_card='%s'", $dataArr['acc_shop_id'], LibFc::Escape($dataArr['acc_bank_card'])), true);
				if(!empty($res['data'])) return LibFc::ReturnData(false, '该银行卡已绑定，请勿重复绑定！');
				$error = false;
			break;
		}
		if($error) return LibFc::ReturnData(false, 'addTiXianAccount 绑定失败');
		$dataArr['acc_atime'] = time();
		return $this->add('sh_account', $dataArr);
	}
	

	/**
	  * @method 开通店铺
	  * @param  $data 新开张店铺相关信息
	  * @param  $userId 用户ID
	  * @author xu
	  * @copyright 2018/02/21
	  * @return 
	  * 成功 ["status"=>true, "data"=>true ]
	  * 失败 ["status"=>false, "data"=>失败原因 ]
	  */
	public function createNewShop($data,$userId)
	{
		// 校验参数
		if(empty($data) || !LibFc::Int($userId)) 
			return LibFc::ReturnData(false, '参数错误！');
		// 校验用户ID是否存在
		$LibYpApi = new LibYpApi();
		$res = $LibYpApi->Get('user/getUserByIds', [], ['uids'=>$userId]);
		if(empty(current($res['data']))) return LibFc::ReturnData(false, '该用户不存在于宜配网中！');
		// 用户信息
		$user = current($res['data']);
		// 检测b2c数据库
		$B2cBase = new B2cBase();
		$res = $B2cBase->get('us_user_base',['ub_uid'],sprintf(" and ub_uid=%d ",$userId),true);
		if(empty($res['data'])) return LibFc::ReturnData(false, '该用户不存在跑街的中！'); 
		// 是否开通店铺
		$res = $B2cBase->get('sh_shop',['shop_uid'],sprintf(" and shop_uid=%d ",$userId),true);
		if(!empty($res['data'])) return LibFc::ReturnData(false, '该用户已开通店铺！');
		// 去除子账户		
		$res = $B2cBase->get('sh_worker',['wor_uid'],sprintf(" and wor_uid = %d ",$userId),true);
		if(!empty($res['data'])) return LibFc::ReturnData(false,'该用户是某店铺的子账户，开通失败！');
		// 拼接入库
		if(!empty($data['shopLogo']))
		{ 
			$res=json_decode($data['shopLogo'],true);
			$logo=$res['sfile'];
		}
		if(!empty($data['shopLicense']))
		{
			$res = json_decode($data['shopLicense'] ,true);
			$shopLicense = $licenseArr['name'].'.'.$res['ext'];
		}
		$shopName = empty($data['shopName']) ? $user['shopName'] : $data['shopName'];
		$province = (!empty($data['province']) && LibFc::Int($data['province'])) ? $data['province'] : $user['ui_province'];
		$city = (!empty($data['city']) && LibFc::Int($data['city'])) ? $data['city'] : $user['ui_city'];
		$region = (!empty($data['region']) && LibFc::Int($data['region'])) ? ','.$data['region'] : '';
		$street = (!empty($data['street']) && LibFc::Int($data['street'])) ? ','.$data['street'] : ''; 
		$ui_address = empty($data['shopAddress']) ? $user['ui_address'] : $data['shopAddress'];

		// 新增sh_shop数据
		$this->B2CDb->Begin();
		$shopId = $userId;
		$data = array(
			'shop_id'=>$shopId,
			'shop_uid'=>$userId,
			'shop_status'=>1,
			'shop_reg_time'=>time(),
			'shop_baoyou'=>-1,
			'shop_name'=>!empty($data['shopName']) ? $data['shopName']:$user['u_name'],
			'shop_domain'=>mvc::$cfg['HOST']['b2c'].'shop'.$shopId.'/',
			'shop_pct_ids'=>$province.','.$city.$region.$street,
			'shop_address'=>$ui_address,
			'shop_logo'=>empty($logo)?'':$logo,
			'shop_license'=>empty($shopLicense)?'':$shopLicense
		);
		$B2cBase->add('sh_shop',$data);

		//修改会员系统的店铺ID
		$LibYpApi = new LibYpApi();
		$LibYpApi->Get('user/setUser', [], ['uid'=>$userId, 'data'=>['u_b2c_shopid'=>$shopId]]);
		//调用日志
		$B2cLog = new B2cLog();
		$temp = array(
			'log_shop_id'=>$shopId,
			'log_category'=>'21',
			'log_txt'=>'开通店铺',
			'log_dataid'=>$shopId
		);
		$B2cLog->addFastLog($temp);

		// 店铺会员
		$this->autoAddmemberLevel($shopId);

		// 生成店铺配置文件
		LibDir::copydir(mvc::$cfg['ROOT_SHOPS'].'demo',mvc::$cfg['ROOT_SHOPS'].''.$shopId);
		$res = file_get_contents(mvc::$cfg['ROOT_SHOPS'].$shopId.'/shop.config.php');
		file_put_contents(mvc::$cfg['ROOT_SHOPS'].$shopId.'/shop.config.php',str_replace('#SHOPID#',$shopId,$res));
		//开通跑街令店铺
		//$this->openPjlShop($shopId);
		$this->B2CDb->End();
		return LibFc::ReturnData(true, true);
	}
	/**
	 * @method    开店申请入库
	 * @param     [arr]        $dataArr [开店申请字段]
	 * @param     [Int]        $userId  [用户ID]
	 * @return    [arr]                 [['status'=>true,'status'=>shopid]]
	 * @author 卢
	 * @copyright 2018-04-04
	 */
	function openShopApply($dataArr,$userId,$add=true)
	{
		if(is_array($dataArr)&&count($dataArr))
		{
			$target=[];
			if(!empty($dataArr['service']))
				$target['shop_apply_sers'] = implode(',', $dataArr['service']);
			
			if(!empty($dataArr['shopLogo']))
			{
				$target['shop_logo']=$dataArr['shopLogo'];
			}
			else
			{
				return LibFc::ReturnData(false, '店铺Logo不能为空');
			}
			if(empty($dataArr['shopName'])||mb_strlen($dataArr['shopName'],'utf8')>64)
			{
				return LibFc::ReturnData(false, '店铺名称不正确');
			}
			else
			{
				$target['shop_name']=$dataArr['shopName'];
			}
			if(empty($dataArr['comName']))
			{
				//return LibFc::ReturnData(false, '企业名称不正确');
			}
			else
			{
				$target['shop_com_name']=$dataArr['comName'];
			}
			if(empty($dataArr['shopMainName']))
			{
				return LibFc::ReturnData(false, '负责人名称不正确');
			}
			else
			{
				$target['shop_main_name']=$dataArr['shopMainName'];
			}
			if(empty($dataArr['shopMainTel']))
			{
				return LibFc::ReturnData(false, '负责人电话不正确');
			}
			else
			{
				$target['shop_main_tel']=$dataArr['shopMainTel'];
			}
			$cardImgs=array_filter($dataArr['cardMainImgs']);
			if(empty($dataArr['cardMainImgs'])||count($cardImgs)<=1)
			{
				//return LibFc::ReturnData(false, '负责人身份证不能为空');
			}
			else
			{
				$target['shop_main_idcard']=implode(',',$dataArr['cardMainImgs']);
			}
			if(empty($dataArr['licenceImg']))
			{
				//return LibFc::ReturnData(false, '营业执照不能为空');
			}
			else
			{
				$target['shop_license']=$dataArr['licenceImg'];
			}
			$province=array_filter($dataArr['province']);
			if(count($province))
			{
				$target['shop_pct_ids']=implode(',',$province);
			}
			else
			{
				return LibFc::ReturnData(false, '所在地区不能为空');
			}
			if(empty($dataArr['address']))
			{
				return LibFc::ReturnData(false, '详细地址不能为空');
			}
			else
			{
				$target['shop_address']=$dataArr['address'];
			}
			if(!LibFc::RegularValida($dataArr['societyCode'],'societyCode'))
			{
				//return LibFc::ReturnData(false, '统一社会信用代码/注册号不正确');
			}
			else{
				$target['shop_com_code']=$dataArr['societyCode'];
			}
			if(empty($dataArr['shopCorName']))
			{
				//return LibFc::ReturnData(false, '法人姓名不能为空');
			}
			else
			{
				$target['shop_cor_name']=$dataArr['shopCorName'];
			}
			if(empty($dataArr['shopCorTel']))
			{
				//return LibFc::ReturnData(false, '法人电话不能为空');
			}
			else
			{
				$target['shop_cor_tel']=$dataArr['shopCorTel'];
			}
			$cardImgs=array_filter($dataArr['cardImgs']);
			if(empty($dataArr['cardImgs'])||count($cardImgs)<=1)
			{
				//return LibFc::ReturnData(false, '身份证不能为空');
			}
			else
			{
				$target['shop_idcard']=implode(',',$dataArr['cardImgs']);
			}
			// //校验唯一性
			$res=$this->get('sh_shop',['shop_name','shop_com_code','shop_com_name'],sprintf(" and (shop_name='%s' or shop_com_code='%s' or shop_com_name='%s') and shop_uid!=%d",$target['shop_name'],$target['shop_com_code'],$target['shop_com_name'],$userId));
			if($res['data'])
			{
				foreach ($res['data'] as $v) 
				{
					if($v['shop_name']==$target['shop_name']) return LibFc::ReturnData(false, '店铺名称已被使用');
				}
			}
			if($add)
			{
				$res=$this->get('sh_shop',['count(1) count'],sprintf(' and shop_uid=%d',$userId),true);
				if($res['data']['count'])
					return LibFc::ReturnData(false, '店铺已经开通，无需再次申请！');
			}
			$target['shop_id']=$userId;
			$target['shop_uid']=$userId;
			$target['shop_status']=-2;
			$target['shop_apply_tatus']=0;
			$target['shop_apply_atime']=time();
			// die;
			if($add)
			{
				$this->add('sh_shop',$target);
			}
			else
			{
				$this->set('sh_shop',$target,sprintf(' and shop_uid=%d',$userId));
			}
			return LibFc::ReturnData(true, $target['shop_id']);
		}
		return LibFc::ReturnData(false, 'openShopApply 提供的参数不正确');
	}
	/**
	 * @method    修改申请状态
	 * @param     [arr]         $dataArr [description]
	 * @param     [int]         $shopId  [店铺ID/用户ID]
	 * @param     [int]         $status  [状态]
	 * @author 卢
	 * @copyright 2018-04-04
	 */
	function setApplyStatus($dataArr,$shopId,$status)
	{
		if(is_array($dataArr)&&count($dataArr)&&LibFc::Int($shopId)&&in_array($status, [-1,0,1,2]))
		{
			$this->B2CDb->Begin();
			switch ($status) 
			{
				case '2':
					$dataArr['shop_status']=1;
					$dataArr['shop_reg_time']=time();
					$dataArr['shop_domain']=mvc::$cfg['HOST']['b2c'].'shop'.$shopId.'/';
					//开通跑街令配件商
					//$this->openPjlShop($shopId);
					$this->set('sh_shop',$dataArr,sprintf(' and shop_id=%d',$shopId));
					//修改会员系统的店铺ID
			        $LibYpApi = new LibYpApi();
			        $LibYpApi->Get('user/setUser', [], ['uid'=>$shopId, 'data'=>['u_b2c_shopid'=>$shopId]]);
			        //调用日志
			        $B2cLog = new B2cLog();
			        $temp = array(
			            'log_shop_id'=>$shopId,
			            'log_category'=>'21',
			            'log_txt'=>'开通店铺',
			            'log_dataid'=>$shopId
			        );
			        $B2cLog->addFastLog($temp);
			        $this->autoAddmemberLevel($shopId);
			         // 生成店铺配置文件
			        LibDir::copydir(mvc::$cfg['ROOT_SHOPS'].'demo',mvc::$cfg['ROOT_SHOPS'].$shopId);
			        $res = file_get_contents(mvc::$cfg['ROOT_SHOPS'].$shopId.'/shop.config.php');
			        file_put_contents(mvc::$cfg['ROOT_SHOPS'].$shopId.'/shop.config.php',str_replace('#SHOPID#',$shopId,$res));

					break;				
				default:
					$this->set('sh_shop',$dataArr,sprintf(' and shop_id=%d',$shopId));
					break;
			}
			$this->B2CDb->End();
			return LibFc::ReturnData(true, true);
		}
		return LibFc::ReturnData(false, 'setApplyStatus 提供的参数不正确');
	}
	/**
	 * @method    删除店铺售后模板
	 * @param     [int]          $pdtId  [模板ID]
	 * @param     [int]          $shopId [店铺ID]
	 * @return    [arr]                  [status=>true,'data'=>true]
	 * @author 卢
	 * @copyright 2018-04-18
	 */
	function deleteCustomTpl($pdtId,$shopId)
	{
		if(LibFc::Int($pdtId)&&LibFc::Int($shopId))
		{
			$res=$this->get('bc_product_desc_tpl',['count(1) count'],sprintf(' and pdt_id=%d and pdt_shop_id=%d and pdt_type=1',$pdtId,$shopId),
				true);
			if(empty($res['data']['count']))
				return LibFc::ReturnData(false, '模板不属于该店铺');
			$this->B2CDb->Begin();
			$this->del('bc_product_desc_tpl',sprintf(' and pdt_id=%d and pdt_shop_id=%d and pdt_type=1',$pdtId,$shopId));
			$this->set('bc_product_info',['pri_service_pdt_id'=>0],sprintf(' and pri_service_pdt_id=%d',$pdtId));
			$this->B2CDb->End();
			return LibFc::ReturnData(true, true);
		}
		return LibFc::ReturnData(false, 'deleteCustomTpl 提供的参数不正确');
	}

	/**
	 * @method    保存店铺公众号的基本信息
	 * @param     [array]          	$dataArr [post 过来的数组]
	 * @param     [int]          	$shopId  [店铺id]
	 * @return    [array]                  	 [status=>true,'data'=>true]
	 * @author     廖
	 * @copyright 2018-07-11
	 */
	public function saveGzhBaseInfo($dataArr,$shopId)
	{
		if(LibFc::Int($shopId) && !empty($dataArr))
		{
			if (empty(LibFc::Escape($dataArr['aps_shop_name'])))
			{
				return LibFc::ReturnData(false, '店铺名称不能为空!!');
			}

			$dataArr['aps_shop_name'] = LibFc::Escape($dataArr['aps_shop_name']);

			//检查名称是否唯一
			$res = $this->get('sh_shop_app',['count(*) count'],sprintf(" and aps_shop_name = '%s' and aps_shop_id != %s",$dataArr['aps_shop_name'],$shopId),true);

			if($res['data']['count'] > 0)
			{
				return LibFc::ReturnData(false, '店铺名称已被使用!!');
			}

			$upData = [];
			$upData['aps_shop_name'] = $dataArr['aps_shop_name'];
			// if(isset($dataArr['aps_sales']))$upData['aps_sales'] = $dataArr['aps_sales'];
			if(isset($dataArr['aps_au_uid'])) $upData['aps_au_uid'] = $dataArr['aps_au_uid']?:0;
			//正则规则
			$maEmail = '/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/';
			$maQQ = '/^\d{4,16}$/';
			$maPhone = '/^1\d{10}$/';
			$maTel = '/^([0-9]{3,4}-)?[0-9]{7,8}$/';
			$maEnNum = '/[a-zA-Z][-_a-zA-Z0-9]{5,19}/';
			$maUrl = '/^((https|http|ftp|rtsp|mms):\/\/)?[^\s]+/';
			//banner 链接
			$banner = [];
			if (isset($dataArr['aps_banner']['imgs']))
			{
				//链接不为空才入库
				foreach ($dataArr['aps_banner']['imgs'] as $key => $value) 
				{
					if (!empty($value))
					{
						$url = trim($dataArr['aps_banner']['imgs_url'][$key]);
						//正则校验 URL 地址
						if (!empty($url) && !preg_match($maUrl,$url))
						{
							return LibFc::ReturnData(false, '提供的链接不正确!!');
						}
						$banner[$key]['url'] = $url;
						//banner 名称
						$banner[$key]['name'] = $dataArr['aps_banner']['imgs_name'][$key];
						//banner img地址
						$banner[$key]['img'] = $value;
					}
				}
			}
			$upData['aps_banner'] = json_encode($banner);
			//时间
			if (isset($dataArr['aps_btime'])) $upData['aps_btime'] = strtotime(LibFc::Escape($dataArr['aps_btime']));
			if (isset($dataArr['aps_etime'])) $upData['aps_etime'] = strtotime(LibFc::Escape($dataArr['aps_etime']));
			//备注
			if (isset($dataArr['aps_remark']))
			{
				$upData['aps_remark'] = $dataArr['aps_remark'];
			}
			//信息
			if (isset($dataArr['aps_info']))
				$upData['aps_info'] = $dataArr['aps_info'];
			if(isset($dataArr['aps_model'])) $upData['aps_model'] = $dataArr['aps_model'];
			//电话 微信 qq
			$contact = [];
			$conArr = ['phones'=>'电话','qqs'=>'QQ','wechats'=>'微信','tels'=>'座机','addrs'=>'地址'];
			foreach ($conArr as $k => $v)
			{
				//校验信息组
				if (!empty($dataArr['aps_contact'][$k][$k.'_name']) && (count($dataArr['aps_contact'][$k][$k.'_name']) > 5 || count($dataArr['aps_contact'][$k][$k.'_num']) > 5))
				{
					return LibFc::ReturnData(false, $v.'组太多!!');
				}
				//判断信息格式
				if (isset($dataArr['aps_contact'][$k][$k.'_num']))
				{
					foreach ($dataArr['aps_contact'][$k][$k.'_num'] as $key => $value) 
					{
						//不为空才保存
						$name = !empty($dataArr['aps_contact'][$k][$k.'_name'][$key])?$dataArr['aps_contact'][$k][$k.'_name'][$key]:'';
						if (!empty($value))
						{
							$value = trim($value);
							//正则
							$check = false;
							switch ($k) 
							{
								case 'phones':
									if (!preg_match($maPhone, $value) && !preg_match($maTel, $value))
									{
										$check = true;
									}
									break;
								case 'qqs':
									if (!preg_match($maQQ, $value))
									{
										$check = true;
									}
									break;
								case 'wechats':
									//邮箱 手机 QQ 英文+数字
									if (!preg_match($maEmail, $value) && !preg_match($maPhone, $value) && !preg_match($maQQ, $value) && !preg_match($maEnNum, $value))
									{
										$check = true;
									}
									break;
							}
							if ($check)
							{
								return LibFc::ReturnData(false, '提供的'.$v.'不正确!!');
							}
							//保存一组电话号码
							$contact[$k][] = [
								'name' => $name,
								'val' => $value
							];
						}
					}
				}
			}
			$upData['aps_contact'] = json_encode($contact);
			
			$this->B2CDb->Begin();

			//状态
			if (isset($dataArr['aps_status']))
			{
				$upData['aps_status']  = $dataArr['aps_status'] ? 1 : 0;
				
			}
            $isAdd = $this->get('sh_shop_app',['count(*) as count'],'and aps_shop_id='.$shopId,true);
			if($isAdd['data']['count'] > 0)
            {
                $res = $this->set('sh_shop_app',$upData,'and aps_shop_id='.$shopId);
            }
			else
			{
                $upData['aps_shop_id'] = $shopId;
                $res = $this->add('sh_shop_app',$upData);
			}
			//日志
			$B2cLog = new B2cLog();
			$item = [
				'log_shop_id'=>$shopId,
				'log_category'=>'21',
				'log_txt'=>'设置商城版目录信息',
				'log_dataid'=>$shopId
			];
			$B2cLog->addFastLog($item);			
			$this->updatePjlShopStatus($shopId);

			
			$this->B2CDb->End();
			return LibFc::ReturnData($res);
		}
		return LibFc::ReturnData(false, 'saveGzhBaseInfo 提供的参数不正确');
	}

	/**
	 * @method    联动版公众号赠送跑街令入驻
	 * @param     [int]       $shopId       [店铺id]
	 * @author    soul
	 * @copyright 2021/6/19
	 */
	public function updatePjlShopStatus($shopId)
	{
		$shopId = (int) $shopId;
		$res = $this->get('sh_shop_app join sh_shop on shop_id = aps_shop_id', ['*'], sprintf(" and shop_id=%d", $shopId), true);
		if(!empty($res['data']))
		{
			$b2cArr = $res['data'];

			$PjlProduct = new PjlProduct();
			
			$this->B2CDb->Begin();

			if($b2cArr['aps_status'] == 1)
			{
				$res = $PjlProduct->get('pl_shop', ['shop_id'], sprintf(" and shop_id=%d", $shopId), true);
				if(empty($res['data']))
				{
					$dataArr=[
						'shop_b2c_shop_id'=>$b2cArr['shop_id'],
						'shop_pu_id'=>$b2cArr['shop_uid'],
						'shop_name'=>$b2cArr['aps_shop_name'],
						'shop_pct_ids'=>$b2cArr['shop_pct_ids'],
						'shop_addr'=>$b2cArr['shop_address'],
						'realname'=>$b2cArr['shop_main_name'],
					];
					$LibYpApi = new LibYpApi();
					$LibYpApi->Get('pjl/openPjlShop', [], $dataArr,true);
					$PjlProduct->initShopAddr($dataArr['shop_b2c_shop_id']);
				}
			}

			//微商城尚未到期
			$res = $PjlProduct->get('pl_shop_vip', ['*'], sprintf(" and svip_shop_id=%d order by svip_etime desc limit 1", $shopId), true);
			$hasPjlShopTime = $res['data'];
			
			//PC版
			$res = $PjlProduct->get('pl_user_vip', ['*'], sprintf(" and uvip_uid=%d order by uvip_etime desc limit 1", $shopId), true);
			$hasPjlPcTime = $res['data'];

			$now = time();
			if($b2cArr['aps_etime'] > $now)
			{
				//微商城到期时间大于跑街商铺到期时间
				if(empty($hasPjlShopTime['svip_etime']) || $b2cArr['aps_etime'] > $hasPjlShopTime['svip_etime'])
				{
					$addArr = [
						'svip_shop_id'=>$shopId,	
						'svip_btime'=>$hasPjlShopTime['svip_etime'] < $now? $now: $hasPjlShopTime['svip_etime'],	
						'svip_etime'=>$b2cArr['aps_etime'],	
						'svip_style'=>2	
					];
					$PjlProduct->add('pl_shop_vip', $addArr);
				}
				else if(!empty($hasPjlShopTime['svip_etime']) && $hasPjlShopTime['svip_etime'] > $now && $hasPjlShopTime['svip_style'] == 2)
				{
					//微商城到期时间小于跑街商铺到期时间，如果是赠送的，缩减时间
					$PjlProduct->set('pl_shop_vip', ['svip_etime'=>$b2cArr['aps_etime']], sprintf(" and svip_id=%d and svip_shop_id=%d and svip_style =2", $hasPjlShopTime['svip_id'], $shopId));
				}

				//微商城到期时间大于跑街PC到期时间
				if(empty($hasPjlPcTime['uvip_etime']) || $b2cArr['aps_etime'] > $hasPjlPcTime['uvip_etime'])
				{
					$res = $PjlProduct->get('pl_vip_level', ['*'], ' and vip_id=4 limit 1', true);
					$freeArr = $res['data'];
					$addArr = [
						'uvip_uid'=>$b2cArr['shop_uid'],
						'uip_uvl_id'=>0,
						'uvip_btime'=>$hasPjlPcTime['uvip_etime'] < $now? $now: $hasPjlPcTime['uvip_etime'],
						'uvip_etime'=>$b2cArr['aps_etime'],	
						'uvip_vip_id'=>$freeArr['vip_id'],
						'uvip_name'=>$freeArr['vip_name'],
						'uvip_vin_count'=>$freeArr['vip_vin_count'],
						'uvip_number_count'=>$freeArr['vip_number_count'],
						'uvip_etk_count'=>$freeArr['vip_etk_count'],
						'uvip_cyj_count'=>$freeArr['vip_cyj_count'],
						'uvip_atime'=>time(),
						'uvip_paymoney'=>'0.00'
					];
					if($addArr['uvip_etime'] > $addArr['uvip_btime']) $PjlProduct->add('pl_user_vip', $addArr);
				}
				else if(!empty($hasPjlPcTime['uvip_etime']) && $hasPjlPcTime['uvip_etime'] > $now && $hasPjlPcTime['uip_uvl_id'] == 0)
				{
					//微商城到期时间小于跑街商铺到期时间，如果是赠送的，缩减时间
					$PjlProduct->set('pl_user_vip', ['uvip_etime'=>$b2cArr['aps_etime']], sprintf(" and uvip_id=%d and uvip_uid=%d and uip_uvl_id =0 and uvip_vip_id=4", $hasPjlPcTime['uvip_id'], $shopId));
				}
				$PjlProduct->set('pl_shop', ['shop_status'=>2], sprintf(" and shop_id=%d", $shopId));
			}
			else
			{
				//微商城已到期，如果最后一条记录是赠送的，取消赠送部分时间
				if(!empty($hasPjlShopTime['svip_etime']) && $hasPjlShopTime['svip_etime'] > $now && $hasPjlShopTime['svip_style'] == 2)
				{
					//微商城到期时间小于跑街商铺到期时间，如果是赠送的，缩减时间
					$PjlProduct->set('pl_shop_vip', ['svip_etime'=>$b2cArr['aps_etime']], sprintf(" and svip_id=%d and svip_shop_id=%d and svip_style =2", $hasPjlShopTime['svip_id'], $shopId));
				}

				if(!empty($hasPjlPcTime['uvip_etime']) && $hasPjlPcTime['uvip_etime'] > $now && $hasPjlPcTime['uip_uvl_id'] == 0)
				{
					$PjlProduct->set('pl_user_vip', ['uvip_etime'=>$hasPjlPcTime['uvip_etime']], sprintf(" and uvip_id=%d and uvip_uid=%d and uip_uvl_id =0 and uvip_vip_id=4", $hasPjlPcTime['uvip_id'], $shopId));
				}
			}

			//更新主表的到期时间
			$res = $PjlProduct->get('pl_shop_vip', ['svip_etime'], sprintf(" and svip_shop_id=%d order by svip_etime desc limit 1", $shopId), true);
			$PjlProduct->set('pl_shop', ['shop_vip_etime'=>$res['data']['svip_etime']], sprintf(" and shop_id=%d", $shopId));

			$this->B2CDb->End();
		}
		return LibFc::ReturnData(true);
	}


	/**
	 * @method    保存店铺上传附件
	 * @param     [array]         $dataArr [description]
	 * @param     [int]           $shopId  [description]
	 * @author    liao
	 * @copyright 2018-09-04
	 * @return    [array]                   ['status'=>true,'data'=>xxx]
	 */
	public function saveShopFujian($dataArr,$shopId)
	{
		if(is_array($dataArr) && !empty($dataArr) && LibFc::Int($shopId))
		{
			$this->B2CDb->Begin();
			foreach ($dataArr as $key => $value) 
			{
				if (!LibFc::Int($key))
					return LibFc::ReturnData(false,'saveShopFujian 参数不正确');
				$item = [
					'shf_name' => $value['shf_name'],
					'shf_iscon' => $value['shf_iscon'],
					'shf_seq' => $value['shf_seq'],
				];
				$where = sprintf('and shf_id=%d and shf_shop_id=%d',$key, $shopId);
				$this->set('sh_shop_file', $item, $where);
			}
			$this->B2CDb->End();
			return LibFc::ReturnData(true,true);
		}
		return LibFc::ReturnData(false,'saveShopFujian 参数不正确');
	}
	/**
	 * @method    2020/3/7 入驻商城的商家自动入驻跑街令商家的功能今天开始取消   开通跑街令配件商
	 * @param     [int]      $uid [用户ID|店铺ID]
	 * @return    [type]           []
	 * @author lu
	 * @copyright 2018-11-05
	 */
	public function openPjlShop($uid)
	{
		return LibFc::ReturnData(true,true);
		if(!empty($uid))
		{
			$res=$this->get('sh_shop',['shop_id','shop_status','shop_name','shop_pct_ids','shop_address','shop_main_name'],sprintf(' and shop_uid=%d',$uid),true);

			if(empty($res['data']))
			{
				return LibFc::ReturnData(true,'店铺不存在');
			}
			if($res['data']['shop_status']!=-2)
			{
				return LibFc::ReturnData(true,'店铺已开通');
			}

			$dataArr=[
				'shop_b2c_shop_id'=>$res['data']['shop_id'],
				'shop_pu_id'=>$uid,
				'shop_name'=>$res['data']['shop_name'],
				'shop_pct_ids'=>$res['data']['shop_pct_ids'],
				'shop_addr'=>$res['data']['shop_address'],
				'realname'=>$res['data']['shop_main_name'],
			];

			$LibYpApi = new LibYpApi();
			$LibYpApi->Get('pjl/openPjlShop', [], $dataArr,true);
			$PjlProduct = new PjlProduct();
			$PjlProduct->initShopAddr($dataArr['shop_b2c_shop_id']);
			return LibFc::ReturnData(true,true);
		}
		return LibFc::ReturnData(false,'openPjlShop 参数不正确');
	}


	/**
	  * @method 目录配置
	  * @param  $sup_id 目录ID
	  * @param  $dataArr ['ssu_name'=>....]
	  * @param  $partArr 开通的分类 [1,2,...]
	  * @author soul
	  * @copyright 2019/7/12
	  * @return ["status"=> bool(true), "data"=> true, "code"=>""]
	  */
	public function setShopSuper($sup_id, $dataArr, $partArr = null)
	{
		$sup_id = (int) $sup_id;
		if(!empty($sup_id))
		{
			$res = $this->get('sh_super', ['*'], sprintf(" and ssu_id=%d", $sup_id), true);
			if(empty($res['data'])) return LibFc::ReturnData(false,'品牌目录ID不存在');
			$oldArr = $res['data'];
			if(empty($dataArr['ssu_style'])) $dataArr['ssu_style'] = $oldArr['ssu_style'];
			if(empty($dataArr['ssu_shop_id'])) $dataArr['ssu_shop_id'] = $oldArr['ssu_shop_id'];
		}

		if(isset($dataArr['ssu_engine'])) $dataArr['ssu_engine'] = (int) $dataArr['ssu_engine'];
		if(isset($dataArr['ssu_btime'])) $dataArr['ssu_btime'] = (int) $dataArr['ssu_btime'];
		if(isset($dataArr['ssu_etime'])) $dataArr['ssu_etime'] = (int) $dataArr['ssu_etime'];
		if(isset($dataArr['ssu_zhiming_btime'])) $dataArr['ssu_zhiming_btime'] = (int) $dataArr['ssu_zhiming_btime'];
		if(isset($dataArr['ssu_zhiming_etime'])) $dataArr['ssu_zhiming_etime'] = (int) $dataArr['ssu_zhiming_etime'];
		if(isset($dataArr['ssu_status'])) $dataArr['ssu_status'] = (int) $dataArr['ssu_status'];
		if(isset($dataArr['ssu_seq'])) $dataArr['ssu_seq'] = (int) $dataArr['ssu_seq'];
		if(isset($dataArr['ssu_tuijian_seq'])) $dataArr['ssu_tuijian_seq'] = (int) $dataArr['ssu_tuijian_seq'];
		if(isset($dataArr['ssu_name'])) $dataArr['ssu_initial'] = LibFc::GetInitial($dataArr['ssu_name']);

		if($dataArr['ssu_style'] == 'B2C')
		{
			$dataArr['ssu_shop_id'] = (int) $dataArr['ssu_shop_id'];
			$dataArr['ssu_tcd_supid'] = 0;
			$res = $this->get('sh_shop', ['shop_id'], sprintf(" and shop_id=%d", $dataArr['ssu_shop_id']), true);
			if(empty($res['data']))
				return LibFc::ReturnData(false,'品牌目录配置出错，店铺ID不存在');
		}
		else
		{
			if($dataArr['ssu_style'] == 'TCD') 
				$dataArr['ssu_tcd_supid'] = (int) $dataArr['ssu_tcd_supid'];
			else
				$dataArr['ssu_tcd_supid'] = 0;
			$dataArr['ssu_model'] = '{}';
			$dataArr['ssu_conf'] = '{}';
			$dataArr['ssu_shop_id'] = 0;
		}
		$dataArr['ssu_au_uid'] = $dataArr['ssu_au_uid']?:0;
		$this->B2CDb->Begin();
		//设置超卖
		if(isset($dataArr['shop_overbook']))
		{
			$this->set('sh_shop',['shop_overbook'=>(int)$dataArr['shop_overbook']],sprintf(" AND shop_id=%d",$dataArr['ssu_shop_id']));
			unset($dataArr['shop_overbook']);
		}

		
		//设置水印图
		if(isset($dataArr['shop_warter']))
		{
			$this->setShopProductWarter($dataArr['ssu_shop_id'], $dataArr['shop_warter']);
			unset($dataArr['shop_warter']);
		}

		if(!empty($sup_id))
		{
			$this->set('sh_super', $dataArr, sprintf(" and ssu_id=%d", $sup_id));
		}
		else
		{
			$res = $this->add('sh_super', $dataArr);
			$dataArr['ssu_id'] = $res['data'];
			$sup_id = $dataArr['ssu_id'];
		}
		//更新
		if($dataArr['ssu_shop_id']){
			$YpwBase = new YpwBase();
			$YpwBase->set('yp_user', ['u_b2c_shopid'=>$dataArr['ssu_shop_id']], sprintf(" and u_id=%d", $dataArr['ssu_shop_id']));
		}

		if($partArr !== null && !empty($dataArr['ssu_shop_id']))
		{
			foreach($partArr as $k=>$v)
			{
				$partArr[$k] = (int) $v;
			}
			$res = $this->get('sh_super_part', ['sup_part_id'], sprintf(" and sup_shop_id=%d", $dataArr['ssu_shop_id']));
			$hasArr = array_column($res['data'], 'sup_part_id');
			$delArr = array_diff($hasArr, $partArr);
			$addArr = array_diff($partArr, $hasArr);
			foreach($addArr as $id)
			{
				$this->add('sh_super_part', ['sup_shop_id'=>$dataArr['ssu_shop_id'], 'sup_part_id'=>$id]);
			}
			if(!empty($delArr))
				$this->del('sh_super_part', sprintf(" and sup_shop_id=%d and sup_part_id in (%s)", $dataArr['ssu_shop_id'], implode(',', $delArr)));
		}

		//一个产品都没有时，自动初始化所有数据到目录分类
		$res = $this->get('bc_product', ['count(*) count'], sprintf(" and pro_shop_id=%d and pro_show_super=1", $dataArr['ssu_shop_id']), true);
		if(empty($res['data']))
		{
			$this->set('bc_product', ['pro_show_super'=>1], sprintf(" and pro_shop_id=%d", $dataArr['ssu_shop_id']));
		}
		//配置品牌目录时 配件展示直接赋值
		if($dataArr['ssu_shop_id']){
			$itemCofArr = [];
			if (isset($dataArr['ssu_super_gzh']) && (bool)$dataArr['ssu_super_gzh'] != (bool)$oldArr['ssu_super_gzh']) {
				$itemCofArr['shop_show_super'] = (int)$dataArr['ssu_super_gzh'] > 0 ? 1 : 0;
			}
			if (isset($dataArr['ssu_pjl_show']) && $dataArr['ssu_pjl_show'] != $oldArr['ssu_pjl_show']) {
				$itemCofArr['shop_show_pjl'] = (int)$dataArr['ssu_pjl_show'] > 0 ? 1 : 0;
			}
			if($itemCofArr){
				$this->changeShopItemToShow($dataArr['ssu_shop_id'], $itemCofArr);
			}
		}
		//初始化数据  某个分类一个产品都没有时，自动将此分类下的所有配件设置为目录配件
		/*$where = sprintf(" and pro_part_id in (
			select sup_part_id from sh_super_part where sup_part_id not in (
				select distinct sup_part_id from bc_product join sh_super_part on pro_part_id = sup_part_id and pro_shop_id = sup_shop_id where sup_shop_id=%d and pro_show_super = 1
			) and sup_shop_id= %d 
		) and pro_shop_id=%d", $dataArr['ssu_shop_id'], $dataArr['ssu_shop_id'], $dataArr['ssu_shop_id']);
		$this->set('bc_product', ['pro_show_super'=>1], $where);
		
		//取消不是目录分类的配件
		$this->set('bc_product', ['pro_show_super'=>0], sprintf(" and pro_part_id not in (select sup_part_id from sh_super_part where sup_shop_id=%d) and pro_shop_id=%d", $dataArr['ssu_shop_id'], $dataArr['ssu_shop_id']));*/
		// 日志
		if($dataArr['ssu_style'] == 'B2C'){
			$B2cLog = new B2cLog();
			$item = [
				'log_shop_id'=>$dataArr['ssu_shop_id'],
				'log_category'=>'21',
				'log_txt'=>'设置公众号目录信息',
				'log_dataid'=>$dataArr['ssu_shop_id']
			];
			$B2cLog->addFastLog($item);	
		}
		
		$this->B2CDb->End();
		if($dataArr['ssu_shop_id'] > 0)
		{
			//复制目录文件
			$superSys = mvc::$cfg['ROOT'].'super/';
			if(!file_exists($superSys.$dataArr['ssu_shop_id']))
			{
				LibDir::copydir($superSys.'demo', $superSys.$dataArr['ssu_shop_id']);
			}
		}
		return LibFc::ReturnData(true, $sup_id);
	}

	/**
	 * @method 设置目录组合
	 * @param $ssp_id 目录组合ID
	 * @param $dataArr 数据数组
	 * @author hongzhang
	 * @copyright 2025-07-15
	 * @return ["status"=> bool(true), "data"=> true, "code"=>""]
	 */
	public function setShopSuperPack($ssp_id, $dataArr)
	{ 	
		$ssp_id = (int) $ssp_id;
		$sspData = [];
		$operation = '';
		$target_ssp_id = 0;
		//是否编辑了子目录
		$ifEditChildrenList = $dataArr['ifEditChildrenList'];
		$this->B2CDb->Begin();
		
		//编辑
		if(!empty($ssp_id)){
			$operation = 'edit';
			$target_ssp_id = $ssp_id;
			
			if (isset($dataArr['ssp_name'])) $sspData['ssp_name'] = trim($dataArr['ssp_name']);
			if (isset($dataArr['ssp_seq'])) $sspData['ssp_seq'] = (int) $dataArr['ssp_seq'];
			if (isset($dataArr['ssp_begin_time'])) $sspData['ssp_begin_time'] = (int) $dataArr['ssp_begin_time'];
			if (isset($dataArr['ssp_end_time'])) $sspData['ssp_end_time'] = (int) $dataArr['ssp_end_time'];
			$sspData['ssp_etime'] = time();
			$this->set('sh_super_pack', $sspData, sprintf(" and ssp_id=%d", $ssp_id));
			//根据ssp_super_ids同步关联表,未编辑子目录时，不进行同步	
			if($ifEditChildrenList == 1){
				// 查询现有的关联关系
				$existingRes = $this->get('sh_super_pack_link', ['sspl_ssu_id', 'sspl_seq'], sprintf(" and sspl_ssp_id=%d", $ssp_id));
				$oldLinks = array_column($existingRes['data'], 'sspl_seq' ,'sspl_ssu_id');
				
				// 构建新的关联关系
				$newLinks = [];
				if(isset($dataArr['ssp_super_ids']) && !empty($dataArr['ssp_super_ids'])){
					foreach($dataArr['ssp_super_ids'] as $index => $ssu_id){
						$newLinks[$ssu_id] = $index;
					}
				}
				
				// 找出需要删除的项（原来有但新数据中没有的）
				$toDelete = array_diff_key($oldLinks, $newLinks);
				$toDeleteIds = array_keys($toDelete);
				if(!empty($toDeleteIds)){
					$this->del('sh_super_pack_link', sprintf(" and sspl_ssp_id=%d and sspl_ssu_id in (%s)", $ssp_id, implode(',', $toDeleteIds)));
				}
				
				// 找出需要添加的项（新数据中有但原来没有的）
				$toAdd = array_diff_key($newLinks, $oldLinks);
				foreach($toAdd as $ssu_id => $seq) {
					$this->add('sh_super_pack_link', ['sspl_ssp_id'=>$ssp_id, 'sspl_ssu_id'=>$ssu_id, 'sspl_seq'=>$seq]);
				}
				
				// 找出需要更新的项（原来有但顺序改变的）
				$toUpdate = array_intersect_key($newLinks, $oldLinks);
				foreach($toUpdate as $ssu_id => $newSeq) {
					if($oldLinks[$ssu_id] != $newSeq) {
						$this->set('sh_super_pack_link', ['sspl_seq'=>$newSeq], sprintf(" and sspl_ssp_id=%d and sspl_ssu_id=%d", $ssp_id, $ssu_id));
					}
				}
			}
		}else{
			$operation = 'add';
			
			//添加
			if (isset($dataArr['ssp_name'])) $sspData['ssp_name'] = trim($dataArr['ssp_name']);
			if (isset($dataArr['ssp_seq'])) $sspData['ssp_seq'] = (int) $dataArr['ssp_seq'];
			if (isset($dataArr['ssp_begin_time'])) $sspData['ssp_begin_time'] = (int) $dataArr['ssp_begin_time'];
			if (isset($dataArr['ssp_end_time'])) $sspData['ssp_end_time'] = (int) $dataArr['ssp_end_time'];
			$sspData['ssp_atime'] = time();
			
			$res = $this->add('sh_super_pack', $sspData);
			$target_ssp_id = $res['data'];
			unset($sspData);

			//根据ssp_super_ids同步关联表，未编辑子目录时，不进行同步
			if($ifEditChildrenList == 1 && isset($dataArr['ssp_super_ids']) && !empty($dataArr['ssp_super_ids'])){
				foreach($dataArr['ssp_super_ids'] as $index => $ssu_id){
					$this->add('sh_super_pack_link', ['sspl_ssp_id'=>$target_ssp_id, 'sspl_ssu_id'=>$ssu_id, 'sspl_seq'=>$index]);

				}
			}
		}
		
		$this->B2CDb->End();
		return LibFc::ReturnData(true, $target_ssp_id);
	}

	/**
	 * @method 目录组合详情
	 * @param $ssp_id 目录组合ID
	 * @author hongzhang
	 * @copyright 2025-07-16
	 * @return ["status"=> bool(true), "data"=> array, "code"=>""]
	 */
	public function ShopSuperPackDetail($ssp_id)
	{
		$ssp_id = (int) $ssp_id;
		$this->B2CDb->Begin();
		$res = $this->get('sh_super_pack', ['*'], sprintf(" and ssp_id=%d", $ssp_id), true);
		$superRow = $res['data'];
		//查询组合已经包含的目录
		$res = $this->get('sh_super_pack_link', ['sspl_ssp_id', 'sspl_ssu_id'], sprintf(" and sspl_ssp_id=%d order by sspl_seq asc", $ssp_id));

		$this->B2CDb->End();
		$superRow['ssp_super_ids'] = array_column($res['data'], 'sspl_ssu_id');
		return LibFc::ReturnData(true, $superRow);
	}



	/**
	  * @method 扣除车型库号码查询次数
	  * @param  $shopid 店铺ID
	  * @param  $uid 用户ID
	  * @param  number 查询的号码
	  * @author soul
	  * @copyright 2019/7/12
	  * @return ["status"=> bool(true), "data"=> true, "code"=>""]
	  */
	public function changeYpcNumCount($shopid, $uid, $number)
	{
		$format = LibFc::FormatNum($number);
		if(strlen($format) > 2)
		{
			$shopid = (int) $shopid;
			$uid = (int) $uid;
			$res = $this->get('sh_ypc_number', ['count(*) count'], sprintf(" and syn_shop_id=%d and syn_format='%s'", $shopid, $format), true);
			//之前未查过
			if(empty($res['data']['count']))
			{
				//是否还有次数
				$res = $this->get('sh_super', ['ssu_ypc_num_count'], sprintf(" and ssu_shop_id=%d", $shopid), true);
				if(empty($res['data']) || $res['data']['ssu_ypc_num_count'] < 1)
					return LibFc::ReturnData(false, '查看OE的次数已用完，请联系客服！');

				$this->B2CDb->Begin();
				$addArr = [
					'syn_shop_id'=>$shopid,
					'syn_uid'=>$uid,
					'syn_display'=>$number,
					'syn_format'=>$format,
					'syn_atime'=>time()
				];
				$this->add('sh_ypc_number', $addArr);
				$this->set('sh_super', ['ssu_ypc_num_count'=>'#@ssu_ypc_num_count-1'], sprintf(" and ssu_shop_id=%d", $shopid));
				$this->B2CDb->End();
			}
		}
		return LibFc::ReturnData(true);
	}



	/**
	  * @method 重置产品展示渠道
	  * @param  $shopid 店铺ID
	  * @param  $cofArr [
			'shop_show_b2c'=>1,
			'shop_show_app'=>0,
			'shop_show_super'=>0,
			'shop_show_pjl'=>1
		]
	  * @author soul
	  * @copyright 2019/10/9
	  * @return ["status"=> bool(true), "data"=> true, "code"=>""]
	  */
	public function changeShopItemToShow($shopid, $cofArr)
	{
		$shopid = (int) $shopid;
		if(empty($cofArr)) return LibFc::ReturnData(true);
		$res = $this->get('sh_shop left join sh_super on shop_id=ssu_shop_id left join sh_shop_app on aps_shop_id=shop_id', ['*'], sprintf(" and shop_id=%d", $shopid), true);
		if(!empty($res['data']))
		{
			$shopArr = $res['data'];
			$this->B2CDb->Begin();
			
			if(isset($cofArr['shop_show_b2c'])){
				$setArr['shop_show_b2c'] = !empty($cofArr['shop_show_b2c'])? 1: 0;
				$this->set('bc_product', ['pro_show_b2c'=>$setArr['shop_show_b2c']], sprintf(" and pro_shop_id=%d", $shopArr['shop_id']));
			}
			
			if(isset($cofArr['shop_show_app'])){
				$setArr['shop_show_app'] = !empty($cofArr['shop_show_app']) && !empty($shopArr['aps_shop_id'])? 1: 0;
				$this->set('bc_product', ['pro_show_app'=>$setArr['shop_show_app']], sprintf(" and pro_shop_id=%d", $shopArr['shop_id']));
			}
			
			if(isset($cofArr['shop_show_super'])){
				$setArr['shop_show_super'] = !empty($cofArr['shop_show_super']) && !empty($shopArr['ssu_shop_id'])? 1: 0;
				$this->set('bc_product', ['pro_show_super'=>$setArr['shop_show_super']], sprintf(" and pro_shop_id=%d", $shopArr['shop_id']));
			}
			
			if(isset($cofArr['shop_show_pjl'])){
				$setArr['shop_show_pjl'] = !empty($cofArr['shop_show_pjl'])? 1: 0;
				$this->set('bc_product', ['pro_show_pjl'=>$setArr['shop_show_pjl']], sprintf(" and pro_shop_id=%d", $shopArr['shop_id']));
			}
		
			$this->set('sh_shop', $setArr, sprintf(" and shop_id=%d", $shopArr['shop_id']));
			$this->B2CDb->End();
		}
		return LibFc::ReturnData(true);
	}

	/**
	  * @method 设置店铺的产品水印图
	  * @param  $shopid 店铺ID
	  * @param  $shop_warter 为空时将删除水印图
	  * @author soul
	  * @copyright 2021/6/22
	  * @return ["status"=> bool(true), "data"=> true, "code"=>""]
	  */
	public function setShopProductWarter($shopid, $shop_warter)
	{
		if(stripos($shop_warter, 'png') > 0)
		{
			$this->set('sh_shop',['shop_warter'=>$shop_warter], sprintf(" and shop_id=%d", $shopid));
		}
		else
		{
			$res = $this->get('sh_shop',['shop_warter'], sprintf(" and shop_id=%d", $shopid), true);
			if(!empty($res['data']))
			{
				$OthFileCenter = new OthFileCenter();
				$dataArr = [
					'cate'=>'warter',
					'files'=>[$res['data']['shop_warter']]
				];
				$OthFileCenter->del($dataArr, 'b2c');
				$this->set('sh_shop', ['shop_warter'=>''], sprintf(" and shop_id=%d", $shopid));
			}
		}
		return LibFc::ReturnData(true);
	}


	/**
	 * @method   修改代理商信息
	 * @author soul
	 * @copyright 2021/7/27
	 */
	public function setShopDaili($shopId, $addrArr)
	{
		$shopId = (int) $shopId;
		if($shopId < 1 || empty($addrArr)) return LibFc::ReturnData(false, 'setShopAddr 参数不正确');
		
		$LibYpApi = new LibYpApi();
		$res = $this->get('sh_daili_addr', ['sha_id', 'sha_addr', 'sha_pct_ids', 'sha_lng'], sprintf(" and sha_shop_id=%d", $shopId));
		$hasArr = array_column($res['data'], null, 'sha_id');
		$this->B2CDb->Begin();
		$newIdArr = array_keys($addrArr);
		$delwhere = sprintf(" and sha_shop_id=%d", $shopId);
		if(!empty($newIdArr)) $delwhere .= sprintf(" and sha_id not in (%s)", implode(',', $newIdArr));
		$this->del('sh_daili_addr', $delwhere);
		foreach($addrArr as $shaId=>$val)
		{
			if(empty($val['sha_comname']) || empty($val['sha_tel']) || empty($val['sha_pct_ids']) || empty($val['sha_addr'])) continue;
			$aroundArr = [
				'sha_shop_id'=>$shopId,
				'sha_comname'=>$val['sha_comname'],
				'sha_tel'=>$val['sha_tel'],
				'sha_pct_ids'=>$val['sha_pct_ids'],
				'sha_addr'=>$val['sha_addr'],
				'sha_etime'=>time(),
				'sha_seq'=>(int)$val['sha_seq'],
			];
			if(empty($hasArr[$shaId]) || empty($hasArr[$shaId]['sha_lng']) || $hasArr[$shaId]['sha_addr'] != $val['sha_addr'] || $hasArr[$shaId]['sha_pct_ids'] != $val['sha_pct_ids'])
			{
				$lngres = $LibYpApi->Get('user/formatAddrInfo', ['addr'=>$val['sha_addr'], 'pctIds'=>$val['sha_pct_ids'], 'lngFlag'=>1]);
				if($lngres['data']['lng'] && $lngres['data']['lat'])
				{
					$aroundArr['sha_lng'] = $lngres['data']['lng'];
					$aroundArr['sha_lat'] = $lngres['data']['lat'];
				}
				usleep(300000);
			}
			if($shaId > 0)
			{
				$this->set('sh_daili_addr', $aroundArr, sprintf(" and sha_shop_id=%d and sha_id=%d", $shopId, $shaId));
			}
			else
			{
				$aroundArr['sha_atime'] = time();
				$this->add('sh_daili_addr', $aroundArr);
			}
		}
		$this->B2CDb->End();
		return LibFc::ReturnData(true);
	}


	/**
	 * @method   修改代理商信息
	 * @author soul
	 * @copyright 2021/7/27
	 */
	public function importShopDaili($shopId, $addrArr)
	{
		$shopId = (int) $shopId;
		if($shopId < 1 || empty($addrArr)) return LibFc::ReturnData(false, '获取店铺信息失败');
		
		$res = $this->get('sh_daili_addr', ['max(sha_seq) as maxseq'], sprintf(" and sha_shop_id=%d", $shopId), true);
		$maxseq = (int) $res['data']['maxseq'];

		$LibYpApi = new LibYpApi();
		$this->B2CDb->Begin();
		foreach($addrArr as $k=>$val)
		{
			if(empty($val['sha_comname']) || empty($val['sha_tel']) || empty($val['sha_addr'])) continue;
			$lngres = $LibYpApi->Get('user/formatAddrInfo', ['addr'=>$val['sha_addr'], 'lngFlag'=>1]);
			$lngres = $lngres['data'];
			$val['sha_lng'] = $lngres['lng'];
			$val['sha_lat'] = $lngres['lat'];
			$val['sha_pct_ids'] = implode(',', $lngres['pctids']);
			$val['sha_addr'] = $lngres['new'];

			$aroundArr = [
				'sha_shop_id'=>$shopId,
				'sha_comname'=>$val['sha_comname'],
				'sha_tel'=>$val['sha_tel'],
				'sha_pct_ids'=>$val['sha_pct_ids'],
				'sha_lng'=>$val['sha_lng'],
				'sha_lat'=>$val['sha_lat'],
				'sha_addr'=>$val['sha_addr'],
				'sha_etime'=>time()
			];
			
			$chkwhere = sprintf(" and sha_shop_id=%d and sha_pct_ids='%s' and sha_addr='%s'", $shopId, LibFc::Escape($val['sha_pct_ids']), LibFc::Escape($val['sha_addr']));
			$res = $this->get('sh_daili_addr', ['sha_id'], $chkwhere, true);
			if(!empty($res['data']['sha_id']))
			{
				$shaId = $res['data']['sha_id'];
				$this->set('sh_daili_addr', $aroundArr, sprintf(" and sha_shop_id=%d and sha_id=%d", $shopId, $shaId));
			}
			else
			{
				$aroundArr['sha_seq'] = $maxseq;
				$maxseq++;
				$aroundArr['sha_atime'] = time();
				$this->add('sh_daili_addr', $aroundArr);
			}
		}
		$this->B2CDb->End();
		return LibFc::ReturnData(true);
	}


	/**
	 * @method 获取公众号的指定用户的权限代码
	 * @http get 
	 * @param  shopid              int [必填] 店铺ID
	 * @param  uid              int [必填] 用户ID
	 * @author zhengweihua 
	 * @copyright 2022-05-20
	 * @return  {"status":true,"data":[{"smr_code":"item_buy","smr_name":"配件购买"},{"smr_code":"item_page","smr_name":"配件详情页"},{"smr_code":"search_engine","smr_name":"发动机查询"}],"code":"","encry":0,"runtime":99}
	 	smr_code 会员权限代码
	    smr_name 会员权限说明
	 */
	public function getGzhUserRule($shopid, $uid)
	{
		$shopid = (int) $shopid;
		$uid = (int) $uid;
		$B2cBase = new B2cBase();
		$now = time();
		$where = sprintf(" and aps_status =1 and shop_status=1 and shop_id=%d and aps_btime <= %d and aps_etime >=%d ", $shopid, $now, $now);
		$superRes = $B2cBase->get('sh_shop_app join sh_shop on aps_shop_id = shop_id',['aps_shop_id'], $where, true);
		if(empty($superRes['data'])) LibFc::ReturnJson(true, []);
		
		$table = 'sh_member_rule_link join sh_member_rule on smr_code = smrl_smr_code';
		$res = $B2cBase->get($table, ['smr_code,smr_name,smrl_mel_id'], sprintf(" and smrl_shop_id=%d order by smr_seq asc", $shopid));
		//未配置,拥有所有权限
		if ($shopid == $uid || empty($res['data'])) 
		{
			$result = $B2cBase->get('sh_member_rule', ['smr_code,smr_name']," order by smr_seq asc");
			$res = $result['data'];
		}
		else
		{	//未注册登陆
			$meml_id = -1;
			$result = [];
			foreach ($res['data'] as $item) 
			{
				$result[$item['smrl_mel_id']][] = [
					'smr_code' => $item['smr_code'],
					'smr_name' => $item['smr_name']
				];
			}
			if(!empty($uid)) 
			{
				$meml_id = 0;
				//存在店铺用户
				$table = 'sh_member_link join sh_member on meml_mem_id = mem_id';
				$memberRes = $B2cBase->get($table, ['mem_mel_id'], sprintf(" and meml_uid=%d and meml_shop_id=%d ", $uid, $shopid), true);
				if (!empty($memberRes['data'])) $meml_id = $memberRes['data']['mem_mel_id'];
			}
			$res = $result[$meml_id] ? $result[$meml_id] : [];
		}
		return LibFc::ReturnData(true,$res);
	}

	/**
	 * @param  int $shopId
	 * @param  array  $brandArr
	 * @method 保存店铺全车件品牌
	 * @author zhengweihua 
	 * @copyright 2023-05-08
	 */
	public function setShopBrand($shopId,$brandArr = [])
	{
		$shopId = (int) $shopId;

		$res = $this->get('sh_shop_brand',['ssb_brand_id'],sprintf(" AND ssb_shop_id=%d",$shopId));
		$this->B2CDb->Begin();
		$oldBrandArr = array_column($res['data'],'ssb_brand_id');
		$delBrandArr = array_filter(array_diff($oldBrandArr,$brandArr));	
		$addBrandArr = array_filter(array_diff($brandArr,$oldBrandArr));
		if(!empty($delBrandArr)){
			$this->del('sh_shop_brand',sprintf(" AND ssb_shop_id=%d AND ssb_brand_id IN (%s)",$shopId,implode(',',$delBrandArr)));
		}
		if(!empty($addBrandArr)){
			$arr =[];
			foreach ($addBrandArr as $key => $aitem) {
				$arr[] = ['ssb_shop_id'=>$shopId,'ssb_brand_id'=>$aitem];
			}
			$this->addAny('sh_shop_brand',['ssb_shop_id','ssb_brand_id'],$arr);
		}
		$this->B2CDb->End();
		return LibFc::ReturnData(true);
	}

	/**
	 * @param  int $shopId
	 * @method 获取店铺设置品牌
	 * @author zhengweihua 
	 * @copyright 2023-05-08
	 */
	public function getShopBrand($shopId)
	{
		$brandArr = [];
		$res = $this->get("sh_shop",['shop_mod_admin'],sprintf(" AND shop_id=%d",$shopId),true);
		if($res['data']['shop_mod_admin']){
			switch ($res['data']['shop_mod_admin']) {
				case 'pc':
						$ComModel = new ComModel();
						$res = 	$ComModel->get('bc_model2 join bc_brand on mod2_brand_id = brand_id',['distinct brand_id']," and mod2_pc=1 and mod2_cv=0");
					break;
				case 'cv':
						$ComModel = new ComModel();
						$res = 	$ComModel->get('bc_model2 join bc_brand on mod2_brand_id = brand_id',['distinct brand_id']," and mod2_pc=0 and mod2_cv=1");
					break;
				case 'brand':
						$res = $this->get("sh_shop_brand",['ssb_brand_id as brand_id'],sprintf(" AND ssb_shop_id=%d",$shopId));
					break;
			}
			if($res['data']){
				$brandArr = array_column($res['data'],'brand_id');
			}
		}
		return LibFc::ReturnData(true, $brandArr);
	}

	/**
	 * @param  Int $shopId
	 * @method 获取后端展示车型类型
	 * @author zhengweihua 
	 * @copyright 2023-06-27
	 */
	public function getshopModAdmin($shopId)
	{	
		$data = [];
		$res = $this->get("sh_shop",['shop_mod_admin'],sprintf(" AND shop_id=%d",$shopId),true);
		
		switch ($res['data']['shop_mod_admin']) {
			case 'pc':
				$data['pc'] = 1;
				break;
			case 'cv':
				$data['cv'] = 1;
				break;
			case 'brand':
				$brandRes = $this->get("sh_shop_brand", ['ssb_brand_id'], sprintf(" AND ssb_shop_id=%d", $shopId));
				if($brandRes['data']){
					$data['brand_limit'] = implode(',', array_column($brandRes['data'],'ssb_brand_id'));
				}
			break;
		}
		return  LibFc::ReturnData(true, $data);
	}

	/**
	 * @param  Int $shopId
	 * @method 获取不同模式下的sql
	 * @author zhengweihua 
	 * @copyright 2023-06-27
	 */
	public function getshopModAdminSql($shopId)
	{	
		$comWhere = '';
		$res = $this->get("sh_shop",['shop_mod_admin'],sprintf(" AND shop_id=%d",$shopId),true);
		if ($res['data']) {
			switch ($res['data']['shop_mod_admin']) {
				case 'pc':
					$comWhere .= " AND mod2_pc=1 and mod2_cv=0";
					break;
				case 'cv':
					$comWhere .= " AND mod2_pc=0 and mod2_cv=1";
					break;
				case 'brand':
					$brandRes = $this->get("sh_shop_brand", ['ssb_brand_id'], sprintf(" AND ssb_shop_id=%d", $shopId));
					if ($brandRes['data']) {
						$comWhere .= sprintf(" AND brand_id in (%s)", implode(',',array_column($brandRes['data'],'ssb_brand_id')));
					}
					break;
			}
		}
		return  LibFc::ReturnData(true, $comWhere);
	}

	/**
	 * @param  int $shopId
	 * @param  Array $dataArr
	 * @method 设置后端车型展示
	 * @author zhengweihua 
	 * @copyright 2023-06-27
	 */
	public function setShopModAdmin($shopId,$dataArr)
	{		
		
		$this->B2CDb->Begin();
		if($dataArr['shop_mod_admin'] =='brand')
		{
			if(empty($dataArr['brand_id'])) return LibFc::ReturnJson(false,'参数错误');
			$this->setShopBrand($shopId,$dataArr['brand_id']);
		}else{
			$this->del('sh_shop_brand',sprintf(" AND ssb_shop_id=%d",$shopId));
		}
		$res = 	$this->set('sh_shop',['shop_mod_admin'=>$dataArr['shop_mod_admin']],sprintf(" and shop_id=%d",$shopId));
		$this->B2CDb->End();
		return LibFc::ReturnData(true);
	}

	
	/**
	 * @param  int $shopId
	 * @param  Array $dataArr ['shop'=>['shop_mod_admin'=>'','shop_mod_from'=>'','shop_mod_adminfield'=>'','shop_mod_webfield'=>'']]
	 * @method
	 * @author zhengweihua 
	 * @copyright 2023-10-19
	 */
	public function setShopMod($shopId,$dataArr)
	{
		if(empty($dataArr['shop'])) return LibFc::ReturnData(false,'参数错误');
		$shopData = $dataArr['shop'];
		$this->B2CDb->Begin();
		$res = 	$this->set('sh_shop',$shopData,sprintf(" and shop_id=%d",$shopId));	
		if($shopData['shop_mod_admin']=='brand')
		{
			if(empty($dataArr['brand_id'])) return LibFc::ReturnData(false,'参数错误');
			$this->setShopBrand($shopId,$dataArr['brand_id']);
		}
		else
		{
			$this->del('sh_shop_brand',sprintf(" AND ssb_shop_id=%d",$shopId));
		}
		if($shopData['shop_mod_from']=='self')
		{
			$res = $this->get('sh_shop_model1',['ssm_mod1_id'],sprintf(' and ssm_shop_id = %d',$shopId));
			$oldMod1Id = array_column($res['data'],'ssm_mod1_id');
			if(!empty($dataArr['mod_ids'])){
				$modIdArr = explode(',',$dataArr['mod_ids']);
				$delIdArr = array_diff($oldMod1Id,$modIdArr);
				$addIdArr = array_diff($modIdArr,$oldMod1Id);
				$arr = [];
				if(!empty($delIdArr)){
					$where =  sprintf(' and ssm_mod1_id in (%s)',implode(',',$delIdArr));
					$this->del('sh_shop_model1',$where);
				}
				if(!empty($addIdArr)){
					foreach ($addIdArr as $item) {
						$t  = [
							'ssm_shop_id'=> $_SESSION['_shopid'],
							'ssm_mod1_id'=> $item
						];
						$arr[] = $t;
					}
					$this->addAny('sh_shop_model1',['ssm_shop_id','ssm_mod1_id'],$arr);
				}
			}
		}
		$this->B2CDb->End();
		return LibFc::ReturnData(true);
	}

	/**
	 * @param  int $shopId
	 * @method 获取店铺等级
	 * @author zhengweihua 
	 * @copyright 2024-03-26
	 */
	public function getShopMember($shopId)
	{
		$table = sprintf('sh_member_level left join sh_member on mel_id = mem_mel_id AND mem_shop_id=%d',$shopId);
        $res = $this->get($table,['*'],'AND mel_id!=-1 order by mel_id asc');
		return LibFc::ReturnData(true,$res['data']);
	}
}