<?php
class indexAction
{
	//只能调用/static/目录下的 js | css | 控件[webuploader、datetimepicker、ueditor]
	private $HEAD_CSSJS = ['css'=>['css/style.css'], 'js'=>['js/index.js'], 'plugin'=>[]];

	function __construct()
	{
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
	}

	function index()
	{
		$Params = mvc::$URL_PARAMS;
		
		$B2cPart = new B2cPart();
		// 获取销售排行
		$res = $B2cPart->getSaleTopPart();
		$saleTop = $res['data'];
		//首页配置
		$cofArr = [
			'menuPart'=>[2996, 3006, 4006, 2984, 4007],
			//销售排行
			'saleTop'=>[
				'partIds'=>$saleTop
			],
			//易损及耗材
			'footFast'=>[
				'partIds'=>[2996, 3006, 4006]
			]
		];

		// 'partIds'=>[160, 36, 327, 57, 196]
		$res = $B2cPart->getAllPart();
		$allPartArr = $res['data'];

		$menuPartArr = [];
		foreach($cofArr['menuPart'] as $v)
		{
			if(!empty($allPartArr[$v]))
				$menuPartArr[$v] = $allPartArr[$v];
		}
		LibTpl::Set('menuPartArr', $menuPartArr);

		// 获取销售排行
		$res = self::getProductByPart(current($saleTop), 4);
		LibTpl::Set('saleTopFourByPart',$res['data']);
		//获取易损及耗材
		$res = self::getProductByPart(current($cofArr['footFast']['partIds']), 8);
		LibTpl::Set('footFastData',$res['data']);
		//获取特卖场配件
		$res = self::getProRoast(1, 5);
		LibTpl::Set('proRoast',$res['data']);

		
		
		//接口调用
		/*$YpwBase = new YpwBase();
		$Res = $YpwBase->Get('yp_user', ['u_id', 'u_name'], 'limit 10');  
		LibTpl::Set('UserArr', $Res['data']);*/
		
		//获取某个表的自增ID
		/*$B2cBase = new B2cBase();
		$Res = $B2cBase->GetTabelAutoId('bc_param_label');
		LibTpl::Set('AutoId', $Res['data']);*/

		//页面head
		$headArr = [
			'title'=>'跑街的-宜配商城',	
			'keyword'=>'宜配,B2C,宜配商城,跑街的',	
			'des'=>'跑街的-宜配商城(www.paojd.cn)是中国专业的汽配网，是集汽配数据、汽配服务和网络推广为一体的大型汽配门户网， 致力成为全球权威的汽车配件服务平台。'
		];
		// 取出yipart网（可售数量大于0且状态是售卖中的）全网销量前面10个
		$B2cProduct=new B2cProduct();
		//取出分类的名称
		$partIdArr = array_filter(array_merge($cofArr['saleTop']['partIds'],$cofArr['footFast']['partIds']),'LibFc::Int');

		if(!empty($partIdArr))
		{
			$res = $B2cProduct->get('bc_part',['part_id','part_name'],sprintf(' and part_id in(%s)',implode(',',$partIdArr)));
			$part = array_column($res['data'], 'part_name','part_id');
			$partData = $res['data'];
			// 现在按照数组排序
			if(!empty($cofArr['saleTop']['partIds']))
			{
				$saleTop = array();
				foreach ($cofArr['saleTop']['partIds'] as $key => $value) 
				{
					foreach ($partData as $kk => $vv)
					{
						if($vv['part_id']==$value)
						{
							$saleTop[] = $vv;
						}
					}	
				}
				LibTpl::Set('saleTop', $saleTop);
			}
			if(!empty($cofArr['footFast']['partIds']))
			{
				$footFast = array();
				foreach ($cofArr['footFast']['partIds'] as $key => $value) 
				{
					$footFast[$value] = $part[$value];
				}
				LibTpl::Set('footFastPart', $footFast);
			}
		}
		$saleOrderBy = sprintf(" and pro_status=1 and pro_count>0 order by pro_sold_count desc limit %d",10);
		//热销排行
		$saleInfo=$B2cProduct->get('bc_product',['pro_id','pro_name'],$saleOrderBy);
		$saleInfo = $saleInfo['data'];
		$allSaleInfoId = array();
		foreach ($saleInfo as $key => $value)
		{
			$allSaleInfoId[] = $value['pro_id'];
		}
		// 去除热销排行的相关图片
		$saleInfoPic = $B2cProduct->getProductPic($allSaleInfoId);
		$saleInfoPic = $saleInfoPic['data'];
		// 拼接获取热销前十的商品ID\PIC\NAME
		$allSaleInfoMsg = array();
		foreach ($saleInfo as $v)
		{
			foreach ($saleInfoPic as $kk => $vv)
			{
				if( $kk == $v['pro_id'])
				{
					$vv = current($vv);
					$allSaleInfoMsg[] = array(
						'pro_id' => $v['pro_id'],
						'pro_name' => $v['pro_name'],
						'pro_pic' => $vv['spi_path'].'100/'.$vv['spi_name']
					);
				}
			}
		}
		LibTpl::Set('allSaleInfoMsg', $allSaleInfoMsg);
		$partArr=include(mvc::$cfg['ROOT'].'/home/config/indexPart.php');
		// print_r($partArr);
		LibTpl::Set('partArr', $partArr);
		LibTpl::Set('headArr', $headArr);
		$this->HEAD_CSSJS['js'][] = 'js/slider.js';
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
		LibTpl::Set('bodyClass', 'homeBody');
		LibTpl::Set('index', true);
		LibTpl::Put();
	}

	/**
	  * @method 根据partId获取销售排行指定数量信息
	  * @author xu
	  * @copyright 2017/11/9
	  */
	private function getProductByPart($partId, $Count)
	{
		$B2cBase = new B2cBase();
		// 获取可售数、当前配件分类、
		$where = sprintf(" and pro_count>0 and pro_part_id=%d and shop_status=1 and pro_status>0  order by pro_sold_count desc limit %d",$partId, $Count);
		$res=$B2cBase->Get('bc_product left join sh_shop on pro_shop_id=shop_id',['pro_id','pro_shop_id','pro_name','pro_sale_price','pro_part_id'], $where);
		$proMsg = $res['data'];
		$shopIds = $res['data']?array_unique(array_column($res['data'],'pro_shop_id')):[];
		//取店铺权限
		$rulesArr = [];
		if($shopIds)
		{
			$B2cShop = new B2cShop();
			foreach ($shopIds as $key => $val) {
				$rules = $B2cShop->getGzhUserRule($val,$_SESSION['_userid']);
				$rulesArr[$val]= $rules['data']?array_column($rules['data'],'smr_code'):[];
			}
		}
		

		// 获取商品主图
		$proIds = array();
		foreach ($proMsg as $k => $v)
		{
			$shopRulesArr =$rulesArr[$v['pro_shop_id']];
			if(!in_array('item_price',$shopRulesArr)){
				unset($proMsg[$k]['pro_sale_price']);
			}
			$proIds[] = $v['pro_id'];
		}
		$B2cProduct = new B2cProduct();
		$res = $B2cProduct->getProductPic($proIds);
		$proPic = $res['data'];
		// 拼接到proMsg
		foreach ($proPic as $k => $v)
		{
			foreach ($proMsg as $kk => $vv)
			{
				if($vv['pro_id'] == $k)
				{
					$shopRulesArr =$rulesArr[$vv['pro_shop_id']];
					if(in_array('item_pic',$shopRulesArr)){
						$proMsg[$kk]['proPic'] = current($v);
					}
				}
			}
		}
		return LibFc::ReturnData(true,$proMsg);
	}
	/**
	  * @method 获取特卖场的分页
	  * @author 廖
	  * @copyright 2017/11/9
	  */
	private function getProRoast($startPage,$perPage)
	{
		if(!LibFc::Int($perPage)) return LibFc::ReturnData(true,[]);

		$B2cProduct = new B2cProduct();
		$count = $B2cProduct->get('bc_product',['count(*) count'],"and pro_status=1 and pro_count>0 and pro_host='Y'",true);
		if($startPage<=0) $startPage = $count['data']['count']+$startPage;
		if($startPage>$count['data']['count']) $startPage = $startPage-$count['data']['count'];
		
		if($count['data']['count']>0 && LibFc::Int($startPage))
		{
			$selData = ['pro_id','pro_name','pro_sale_price','pro_promotion_price','pro_promotion_btime','pro_promotion_etime'];
			$twhere = sprintf(" and pro_status=1 and pro_count > 0 and pro_host='Y' order by pro_sold_count desc,pro_id desc limit %d,%d",implode(',', $selData), ($startPage-1)*$perPage, $perPage);
			$res = $B2cProduct->get('bc_product', $selData, $twhere);
			$proIdArr = array_column($res['data'],'pro_id');
			if(!empty($proIdArr))
			{
				//合并数据
				$proImgData = $B2cProduct->getProductPic($proIdArr);
				foreach ($res['data'] as $key => $value) 
				{
					$res['data'][$key]['proPic'] =isset($proImgData['data'][$value['pro_id']][0])? $proImgData['data'][$value['pro_id']][0]:[];
				}
			}
			return $res;
		}

		return LibFc::ReturnData(true,[]);
	}
	/**
	  * @method 易损及耗材
	  * @author 廖
	  * @copyright 2017/11/9
	  */
	function ajaxGetfootFast()
	{
		if(LibFc::Int($_POST['partId']))
		{
			$res = self::getProductByPart($_POST['partId'], 8);
			LibTpl::Set('footFastData',$res['data']);
			$footFast = LibTpl::Fetch('index/ajaxGetfootFast.php');
			LibFc::ajaxJsonEncode(['status'=>true,'data'=>$footFast]);
		}
		else LibFc::ajaxJsonEncode(['status'=>false,'data'=>'参数不正确']);
	}
	/**
	  * @method 特卖场
	  * @author 廖
	  * @copyright 2017/11/9
	  */
	function ajaxGetProRoast()
	{
		$res = self::getProRoast($_POST['page'],5);
		LibTpl::Set('proRoast',$res['data']);
		$proRoast = LibTpl::Fetch('index/ajaxGetProRoast.php');
		LibFc::ajaxJsonEncode(['status'=>true,'data'=>$proRoast]);
	}
	/**
	  * @method ajax获取分类销售排行前四
	  * @author xu
	  * @copyright 2017/11/9
	  */
	function ajaxGetSaleTop()
	{
		$partId = $_POST['partId'];
		$res = self::getProductByPart($partId, 4);
		LibTpl::Set('proMsg',$res['data']);
		$data = LibTpl::Fetch('index/topFour.php');
		$msg = array('status'=>true,'data'=>$data);
		LibFc::ajaxJsonEncode($msg);
	}

	/**
	  * @method 图片验证码
	  * @author soul
	  * @copyright 2017/5/9
	  */
	function imgcode()
	{
		$Params = mvc::$URL_PARAMS;
		$OthCheckcode = new OthCheckcode();
		$CofArr = [];
		if(!empty($Params['type']))
		{
			switch($Params['type'])
			{
				case 'reg':
				case 'login': $CofArr = ['height'=>30, 'width'=>90]; break;
				case 'business': $CofArr = ['session_key'=>'BusinessImageCode','level'=>4,'height'=>30, 'width'=>80]; break;
			}
		}
		$OthCheckcode->getImgcode($CofArr);
	}
	
	/**
	  * @method 匹配验证码
	  * @author soul
	  * @copyright 2017/5/9
	  */
	function checkImgcode()
	{
		$Return = ['status'=>false, 'data'=>'验证码不正确', 'code'=>'code_error'];
		if($_SESSION['imgcode'] == strtoupper($_POST['val']))
		{
			$Return = ['status'=>true, 'data'=>'', 'code'=>''];
		}
		LibFc::ajaxJsonEncode($Return);
	}

	/**
	  * @method 发送手机验证码[图片验证码、登录两种发送渠道]
	  * @author soul
	  * @copyright 2017/5/9
	  */
	function sendMobilecode()
	{
		$Flag = false;
		$Mobile = trim($_POST['mobile']);
		$Act = $_POST['act'];
		
		if(!preg_match('/^1\d{10}$/', $Mobile))
		{
			$Return = ['status'=>false, 'data'=>'手机号码不正确', 'code'=>'mobile_error'];
			LibFc::ajaxJsonEncode($Return);
		}
		if(!in_array($Act, ['bind', 'unbind', 'password']))
		{
			$Return = ['status'=>false, 'data'=>'act 参数缺失', 'code'=>'act_error'];
			LibFc::ajaxJsonEncode($Return);
		}
		
		if(isset($_POST['imgcode']))
		{
			if($_SESSION['imgcode'] != strtoupper($_POST['imgcode']))
			{
				$Return = ['status'=>false, 'data'=>'图片验证码不正确', 'code'=>'imgcode_error'];
				LibFc::ajaxJsonEncode($Return);
			}
			else
			{
				$Flag = true;
			}
		}
		if(!empty($_SESSION['_userid']))
		{
			$Flag = true;
		}

		if(!$Flag)
		{
			$Return = ['status'=>false, 'data'=>'获取数据失败，请稍后重试。', 'code'=>'data_error'];
			LibFc::ajaxJsonEncode($Return);
		}

		$LibYpApi = new LibYpApi();
		$dataArr = [
			'mobile'=>$Mobile,	
			'style'=>$Act,
			'from'=>'PJD',
			'again'=>$_POST['count']
		];
		$Res = $LibYpApi->Get('sms/sendMobileCode', $dataArr, [], true);
		if($Res['status'])
		{
			$Return = ['status'=>true, 'data'=>'', 'code'=>''];
		}
		else
		{
			$Return = ['status'=>false, 'data'=>$Res['data'], 'code'=>'send_error'];
		}
		LibFc::ajaxJsonEncode($Return);
	}

	/**
	  * @method 短信验证码匹配
	  * @author soul
	  * @copyright 2017/5/9
	  */
	function checkMobilecode()
	{
		$Return = ['status'=>false, 'data'=>'短信校验码不正确', 'code'=>'code_error'];
		if(!empty($_POST['mobile']) && preg_match('/^1\d{10}$/', trim($_POST['mobile'])) && !empty($_POST['code']) && preg_match('/^\d{6}$/', trim($_POST['code'])))
		{
			$LibYpApi = new LibYpApi();
			$dataArr = [
				'mobile'=>$_POST['mobile'],	
				'style'=>$_POST['act'],
				'from'=>'PJD',
				'code'=>$_POST['code'],
			];
			$Res = $LibYpApi->Get('sms/checkMobileCode', $dataArr, [], true);
			if($Res['status'])
			{
				$Return = ['status'=>true, 'data'=>true, 'code'=>''];
			}
		}
		LibFc::ajaxJsonEncode($Return);
	}


	/**
	  * @method 获取店铺的模块样式
	  * @author soul
	  * @copyright 2017/9/13
	  */
	function getShopCss()
	{
		header('Content-type: text/css');
		$Params = mvc::$URL_PARAMS;
		$txt = '/**店铺模块**/';
		if(!empty($Params['val']))
		{
			foreach(explode(',', $Params['val']) as $val)
			{
			    // 年检
			    if (false !== strpos($val, '/etc/passwd')) {
                    header("http/1.1 404 not found"); exit;
                }

				$file = mvc::$cfg['ROOT_SHOP_SYS'].'static/css/'.$val;
				if(file_exists($file))
				{
					$txt .= file_get_contents($file);
				}
			}
		}
		
		echo $txt;
	}


	/**
	  * @method 获取店铺的模块JS
	  * @author soul
	  * @copyright 2017/9/13
	  */
	function getShopJs()
	{
		header('Content-type: text/javascript');
		$Params = mvc::$URL_PARAMS;
		$txt = '/**店铺模块**/';
		if(!empty($Params['val']))
		{
			foreach(explode(',', $Params['val']) as $val)
			{
                // 年检
                if (false !== strpos($val, '/etc/passwd')) {
                    header("http/1.1 404 not found"); exit;
                }

				$file = mvc::$cfg['ROOT_SHOP_SYS'].'static/js/'.$val;
				if(file_exists($file))
				{
					$txt .= file_get_contents($file);
				}
			}
		}
		echo $txt;
	}
}