<?php
/**
  * @method 购物车
  * @author soul 2017/7/26
  */
class cartAction
{
	private $HEAD_CSSJS = ['css'=>['css/cart.css'], 'js'=>['js/cart.js'], 'plugin'=>[]];

	function __construct()
	{
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
	}


	/**
	  * @method 购物车
	  * @author soul 2017/7/26
	  */
	function index()
	{
		//检验登陆状态
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$B2cBase = new B2cBase();		
		//获取当前用户购物车信息
		$Params = mvc::$URL_PARAMS;
		$B2cShoppingCart = new B2cShoppingCart();

		// 配件数据
		$res = $B2cShoppingCart->getUserCartInfo($_SESSION['_userid'],!empty($Params['depre']));
		LibTpl::Set('cartPro', $res['data']);
		
		// 选中的商品ID
		$res = $B2cBase->get('us_cart',['car_pro_id'],sprintf(' and car_uid=%d and car_checked=1 and car_prpa_id=0',$_SESSION['_userid']));
		LibTpl::Set('selectedPro',array_column($res['data'], 'car_pro_id'));

		// 选中的套餐ID
		$res = $B2cBase->get('us_cart',['car_prpa_id'],sprintf(' and car_uid=%d and car_checked=1 and car_prpa_id!=0',$_SESSION['_userid']));
		LibTpl::Set('selectedPrpa',array_column($res['data'],'car_prpa_id'));

		// 统计购物车中降价商品数量
		$res = $B2cShoppingCart->getCarGoodNum($_SESSION['_userid'],true);
		LibTpl::Set('countDepre',$res['data']);

		// 统计购物车全部配件数量
		$res = $B2cShoppingCart->getCarGoodNum($_SESSION['_userid']);
		LibTpl::Set('countPro',$res['data']);

		//我的收藏
		$where=sprintf(' and prc_uid=%d and prc_add_time>=%d and shop_status>0 and pro_count>0',$_SESSION['_userid'],(time()-7*24*60*60));
		$where.=isset($_SESSION['_shopid'])?sprintf(' and pro_shop_id!=%d ',$_SESSION['_shopid']):'';
		$collData=$B2cBase->get('us_product_collection left join bc_product on prc_pro_id=pro_id left join sh_shop on shop_id=pro_shop_id',['count(1) count'],$where,true);
		// 浏览历史
		$where2=sprintf(' and prh_uid=%d and shop_status>0',$_SESSION['_userid']);
		$where2.=isset($_SESSION['_shopid'])?sprintf(' and pro_shop_id!=%d',$_SESSION['_shopid']):'';
		$hisData=$B2cBase->get('us_product_history left join bc_product on prh_pro_id=pro_id left join sh_shop on shop_id=pro_shop_id',['count(1) count'],$where2,true);
		// 猜您喜欢
		$where3=' and pro_status>0 and shop_status>0';
		$where3.=isset($_SESSION['_shopid'])?sprintf(' and pro_shop_id!=%d',$_SESSION['_shopid']):'';
		$likeData=$B2cBase->get('bc_product left join sh_shop on pro_shop_id=shop_id',['count(1) count'],$where3,true);

		LibTpl::Set('proNum',['coll'=>$collData['data']['count'],'hist'=>$hisData['data']['count'],'like'=>$likeData['data']['count']]);
		//设置meta信息
		$headArr = [
			'title'=>'购物车-跑街的',	
			'keyword'=>'',	
			'des'=>''
		];
		// 用户ID
		LibTpl::Set('fromUid',$_SESSION['_userid']);
		// 友好提示
		LibTpl::Set('msg',empty($Params['depre'])?'您的购物车是空的！快去选购吧。':'购物车中无符合条件的配件！快去选购吧。');

		LibTpl::Set('ComTitle','购物车');
		//添加animate样式库
		$this->HEAD_CSSJS['plugin'][] = 'animate';
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
		LibTpl::Set('headArr', $headArr);
		LibTpl::Set('Params', $Params);		
		LibTpl::Put();
	}

	/**
	 * @method ajax设置店铺购物车商品数量
	 * @param  $_POST['PRONUM']; 商品数量 int
	 * @param  $_POST['PROID']; 商品ID int
	 * @author     xu
	 * @copyright 2017-08-07
	 * @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	 */
	public function setCartShopNum()
	{
		//检验登陆状态
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();

		//参数
		if(empty($_POST['PRONUM']) || !LibFc::Int($num = $_POST['PRONUM']) || empty($_POST['PROID']) || !LibFc::Int($proId = $_POST['PROID']))
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		}

		//执行
		$B2cBase = new B2cBase();
		$B2cBase->set("us_cart",['car_count'=>$num],sprintf(" and car_pro_id=%d and car_uid=%d",$proId,$_SESSION['_userid']));

		// 返回
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);
	}



	/**
	 * @method ajax设置店铺购物车的配件套餐数量
	 * @param  $_POST['prpaId']; 商品数量 int
	 * @param  $_POST['num']; 商品ID int
	 * @author     xu
	 * @copyright 2017-08-07
	 * @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	 */
	public function setCartPackNum()
	{
		//登录
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();

		//参数
		if(empty($_POST['num']) || !LibFc::Int($num = $_POST['num']) || empty($_POST['prpaId']) || !LibFc::Int($prpaId = $_POST['prpaId']))
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		}

		// 执行
		$B2cBase = new B2cBase();
		$B2cBase->set('us_cart',['car_count'=>$num],sprintf(" and car_prpa_id=%d and car_uid=%d",$prpaId,$_SESSION['_userid']));

		// 返回
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);	
	}



	/**
	 * @method    ajax删除购物车商品
	 * @param  $_POST['PROID']; 商品ID int
	 * @author     xu
	 * @copyright 2017-08-07
	 * @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	 */
	public function delShoppingCart()
	{
		//登录
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();

		//参数
    	if( empty($_POST['PROID']) || !LibFc::Int($proId = $_POST['PROID']))
		{
			LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		}

		// 执行
		$B2cShoppingCart = new B2cShoppingCart();
		$B2cShoppingCart->delShoppingCart([$proId],$_SESSION['_userid']);

		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);
	}

	/**
	 * @method    ajax删除配件套餐
	 * @param  $_POST['prpa_id']; 商品ID int
	 * @author     xu
	 * @copyright 2017-08-07
	 * @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	 */
	public function delPackCart()
	{
		//检验登陆状态
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		//参数判断
    	if(empty($_POST['prpa_id']) || !LibFc::Int($prpaId = $_POST['prpa_id']))
    		LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
    	
		$B2cShoppingCart = new B2cShoppingCart();
		$B2cShoppingCart->delPackage([$prpaId],$_SESSION['_userid']);
		
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);
	}

	/**
	  * @method 收藏商品
	  * @author xu 2017/8/7
	  */
	function collPro()
	{
		//检验登陆状态
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$B2cCollPro = new B2cCollPro();
		$B2cShoppingCart = new B2cShoppingCart();
		//参数判断
    	if(empty($_POST['proId'])||!($proId = LibFc::Int($_POST['proId']))) LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		//添加收藏
		$B2cCollPro->addUserCollPro($_SESSION['_userid'],$proId);
		//删除购物车商品
		$B2cShoppingCart->delShoppingCart([$proId],$_SESSION['_userid']);

		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);
	}

   /**
	* @method 更改购物车商品选中状态
	* @author xu
	* @copyright 2017/8/11
	* @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	*/
	function togchecked()
	{
		//检验登陆状态
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$B2cBase = new B2cBase();
		//对传过来的status做状态判定
		if(!LibFc::Int($pro_id = $_POST['pro_id'])) LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		$check = (!empty($_POST['STATUS']) && ($_POST['STATUS'] == 'on'))?1:0;
		$B2cBase->set('us_cart',['car_checked'=>$check],sprintf(" and car_pro_id=%d and car_uid=%d ",$pro_id,$_SESSION['_userid']));
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);
	}



   /**
	* @method 更改配件套餐选中状态
	* @author xu
	* @copyright 2018/02/03
	* @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	*/
	function togPackChecked()
	{
		//登录
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$B2cBase = new B2cBase();
		//类型判定
		if(empty($_POST['prpaId']) || !LibFc::Int($prpaId = $_POST['prpaId'])) LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		$where = sprintf(" and car_prpa_id=%d and car_uid=%d ",$prpaId,$_SESSION['_userid']);
		// 选中
		$checked = ( !empty($_POST['STATUS']) && ($_POST['STATUS']=='on') )?1:0;
		$B2cBase->set("us_cart",['car_checked'=>$checked],$where);
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);
	}



   /**
	* @method 店铺全选时候更改店铺商品状态
	* @author xu
	* @copyright 2017/8/11
	* @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	*/
	function togShopchecked()
	{
		//登录
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$B2cBase = new B2cBase();
		//参数
		if(empty($_POST['shop_id']) || !LibFc::Int($shop_id = $_POST['shop_id'])) LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		$checked = (!empty($_POST['STATUS']) && $_POST['STATUS']=='on' )?1:0;
		// 商品
		$where = sprintf(" and pro_shop_id=%d and car_uid=%d ",$shop_id,$_SESSION['_userid']);
		$res = $B2cBase->get("us_cart left join bc_product on pro_id=car_pro_id",['*'],$where);
		$proIds = array_column($res['data'], 'car_pro_id');
		if(!empty($proIds))
		{
			$B2cBase->set('us_cart',['car_checked'=>$checked],sprintf(" and car_pro_id in (%s) and car_uid=%d ",implode(',',$proIds),$_SESSION['_userid']));
		}
		// 套餐
		$res = $B2cBase->get('us_cart left join bc_product_pack on car_prpa_id=prpa_id',['prpa_id'],sprintf(" and prpa_shop_id=%d and car_uid=%d ",$shop_id,$_SESSION['_userid']));
		$prpaIds = array_column($res['data'], 'prpa_id');
		if(!empty($prpaIds))
		{
			$B2cBase->set('us_cart',['car_checked'=>$checked],sprintf(" and car_prpa_id in (%s) and car_uid=%d ",implode(',',$prpaIds),$_SESSION['_userid']));
		}
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);
	}


   /**
	* @method 购物车商品全选更改状态
	* @author xu
	* @copyright 2017/8/11
	* @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	*/
	function togAllchecked()
	{
		//登录
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$B2cBase = new B2cBase();
		//参数
		$checked = (!empty($_POST['STATUS']) && $_POST['STATUS']=='on' )?1:0;
		// 执行
		$B2cBase->set('us_cart',['car_checked'=>$checked],sprintf(" and car_uid=%d ",$_SESSION['_userid']));
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);
	}

	/**
	 * @method ajax删除购物车商品
	 * @param  $_POST['allGodIds']; 商品ID array
	 * @author     xu
	 * @copyright 2017-08-07
	 * @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	 */
	public function settlementDel()
	{
		//检验登陆状态
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$B2cBase = new B2cBase();
		//商品
		if(!empty($_POST['allGodIds']) && is_array($_POST['allGodIds']) && !empty($proIds=array_filter($_POST['allGodIds'],"LibFc::Int")))
		{
			$B2cBase->del('us_cart',$where=sprintf(' and car_uid=%d and car_pro_id in (%s) ',$_SESSION['_userid'],implode(",", $proIds)));	
		}
		// 套餐
		if(!empty($_POST['allPrpaIds']) && is_array($_POST['allPrpaIds']) && !empty($prpaId=array_filter($_POST['allPrpaIds'],"LibFc::Int")))
		{
			$B2cBase->del('us_cart',$where=sprintf(' and car_uid=%d and car_prpa_id in (%s) ',$_SESSION['_userid'],implode(",", $prpaId)));
		}
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);		
	}


	
	/**
	 * @method 点击底部收藏按钮收藏选中商品
	 * @param  $_POST['PROID']; 商品ID int
	 * @author xu
	 * @copyright 2017-08-07
	 * @return 成功：{'status':true,'data':'success','code':0} 失败：{'status':false,'data':'error'/'参数错误！','code':0}
	 */
	public function settlementColl()
	{
		//登录
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		//参数
		if(empty($_POST['allGodIds'])||!is_array($_POST['allGodIds'])||empty($proIds=array_filter($_POST['allGodIds'],'LibFc::Int'))) LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		//收藏
		$B2cCollPro = new B2cCollPro();
		$res = $B2cCollPro->addUserCollPro($_SESSION['_userid'],$proIds);
		//删除
		$B2cShoppingCart = new B2cShoppingCart();
		$B2cShoppingCart->delShoppingCart($proIds,$_SESSION['_userid']);
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>'success']);
	}
	/**
	 * @method    购物车底部配件列表
	 * @author 卢
	 * @copyright 2017-11-02
	 */
	public function getProList()
	{
		//检验登陆状态
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$Params = mvc::$URL_PARAMS;
		$nowPage=isset($Params['page'])?$Params['page']:1;
		$perPage=5;
		$start=time()-(24*60*60)*7;//7天前时间戳
		switch ($Params['type']) 
		{
			case 'coll':
				$B2cCollPro=new B2cCollPro();
				$where=sprintf(' and prc_uid=%d and prc_add_time>=%d and pro_status>0 and pro_count>0 and shop_status=1',$_SESSION['_userid'],$start);
				$where.=isset($_SESSION['_shopid'])?sprintf(' and pro_shop_id !=%d',$_SESSION['_shopid']):'';
				// $where=sprintf(' and prc_uid=%d order by pro_coll_count desc',$_SESSION['_userid']);
				$count=$B2cCollPro->get('us_product_collection left join bc_product on prc_pro_id=pro_id left join sh_shop on shop_id=pro_shop_id',['count(1) count'],$where,true);
				// print_r($count);
				$total=$count['data']['count']>=(5*$perPage)?5:ceil($count['data']['count']/$perPage);
				$res=$B2cCollPro->getUserCollProList($where.' order by pro_coll_count desc',$nowPage,$perPage,['pro_sold_count','pro_coll_count']);
				// print_r($res);
				break;
			case 'history':
				$B2cHistory= new B2cHistory();
				$B2cProduct=new B2cProduct();
				$table='us_product_history left join bc_product on prh_pro_id=pro_id left join sh_shop on shop_id=pro_shop_id';
				$where=isset($_SESSION['_shopid'])?sprintf(' and prh_uid=%d and pro_shop_id !=%d and shop_status>0 and pro_status>0',$_SESSION['_userid'],$_SESSION['_shopid']):sprintf(' and prh_uid=%d and shop_status>0',$_SESSION['_userid']);
				$count=$B2cHistory->get('us_product_history left join bc_product on prh_pro_id=pro_id left join sh_shop on shop_id=pro_shop_id',['count(1) count'],$where,true);
				$res = $B2cHistory->get($table, ['*'], $where.sprintf(" order by prh_ltime desc limit %d,%d",($nowPage-1)*$perPage, $perPage));
				$total=$count['data']['count']>=(5*$perPage)?5:ceil($count['data']['count']/$perPage);
				$proArr=array_column($res['data'], 'pro_id');
				if(count($proArr))
				{
					$picArr=$B2cProduct->getProductPic($proArr);
					foreach ($res['data'] as $k=> $v) 
					{
						$res['data'][$k]=isset($picArr['data'][$v['pro_id']][0])?array_merge($res['data'][$k],$picArr['data'][$v['pro_id']][0]):$res['data'][$k];
					}
				}
				break;
			case 'like':
				$B2cHistory= new B2cHistory();
				$where = isset($_SESSION['_shopid'])?sprintf(' and pro_shop_id !=%d and pro_status>0 and pro_count>0 and shop_status=1',$_SESSION['_shopid']):'and pro_status>0 and pro_count>0 and shop_status=1';
				$count=$B2cHistory->get('bc_product left join sh_shop on pro_shop_id=shop_id',['count(1) count'],$where,true);
				$total=$count['data']['count']>=(5*$perPage)?5:ceil($count['data']['count']/$perPage);
				$res=$B2cHistory->getGuessLovely($_SESSION['_userid'],$perPage,$nowPage,$where,['pro_sold_count','pro_coll_count']);				
				break;
		}
		LibTpl::Set('page',$nowPage);
		LibTpl::Set('pageTotal',$total);
		LibTpl::Set('proArr',$res['data']);
		$result=LibTpl::Fetch('/cart/carProList.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$result]);
	}
	
	/**
	 * @method 点击获取相似宝贝
	 * @author xu
	 * @copyright 2017-11-02
	 */
	public function showThisLikeGodWrap()
	{
		//检验登陆状态
		$OthCheck = new OthCheck();
		$OthCheck->mustLogin();
		$B2cBase = new B2cBase();
		$B2cHistory= new B2cHistory();
		// 参数
		if(empty($_POST['partId'])||!LibFc::Int($partId=$_POST['partId'])||empty($_POST['proId'])||!LibFc::Int($proId=$_POST['proId']))
		LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数错误！']);
		// 页码
		$perPage=6;
		$nowPage = (!empty($_POST['nowPage']) && LibFc::Int($_POST['nowPage']))?$_POST['nowPage']:1;
		// 数量
		$res = $B2cBase->get('bc_product left join sh_shop on pro_shop_id=shop_id ',['count(*) pro_sum'],sprintf(' and pro_part_id =%d and pro_count>0 and pro_id != %d and shop_status=1 and pro_status>0 ',$partId,$proId),true);
		$sum = $res['data']['pro_sum'];
		if(!$sum) LibFc::ajaxJsonEncode(['status'=>false,'data'=>'无相似宝贝！']);
		// 数据
		$res=$B2cHistory->showThisLikeGodWrap($partId,$proId,$perPage,$nowPage,$where);
		LibTpl::Set('page',$nowPage);
		LibTpl::Set('proId',$proId);
		LibTpl::Set('partId',$partId);
		// 计算总页数(向下取整加一)
		LibTpl::Set('pageNum',ceil($sum/$perPage)>8 ? 8 : ceil($sum/$perPage));
		LibTpl::Set('proArr',$res['data']);
		// 返回
		$res=LibTpl::Fetch('/cart/showThisLikeGodWrap.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$res]);
	}
}