<?php
/**
  * @method 配件
  * @author soul 2017/5/10
  */
class itemAction
{
	//只能调用/static/目录下的 js | css | 控件[webuploader、datetimepicker、ueditor]
	private $HEAD_CSSJS = [];

	function __construct()
	{
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
	}
	
	/**
	  * @method 配件详细页
	  * @author soul 2017/5/10
	  */
	function index()
	{
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();

		$Params = mvc::$URL_PARAMS;
		$proId = (int) $Params['proId'];
		$B2cProduct = new B2cProduct();
		$res = $B2cProduct->getProduct(['pro_id', 'pro_shop_id', 'pro_name'], sprintf(" and pro_show_b2c=1 and shop_status = 1 and pro_id = %d", $proId), true);
		$proArr = $res['data'];
		if(empty($proArr['pro_id']))
		{
			//页面不存在
			LibTpl::itemError();
		}

		//获取权限
		$permissionArr = [];
		$B2cShop  = new B2cShop();
		$result = $B2cShop->getGzhUserRule($proArr['pro_shop_id'],$_SESSION['_userid']);
		if($result['data']) $permissionArr = array_column($result['data'], 'smr_code');
		mvc::$cfg['permissionArr'] = $permissionArr;
		//配件详情权限
		if(!in_array('item_page',$permissionArr)){
			//页面不存在
			LibTpl::Error('无权限访问该页面！');
			exit;
		}
		//配件车型权限
		if(in_array('item_model',$permissionArr))
		{
			//获取适配车型
			$res = $B2cProduct->get('bc_product_model3_link',['count(*) count'],'and pml3_pro_id='.$proId,true);
			if($res['data']['count']>0) LibTpl::Set('fitCar',$res['data']['count']);
		}
		

		// 获取参考号码数量
		$B2cBase = new B2cBase();
		// $res = $B2cBase->get('bc_number', ['count(*) fitnumber'], sprintf(" and num_self=0 and num_pro_id=%s ", $proId));
		// $res = current($res['data']);
		// LibTpl::Set('fitNumber',$res['fitnumber']);
		
		//初始化店铺路径
		mvc::$cfg['ROOT_SHOP'] = mvc::$cfg['ROOT'].'shop/'.$proArr['pro_shop_id'].'/';
		if(!file_exists(mvc::$cfg['ROOT_SHOP'].'shop.config.php'))
		{
			//页面不存在
			LibTpl::Error('店铺不存在！');
			exit;
		}
		$shopCfg = require(mvc::$cfg['ROOT_SHOP'].'shop.config.php');
		mvc::$cfg = array_merge(mvc::$cfg, $shopCfg);
		$config['PATH_TPL'] = mvc::$cfg['ROOT'].'shop/demo/tpl/';
		//店铺页面配置
		$pageConfigAll = require(mvc::$cfg['ROOT_SHOP'].'page.config.php');
		$pageConfing = $pageConfigAll['item/index'];
		mvc::$cfg['tplName'] = $pageConfigAll['tplName'];

		//头部和底部公共模块配置
		$pageConfing['modules']['top'] = $pageConfigAll['public']['top'];
		$pageConfing['modules']['foot'] = $pageConfigAll['public']['foot'];

		//模块配置
		$pageData = [];
		//店铺基本信息、店铺名称、域名等提前加载
		$ShopBase = new ShopBase();
		$shopInfo = $ShopBase->getShopInfo($proArr['pro_shop_id']);
		LibTpl::Set('shopInfoData', $shopInfo);

		//获取有图片的评价总数
		$count = $B2cBase->get('or_evaluate_product',['count(*) as count'],sprintf(' and evp_pro_id=%d',$proId).' and evp_id in(select evp_id from or_evaluate_product left join or_evaluate_img on evp_id=evi_evi_id where evi_id is not null group by evp_id)',true);
		LibTpl::Set('imgTotal', $count['data']['count']);

		//查询是否已收藏配件
		if(!empty($_SESSION['_userid']))
		{
			$res = $B2cBase->get('us_product_collection',['count(*) count'],sprintf('and prc_uid=%d and prc_pro_id=%d',$_SESSION['_userid'],$proId),true);
			LibTpl::Set('isColledPro', $res['data']['count']);
		}
		
		$allModuleConfig = require(mvc::$cfg['ROOT_SHOP_SYS'].'module.config.php');
	
		//加载该店铺的模块数据
		$htmlArr = [];
		$shopCssJs = ['css'=>[], 'js'=>[]];
		foreach($pageConfing['modules'] as $location=>$moduleArr)
		{
			$htmlArr[$location] = [];
			//此位置的所有模块
			foreach($moduleArr as $moduleVal)
			{
				//系统模块配置
				$sysModulConfig = $allModuleConfig[$moduleVal['module']];
				//模块需要加载的数据
				if(!empty($sysModulConfig['data']))
				{
					$class = new $sysModulConfig['data']['class'];
					LibTpl::Set($moduleVal['module'].'Config', $moduleVal['config']);
					LibTpl::Set($moduleVal['module'].'Data', call_user_func_array(array($class, $sysModulConfig['data']['function']), [$proArr['pro_shop_id'],$moduleVal['config']]));
					// print_r(call_user_func_array(array($class, $sysModulConfig['data']['function']), [$moduleVal['config']]));
				}
				//模块需要调用的模板
				if(!empty($sysModulConfig['tpl']))
				{
					$htmlArr[$location][] = LibTpl::Fetch($sysModulConfig['tpl'],$config['PATH_TPL']);
				}
				//模块需要加载的CSS
				if(isset($sysModulConfig['css']))
				{
					$shopCssJs['css'] = array_merge($shopCssJs['css'], $sysModulConfig['css']);
				}
				//模块需要加载的JS
				if(isset($sysModulConfig['js']))
				{
					$shopCssJs['js'] = array_merge($shopCssJs['js'], $sysModulConfig['js']);
				}
			}
		}
		
		//加载模块样式和JS
		$shopCssJs['css'] = array_unique($shopCssJs['css']);
		$shopCssJs['js'] = array_unique($shopCssJs['js']);
		LibTpl::Set('shopCssJs', $shopCssJs);

		$headArr = [
			'title'=> $proArr['pro_name'].'-跑街的-宜配商城',	
			'keyword'=>'欢迎前来跑街的-宜配商城-'.$shopInfo['shop_name'].' 旺铺，众多商品任你选购',	
			'des'=>$shopInfo['shop_profile']
		];
		LibTpl::Set('htmlArr', $htmlArr);
		
		//添加jqeury fly插件
		// $this->HEAD_CSSJS['plugin'][] = 'jqueryFly';
		//添加animate样式库
		$this->HEAD_CSSJS['plugin'][] = 'animate';
		//添加图片放大镜
		$this->HEAD_CSSJS['js'][] = 'js/jquery.imagezoom.min.js';

		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
		LibTpl::Set('headArr', $headArr);
		LibTpl::Put($pageConfing['layout'], $config['PATH_TPL']);
		exit;
	}
	/**
	 * @method    保存收藏配件
	 * @author     廖
	 * @copyright 2017-07-31
	 * @return    LibFc::ReturnData(['status'=>false,'data'=>'xxx']);
	 */
	function ajaxSaveCollPro()
	{
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['proId']))
		{
			$B2cCollPro = new B2cCollPro();
			if(isset($_SESSION['_shopid']) && LibFc::Int($Params['proId']))
			{
				$res = $B2cCollPro->get('bc_product',['count(*) as count'],sprintf(' and pro_id=%d and pro_shop_id=%d',$Params['proId'],$_SESSION['_shopid']),true);
				if($res['data']['count']>0)
				{
					LibFc::ajaxJsonEncode(['status'=>false,'data'=>'不能收藏自己店铺的配件']);
					exit();
				}
			}
			$re = $B2cCollPro->get('us_product_collection',['count(*) as count'],sprintf(' and prc_uid=%d and prc_pro_id=%d',$_SESSION['_userid'],$Params['proId']),true);
			if($re['data']['count']>0)
			{
				$res = $B2cCollPro->cancelCollPro($_SESSION['_userid'],$Params['proId']);
				if($res['status'])
				{
					LibFc::ajaxJsonEncode(['status'=>true,'data'=>false]);
				}else
				{
					LibFc::ajaxJsonEncode(['status'=>false,'data'=>'取消收藏失败！']);
				}
			}else
			{
				$re = $B2cCollPro->addUserCollPro($_SESSION['_userid'],$Params['proId']);
				if($re['status'])
				{
					LibFc::ajaxJsonEncode(['status'=>true,'data'=>true]);
				}
				exit();
			}
		}else
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'收藏配件失败！']);
		}
	}
	/**
	 * @method    保存收藏店铺
	 * @author     廖
	 * @copyright 2017-08-01
	 * @return    LibFc::ReturnData(['status'=>false,'data'=>'xxx']);
	 */
	function ajaxSaveCollShop()
	{
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['shopId']))
		{
			if($_SESSION['_shopid'] != $Params['shopId'])
			{
				$B2cCollShop = new B2cCollShop();
				$re = $B2cCollShop->Get('us_shop_collection',['count(*) as count'],sprintf(' and shc_uid=%d and shc_shop_id=%d',$_SESSION['_userid'],$Params['shopId']),true);
				if($re['data']['count']>0)
				{
					$re = $B2cCollShop->del('us_shop_collection',sprintf(' and shc_uid=%d and shc_shop_id=%d',$_SESSION['_userid'],$Params['shopId']));
					if($re['status'])
					{
						LibFc::ajaxJsonEncode(['status'=>true,'data'=>false]);
					}else
					{
						LibFc::ajaxJsonEncode(['status'=>false,'data'=>'取消收藏店铺失败！']);
					}
					exit();
				}else
				{
					$re = $B2cCollShop->addUserCollShop($_SESSION['_userid'],$Params['shopId']);
					LibFc::ajaxJsonEncode(['status'=>true,'data'=>true]);
					exit();
				}
			}else
			{
				LibFc::ajaxJsonEncode(['status'=>false,'data'=>'不能收藏自己的店铺']);
				exit();
			}
		}
		LibFc::ajaxJsonEncode(['status'=>false,'data'=>'收藏店铺失败']);
	}
	/**
	 * @method    检查收藏店铺
	 * @author     廖
	 * @copyright 2018-2-5
	 * @return    LibFc::ReturnData(['status'=>false,'data'=>'xxx']);
	 */
	function ajaxCheckCollShop()
	{
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['shopId']) && !empty($_SESSION['_userid']))
		{
			$B2cCollShop = new B2cCollShop();
			$re = $B2cCollShop->Get('us_shop_collection',['count(*) as count'],sprintf(' and shc_uid=%d and shc_shop_id=%d',$_SESSION['_userid'],$Params['shopId']),true);
			$re['data'] = $re['data']['count'];
			LibFc::ajaxJsonEncode($re);
		}
	}
	/**
	 * @method    获取评论区域信息
	 * @author     廖
	 * @copyright 2017-08-04
	 * @return    LibFc::ReturnData(['status'=>false,'data'=>html]);
	 */
	function ajaxGetCommentHtml()
	{
		$status = ['status'=>false,'data'=>'参数不正确!'];
		if(LibFc::Int($_POST['proId']))
		{
			$B2cBase = new B2cBase();
			$YpwUser = new YpwUser();
			$base = sprintf(' and evp_pro_id=%d',$_POST['proId']);
			//时间排序
			$seq = $_POST['seq'] == 'time'?' order by evp_add_time desc':' order by evp_add_time asc';
			//有内容
			$hasCom = $_POST['hasCom'] == 'hasCom'?" and evp_comment is not null":'';
			if(empty($_POST['order'])) $_POST['order'] = 'all';
			switch ($_POST['order']) 
			{
				case 'all':
					$order = '';
					break;
				case 'hasImg':
					$order = ' and evp_id in(select evp_id from or_evaluate_product left join or_evaluate_img on evp_id=evi_evi_id where evi_id is not null group by evp_id)';
					break;
				default:
					$_POST['order'] = (int) $_POST['order'];
					$order = sprintf(' and evp_id in(select ell_evp_id from or_evaluate_label_link left join or_evaluate_label on ell_evl_id=evl_id where ell_evl_id=%d)', $_POST['order']);
					break;
			}
			LibTpl::Set('order', $_POST['order']);
			//获取改配件的所有评论的id
			$where = $base.$order.$hasImg.$hasCom.$seq;
			$count = $B2cBase->get('or_evaluate_product',['count(*) as count'],$base.$order.$hasImg.$hasCom,true);
			$total = $count['data']['count'];
			$perPage = 20;
			$nowPage = LibFc::Int($_POST['pageNum']) && $_POST['pageNum'] > 0?$_POST['pageNum']:1;
			$totalPage = ceil($total/$perPage);
			LibTpl::Set('totalPage', $totalPage);
			LibTpl::Set('realPage', $nowPage);

			$dataArr = $B2cBase->Get('or_evaluate_product',['*'], $where.sprintf(' limit %d,%d', ($nowPage-1)*$perPage, $perPage));
			//获取每个评论下的图片 和 评论用户的信息
			if(!empty($dataArr['data']))
			{
				foreach($dataArr['data'] as $key=>$value)
				{
					$imgArr = $B2cBase->Get('or_evaluate_img',['evi_path','evi_name','evi_ext'],' and evi_evi_id='.$value['evp_id'].' order by evi_seq asc');
					$dataArr['data'][$key]['imgInfo'] = $imgArr['data'];
					if(!empty($value['evp_uid']))
					{
						$user = $YpwUser->getUser(['u_name'], sprintf(" and u_id=%d",$value['evp_uid']), true);
						$dataArr['data'][$key]['comUserName'] = $user['data']['u_name'];
					}
				}
			}
			$Page = LibPage::Show($total, $perPage);
			LibTpl::Set('Page', $Page);
			LibTpl::Set('comArr', $dataArr['data']);
			$result=LibTpl::Fetch('item/ajaxGetCommentHtml.php');
			$status = ['status'=>true,'data'=>$result];
		}
		LibFc::ajaxJsonEncode($status);
	}
	



	/**
	 * @method    获取适用车型信息
	 * @author     廖
	 * @copyright 2018-1-3
	 * @return    LibFc::ReturnData(['status'=>false,'data'=>html]);
	 */
	function ajaxGetFitCarHtml()
	{
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['proId']))
		{
			$B2cBase = new B2cBase();
			//绑定车型
			$res = $B2cBase->get('bc_product_brand_link',['pbl_brand_id'],'and pbl_pro_id='.$Params['proId']);
			$brandId = array_column($res['data'], 'pbl_brand_id');
			// //一级车型
			// $res1 = $B2cBase->get('bc_product_model1_link',['pml1_mod1_id'],'and pml1_pro_id='.$Params['proId']);
			// //二级车型
			// $res2 = $B2cBase->get('bc_product_model2_link',['pml2_mod2_id'],'and pml2_pro_id='.$Params['proId']);
			//三级车型
			$res3 = $B2cBase->get('bc_product_model3_link',['pml3_mod3_id'],'and pml3_pro_id='.$Params['proId']);
			$modId = array_filter(array_column($res3['data'], 'pml3_mod3_id'),'LibFc::Int');
			if(!empty($brandId))
			{
				$ComModel = new ComModel();
				if(!empty($modId))
				{
					$ComModel = new ComModel();
					$where = sprintf(" and mod3_id in (%s) order by brand_seq, brand_initial, make_seq, make_initial, mod1_name, mod2_name, mod3_name", implode(',', $modId));
					$mres = $ComModel->getModel(3, ['*'], $where);
					if(!empty($mres['data']))
					{	
						$m3ids = array_column($mres['data'], 'mod3_id');
						//车型参数
						$modelPara = [];
						$where = sprintf(" and pml3_pro_id = %d and pml3_mod3_id in (%s) and pml3_remark != '' group by pml3_mod3_id, pml3_remark", $Params['proId'], implode(',', $m3ids));
						$res = $B2cBase->get('bc_product_model3_link', ['pml3_mod3_id', 'pml3_remark'], $where);
						foreach($res['data'] as $pv)
						{
							$modelPara[$pv['pml3_mod3_id']][] = $pv['pml3_remark'];
						}

						$where = sprintf(" and pmp_pro_id = %d and pmp_mod3_id in (%s) and pmp_info != '' group by pmp_mod3_id, pmp_info", $Params['proId'], implode(',', $m3ids));
						$res = $B2cBase->get('bc_product_model3_para', ['pmp_mod3_id', 'pmp_info'], $where);
						foreach($res['data'] as $pv)
						{
							$modelPara[$pv['pmp_mod3_id']][] = $pv['pmp_info'];
						}


						$makeCount = [];
						$brandCount = [];
						$brandArr = [];
						$newArr = [];
						foreach ($mres['data'] as $key => $value) 
						{
							$makeCount[$value['brand_id']][$value['make_id']][$value['mod3_id']] = ['mod3_name' =>$value['mod3_name']];

							$brandCount[$value['brand_id']][$value['mod3_id']] = ['mod3_name' =>$value['mod3_name']];

							$brandArr[$value['brand_id']] = ['brand_name' =>$value['brand_name'],'brand_code' => $value['brand_code']];
							
							$newArr[$value['brand_id']][$value['make_id']][$value['make_id']]=['make_name'=>$value['make_name'],'make_show_brand'=>$value['make_show_brand'],'brand_name'=>$value['brand_name']];
							$newArr[$value['brand_id']][$value['make_id']]['son'][$value['mod2_id']][$value['mod2_id']] = ['mod2_name' =>$value['mod2_name']];
							$newArr[$value['brand_id']][$value['make_id']]['son'][$value['mod2_id']]['son'][$value['mod3_id']] = [
								'mod3_name' =>$value['mod3_name'],
								'mod3_start_year'=>$value['mod3_start_year'],
								'mod3_end_year'=>$value['mod3_end_year'],
								'mod3_fuel'=>$value['mod3_fuel'],
								'mod3_para'=>empty($modelPara[$value['mod3_id']])? '': implode(';', array_unique($modelPara[$value['mod3_id']]))
							];
						}

					}
				}
			}
			foreach ($makeCount as $key => $value) 
			{
				$makeCount[$key] = array_map('count', $value);
			}
			// print_r($newArr);
			$brandCount = array_map('count', $brandCount);
			LibTpl::Set('brandArr',$brandArr);
			LibTpl::Set('newArr',$newArr);
			LibTpl::Set('makeCount',$makeCount);
			LibTpl::Set('brandCount',$brandCount);
			$result=LibTpl::Fetch('item/ajaxGetFitCarHtml.php');
			$status = ['status'=>true,'data'=>$result];
			LibFc::ajaxJsonEncode($status);
		}
		else
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确!']);
		}
	}


	/**
	 * @method    获取参考号码信息
	 * @author     xu
	 * @copyright 2018-1-11
	 * @return    ['status'=>false,'data'=>html]);
	 */
	function showfitNumberList()
	{
		// 参数
		$Params = mvc::$URL_PARAMS;
		if(empty($Params['proId']) || !LibFc::Int($proId = $Params['proId']))
			LibFc::ajaxJsonEncode(['status'=>true,'data'=>'']);

		// 参考号码
		$B2cBase = new B2cBase();
		$where = sprintf(" and num_self=0 and num_pro_id=%s order by num_factory, num_format", $proId);
		$res = $B2cBase->get('bc_number', ['num_id', 'num_factory', 'num_display', 'num_format', 'num_ismain'],$where);
		$proNum = $res['data'];
		if(count($proNum))
		{
			$proNum = array_chunk($proNum,ceil(count($proNum)/3)); // 拆成三组
			LibTpl::Set('proNum',$proNum);// 传递数据
		}
		$res = LibTpl::Fetch('item/showfitNumberList.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$res]);
	}

	/**
	 * @method    获取运费城市列表
	 * @author 卢
	 * @copyright 2017-07-31
	 */
	function ajaxGetTemplateHtml()
	{
		$Params = mvc::$URL_PARAMS;
		// print_r($Params);
		$YpwAddr=new YpwAddr();
		$data=$YpwAddr->getAddrTree();
		LibTpl::Set('tplId',(int)$Params['tplId']);
		LibTpl::Set('selectId',(int)$Params['selectId']);
		LibTpl::Set('selectCity',(int)$Params['selectCity']);
		LibTpl::Set('list',$data['data']);
		$result=LibTpl::Fetch('item/ajaxGetTemplateHtml.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$result]);
	}
	/**
	 * @method    获取某个城市的运费
	 * @author 卢
	 * @copyright 2017-07-31
	 */
	function getFrtContent()
	{
		$B2cBase = new B2cBase();
		$Params = mvc::$URL_PARAMS;
		$tplId=$Params['tplId'];
		$ftl_city=$Params['ftl_city'];
		if(LibFc::Int($tplId)&&LibFc::Int($ftl_city))
		{
			$tplData=$B2cBase->get('sh_freight_tpl_link',['*'],' and ftl_frt_id='.$tplId);
			$result=array();
			// print_r($tplData['data']);
			$method=array();
			foreach ($tplData['data'] as $k => $v)
			{
				if(in_array($v['ftl_shipping_method'], $method)) continue;
				$cityArr=explode(',', $v['ftl_cities']);
				$name=$v['ftl_shipping_method']>0 ? 'EMS' : '快递';
				$result[$v['ftl_shipping_method']]['name']=$name;
				if($v['ftl_default']=='Y'&&!in_array($ftl_city, $cityArr))
				{
					$result[$v['ftl_shipping_method']]['price']=sprintf('%.2f',$v['ftl_begin_money']);
					continue;
				}
				if(in_array($ftl_city, $cityArr))
				{			
					$result[$v['ftl_shipping_method']]['price']=sprintf('%.2f',$v['ftl_begin_money']);
					$method[]=$v['ftl_shipping_method'];
					continue;			
				}

				
			}
			LibFc::ajaxJsonEncode(['status'=>true,'data'=>$result]);
		}
	}

	/**
	 * @method    添加商品到购物车
	 * @author xu
	 * @copyright 2017-08-01
	 * @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	 */
	function addUserShopCart()
	{	
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();

		$B2cShoppingCart = new B2cShoppingCart();
		//参数检测
		if(!LibFc::Int($_POST['GoodNum'])||!LibFc::Int($_POST['thisGoodsId']))
		{	
			$msg = array('status'=>false,'data'=>'参数错误！','code'=>0);
			return LibFc::ajaxJsonEncode($msg);
		}

		// 保存
		$B2cShoppingCart = new B2cShoppingCart();
		$B2cShoppingCart->addCart($_POST['thisGoodsId'],$_SESSION['_userid'],$_POST['GoodNum']);

		// 调用接口获取当前购物车数量
		$res = $B2cShoppingCart->getCarGoodNum($_SESSION['_userid']);

		if($res['data'])
		{	
			$array = array('status'=>true,'data'=>$res['data'],'code'=>0);
			LibFc::ajaxJsonEncode($array);
		}
		
	}
	/**
	 * @method    检查用户是否有购买收藏加入购物车的权限（是否自己店铺配件）
	 * @author 卢
	 * @copyright 2017-09-15
	 */
	public function checkProPermi()
	{
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$B2cBase = new B2cBase();
		$Params = mvc::$URL_PARAMS;
		$res=['status'=>false,'data'=>'配件不存在'];
		if(LibFc::Int($Params['proId']))
		{
			//获取配件的所属店铺ID
			$where=sprintf(' and pro_id=%d',$Params['proId']);
			$shopInfo=$B2cBase->get('bc_product',['pro_shop_id'],$where,true);
			if($shopInfo['data']['pro_shop_id']==$_SESSION['_shopid'])
			{
				if($Params['type']=='buy'||$Params['type']=='addCart')
				{
					$res['data']='不能购买自己店铺的配件';
				}
				else if($Params['type']=='coll')
				{
					$res['data']='不能收藏自己店铺的配件';
				}else if($Params['type']=='collShop')
				{
					$res['data']='不能收藏自己的店铺';
				}
			}
			else
			{
				$res=['status'=>true,'data'=>true];
			}
		}
		LibFc::ajaxJsonEncode($res);	
	}
	/**
	 * @method    ajax添加浏览历史以及获取价格满减等信息
	 * @author 卢
	 * @copyright 2017-10-16
	 */
	public function getItemInfo()
	{
		$Params = mvc::$URL_PARAMS;
		//如果已经登录，获取当前用户购物车数据,用于显示购物车商品数量+添加浏览历史
		$B2cProduct = new B2cProduct();
		$YpwAddr = new YpwAddr();
		$B2cBase = new B2cBase();

		if(LibFc::Int($Params['proId']))
		{
			// 浏览历史
			$B2cHistory = new B2cHistory();
			$B2cHistory->addUserProHistory($_SESSION['_userid'],$Params['proId'],!empty($_SESSION['_shopid'])?$_SESSION['_shopid']:0);
			// 商品
			$res = $B2cProduct->getProduct(['*'], sprintf(" and pro_id = %d", $Params['proId']), true);
			$proArr['base'] = $res['data'];
			// 如果配件参与满减，获取店铺满减信息
			if($proArr['base']['pro_manjian']=='Y')
			{
				$sh_manjian_msg = $B2cBase->get('sh_manjian',['*'],sprintf(" and man_shop_id=%d and man_btime < %d and man_etime > %d ", $proArr['base']['pro_shop_id'],time(),time()));
				$sh_manjian_msg = $sh_manjian_msg['data'];
				$data['sh_manjian_msg']=$sh_manjian_msg;
			}
			$res = $B2cBase->get('sh_shop', ['shop_uid, shop_name, shop_pct_ids, shop_license, shop_describe_score, shop_service_score, shop_logistics_score, shop_reg_time,shop_baoyou'], sprintf(" and shop_id=%d", $proArr['base']['pro_shop_id']), true);
			$shopArr = $res['data'];
			$res = $YpwAddr->getAddrByIds($shopArr['shop_pct_ids']);
			$shopArr['shop_pct_ids'] = explode(',', $shopArr['shop_pct_ids']);
			$shopArr['PCT'] = $res['data'];
			$data['shopArr']=$shopArr;			
			//累计评价
			if(LibFc::Int($Params['proId']))
			{
				$evaluateData=$B2cBase->get('or_evaluate_product',['count(*) count'],' and evp_pro_id='.$Params['proId'],true);
				$result['data']['evaluate']=$evaluateData['data']['count'];
			}
			$dataCount = $B2cBase->Get('us_product_collection',['count(*) as count'],' and prc_pro_id='.$proArr['base']['pro_id'],true);
			$proArr['base']['collCount'] = $dataCount['data']['count'];
			$data['proArr']=$proArr;
			LibTpl::Set('itemInfoData',$data);
			$result['status']=true;
			$result['data']['saleNum']=$proArr['base']['pro_sold_count'];
			$result['data']['collProCount']=$proArr['base']['collCount'];
			$result['data']['shop_baoyou']=sprintf('%.2f',$data['shopArr']['shop_baoyou']);
			$result['data']['manjian']=LibTpl::Fetch('/item/manjianTpl.php');
			$result['data']['price']=LibTpl::Fetch('/item/priceTpl.php');
			$result['data']['saleInfo']=LibTpl::Fetch('/item/saleTpl.php');
			LibFc::ajaxJsonEncode($result);			
		}
	}
	/**
	 * @method    ajax获取店铺套餐信息
	 * @author    廖
	 * @copyright 2017-10-19
	 */
	public function ajaxGetShopCombos()
	{
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['shopId']) && LibFc::Int($Params['proId']))
		{
			$B2cPack = new B2cPack();
			//首先找出配件套餐
			$packData = $B2cPack->get('bc_product_pack left join bc_product_pack_link on prpa_id=prpl_prpa_id left join sh_shop on prpa_shop_id=shop_id',['prpa_id','prpa_name','prpa_price'],sprintf(" and prpa_id not in(select prpl_prpa_id from bc_product_pack_link left join bc_product on prpl_pro_id=pro_id where pro_status<1 or pro_count<1) and prpa_shop_id=%d and prpl_pro_id=%d and shop_status>0 and %d between prpa_btime and prpa_etime order by prpa_id desc",$Params['shopId'],$Params['proId'],time()));
			$packData = array_combine(array_column($packData['data'], 'prpa_id'), $packData['data']);
			if(!empty($packData))
			{
				$pack = array_column($packData,'prpa_id','prpa_name');
				$packId = LibFc::Int($Params['packId']) && in_array($Params['packId'],$pack)?$Params['packId']:reset($pack);
				$res = $B2cPack->getProductPack($packId);
				if($res['status'])
				{
					//查询各个套餐配件的数量
					if(!empty($res['data']))
					{
						foreach ($res['data'] as $key => $value) 
						{
							$countArr[$key] = min(array_column($value, 'pro_count'));
						}
						LibTpl::Set('countArr',$countArr);
					}
					LibTpl::Set('pack',$pack);
					LibTpl::Set('count',count($res['data'][$packId]));
					LibTpl::Set('packId',$packId);
					LibTpl::Set('proId',$Params['proId']);
					LibTpl::Set('shopId',$Params['shopId']);
					LibTpl::Set('list',$res['data']);
					LibTpl::Set('packPrice',$packData[$packId]['prpa_price']);
					$data = LibTpl::Fetch('item/ajaxGetShopCombos.php');
					LibFc::ajaxJsonEncode(['status'=>true,'data'=>$data]);
				}
				else LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确!']);
			}
		}
		else LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确!'.$Params['shopId'].'/'.$Params['proId']]);
	}
	/**
	 * @method    ajax获取店铺组合信息
	 * @author    廖
	 * @copyright 2017-12-22
	 */
	public function ajaxGetProGroup()
	{
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['shopId']) && LibFc::Int($Params['proId']))
		{
			$B2cPack = new B2cPack();
			$groupData = $B2cPack->getGroupByPro($Params['shopId'],$Params['proId']);
			if($groupData['status'] && is_array($groupData['data']))
			{
				LibTpl::Set('name',$groupData['data'][0]['prg_name']);
				LibTpl::Set('proId',$Params['proId']);
				LibTpl::Set('list',$groupData['data']);
				$data = LibTpl::Fetch('item/ajaxGetProGroup.php');
				LibFc::ajaxJsonEncode(['status'=>true,'data'=>$data]);
			}
		}
		else LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确!'.$Params['shopId'].'/'.$Params['proId']]);
	}
	/**
	 * @method    ajax检验能否购买套餐
	 * @author    廖
	 * @copyright 2017-10-19
	 */
	public function ajacCheckedCanBuy()
	{
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		if(LibFc::Int($_POST['shopId']) && LibFc::Int($_POST['packId']) && LibFc::Int($_POST['num']))
		{
			if(isset($_SESSION['_shopid']) && $_SESSION['_shopid'] == $_POST['shopId'])
			{
				LibFc::ajaxJsonEncode(['status'=>false,'data'=>'不能购买自己店铺的配件!']);
			}else
			{
				if($_POST['order']=='addToCar')
				{
					$B2cShoppingCart = new B2cShoppingCart();
					$res = $B2cShoppingCart->addPackage($_POST['packId'],$_SESSION['_userid'],$_POST['num'],$isCheck=true);
					LibFc::ajaxJsonEncode($res);
				}
				if($_POST['order']=='buyNow')
				{
					LibFc::ajaxJsonEncode(['status'=>true,'data'=>true]);
				}
			}
		}else LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确']);
	}
	/**
	 * @method    ajax获取uid
	 * @author    廖
	 * @copyright 2017-10-25
	 */
	public function ajaxGetUid()
	{
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$_SESSION['_userid']]);
	}
	public function checkEdit()
	{
		$Params = mvc::$URL_PARAMS;
		$result=['status'=>true,'data'=>false];
		if((int) $Params['proId'])
		{
			$B2cBase = new B2cBase();
			if(isset($_SESSION['_shopid']))
			{
				$res=$B2cBase->get('bc_product',['count(1) count'],sprintf(' and pro_shop_id=%d and pro_id=%d',$_SESSION['_shopid'],$Params['proId']),true);
				if($res['data']['count'])
				{
					$result['data']=true;
				}
			}
		}
		LibFc::ajaxJsonEncode($result);
		exit();
	}
	/**
	 * @method 在商品搜索页的列表显示的添加到购物车按钮
	 * @author xu
	 * @copyright 2018-01-22
	 * @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	 */
	function addToCartFromList()
	{	
		// 校验登录状态
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$B2cShoppingCart = new B2cShoppingCart();

		$B2cBase = new B2cBase();
		$Params = mvc::$URL_PARAMS;
		//参数
		if(empty($Params['thisGoodsId']) || !LibFc::Int($Params['thisGoodsId'])) 
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
			exit();
		}
		$proId = $Params['thisGoodsId'];
		$proNum = (empty($Params['GoodNum']) || !LibFc::Int($Params['GoodNum'])) ? 1:$Params['GoodNum'];

		// 添加购物车
		$B2cShoppingCart->addCart($proId,$_SESSION['_userid'],$proNum);

		//购物车数量统计
		$res = $B2cShoppingCart->getCarGoodNum($_SESSION['_userid']);

		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$res['data']]);
	}
	function getTopList()
	{
		$B2cBase = new B2cBase();
		$Params = mvc::$URL_PARAMS;
		$res['data']=[];
		if(!empty($Params['config'])&&!empty($Params['shopId']))
		{
			$Params['config']=html_entity_decode($Params['config']);
			$shopId=$Params['shopId'];
			$config=json_decode($Params['config'],true);
			$B2cProduct=new B2cProduct();
			$B2cShopSort=new B2cShopSort();
			$source=['pro_id','pro_name','pro_sale_price','pro_promotion_price','pro_set_time','pro_add_time','pro_sold_count','pro_coll_count'];
			$table = 'bc_product';
			//配件分类
			$sortRes=$B2cShopSort->getAllShopSort($shopId);
			// print_r($sortRes);
			$cateRes=$B2cShopSort->getEndSortIds($sortRes['data'],$config['shopSort']);
			$cateId=array_unique($cateRes['data']);
			if(count($cateId))
			{
				// $cateProRes=$B2cShopSort->get('bc_product_sort',['prs_pro_id'],sprintf(' and prs_sort_id in(%s)',implode(',', $cateId)));
				$sortWhere= sprintf(" and prs_sort_id in(%s)",implode(',', $cateId));
				$table .= ' join bc_product_sort on prs_pro_id=pro_id';
			}
			// $sortWhere=count($cateId)>0?sprintf(' and prs_sort_id in(%s)',implode(',', $cateId)):'';
			$baseWhere=sprintf(' and pro_shop_id=%d and pro_status=1',$shopId);
			//价格范围
			$priceWhere='';
			if(count($config['price']))
			{
				$priceWhere.=sprintf(' and pro_sale_price>=%d',$config['price'][0]);
				$priceWhere.=(isset($config['price'][1])&&$config['price'][1]>0)?sprintf(' and pro_sale_price<=%d',$config['price'][1]):'';
			}
			$saleOrderBy=' order by pro_sold_count desc';
			$where=$baseWhere.$sortWhere.$priceWhere;
			$data=[];
			$collOrderBy=' order by pro_coll_count desc';
			if($Params['type']=='shop-itemTop-coll')
			{
				$where = $where.$saleOrderBy;
			}
			else
			{
				$where = $where.$collOrderBy;
			}
			$dataInfo=$B2cProduct->get($table,$source, $where.sprintf(' limit %d', $config['count']));
			$data=$dataInfo['data'];
			if(count($dataInfo['data']))
			{
				$proId=array_column($dataInfo['data'], 'pro_id');
				$proPic=$B2cProduct->getProductPic($proId, false);
				foreach ($data as $k => $v) 
				{
					$data[$k]=isset($proPic['data'][$v['pro_id']][0])?array_merge($data[$k],$proPic['data'][$v['pro_id']][0]):$data[$k];			
				}	
			}
			LibTpl::Set('type',$Params['type']);
			LibTpl::Set('config',$config);
			LibTpl::Set('data',$data);
			$res['data']=LibTpl::Fetch('/item/getTopList.php');
		}
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$res['data']]);
	}
	/**
	 * @method    卖家服务
	 * @author 卢
	 * @copyright 2018-04-24
	 */
	function notice()
	{
		$Params = mvc::$URL_PARAMS;
		if(LibFc::Int($Params['proId']))
		{
			$B2cBase = new B2cBase();
			$B2cProduct=new B2cProduct();
			$res=$B2cBase->get('bc_product join bc_product_info on pro_id=pri_pro_id',['pro_shop_id','pri_service_pdt_id','pro_name','pro_id','pro_sale_price'],sprintf(' and pro_id=%d and pro_status=1 and pro_count>0',$Params['proId']),true);
			if(empty($res['data']))
			{
				LibTpl::Error('卖家服务不存在');
				exit();
			}
			$picInfo=$B2cProduct->getProductPic($Params['proId']);
			if(!empty($picInfo['data']))
			{
				$res['data']=array_merge($res['data'],current($picInfo['data']));
			}
			$shopId=$res['data']['pro_shop_id'];
			$pptId=$res['data']['pri_service_pdt_id'];
			// print_r($res['data']);
			LibTpl::Set('proData',$res['data']);
			if(!empty($pptId))
			{
				$pdtArr=$B2cBase->get('bc_product_desc_tpl',['pdt_id','pdt_name','pdt_txt'],sprintf(' and pdt_id=%d and pdt_shop_id=%d',$pptId,$shopId),true);
				if(empty($pdtArr['data']))
				{
					LibTpl::Error('卖家服务不存在');
					exit();
				}
				LibTpl::Set('pdtArr',$pdtArr['data']);
			}
			$ShopBase = new ShopBase();
			$shopInfo = $ShopBase->getShopInfo($shopId,['shop_money_bail','shop_service','shop_service_status']);
			LibTpl::Set('shopInfoData', $shopInfo);
			$res=$B2cBase->get('sh_shop',['shop_id','shop_name','shop_money_bail','shop_service','shop_service_status'],sprintf(' and shop_id=%d',$shopId),true);
			if($res['data'])
			{
				$res['data']['serviceArr']=json_decode($res['data']['shop_service'],true);
				LibTpl::Set('data', $res['data']);
			}
			// print_r($res['data']);
			//店铺配置文件，取店铺头部
			if(file_exists(mvc::$cfg['ROOT'].'shop/'.$shopId.'/page.config.php'))
			{
				$pageConfigAll =include(mvc::$cfg['ROOT'].'shop/'.$shopId.'/page.config.php');
				$shopTopConfig=$pageConfigAll['public']['top'];
				$configArr=[];
				foreach ($shopTopConfig as $k => $v) 
				{
					if($v['module']=='shopInfo')
					{
						$configArr=$v;
						break;
					}
				}
				$res = $ShopBase->getModuleHtml($shopId, $configArr);
				$shopTopHtml=$res['html'];
				LibTpl::Set('shopTopHtml', $shopTopHtml);
			}
			$this->HEAD_CSSJS['css'][] = 'css/item.css';
			LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
			$headArr = [
				'title'=>'卖家服务-跑街的',
				'keyword'=>'',	
				'des'=>''
			];
			LibTpl::Set('headArr', $headArr);
			LibTpl::Put();
			exit;
		}
		LibTpl::Error('卖家服务不存在');
	}


	/**
	 * @method 商品详情信息
	 * @author zhengweihua
	 * @copyright 2022-08-09
	 */
	function desinfo()
	{
		$Params = mvc::$URL_PARAMS;
		$proId = (int) $Params['proId'];
		if(empty($proId)){
			LibTpl::Error('商品不存在');
		}
		$B2cBase = new B2cBase();
		$table = 'bc_product join bc_product_info on pro_id=pri_pro_id';
		$where = sprintf(' and pro_id=%d and pro_status=1',$proId);
		$res= $B2cBase->get($table,['pro_shop_id','pri_des','pro_name','pro_id'],$where,true);
		if(empty($res['data'])){
			LibTpl::Error('商品不存在');
		}
		$headArr = [
			'title'=>'商品详情-跑街的',
			'keyword'=>'',	
			'des'=>''
		];
		LibTpl::Set('headArr', $headArr);
		LibTpl::Set('proInfo', $res['data']);
		LibTpl::Put();
		exit;
	}

}




