<?php
class countAction extends baseAction
{

	function index()
	{
		$Params = MVC::$URL_PARAMS;
		$B2cBase=new B2cBase();
		$page=!empty($Params['page'])?(int)$Params['page']:1;
		$perPage=!empty($Params['perPage'])?(int)$Params['perPage']:20;
		//一个月前
		if(!empty($Params['limit-time']))
		{
			$temp=explode(' ~ ', $Params['limit-time']);
			$startTime=trim(strtotime($temp[0]));
			$endTime=trim(strtotime($temp[1]));
		}else{
			$startTime=strtotime('- 1 month');
			$endTime=strtotime('+1 month');
			$Params['limit-time']=date('Y-m',$startTime).' ~ '.date('Y-m',$endTime);
		}
		// print_r($Params);
		LibTpl::Set('Params',$Params);
		//获取订单配件
		$orderBy=' total desc,count desc';
		if(!empty($Params['orderBy']))
		{
			switch ($Params['orderBy']) 
			{
				case 'price-asc':
					$orderBy=' total asc';
					break;
				case 'price-desc':
					$orderBy=' total desc';
					break;
				case 'num-asc':
					$orderBy=' count asc';
					break;
				case 'num-desc':
					$orderBy=' count desc';
					break;
				default:
					$orderBy=' total desc,count desc';
					break;
			}
		}		
		$where=" and orp_status!='creat' and orp_status!='cancel' and ((orp_refund_status !='close') or orp_refund_status is null)";
		$where.=sprintf(' and ord_add_time between %d and %d',$startTime,$endTime);
		// echo $where;
		$table1='or_order_product inner join bc_product on pro_id=orp_pro_id inner join or_order on orp_ord_id=ord_id';
		//总数计算
		$res=$B2cBase->get($table1,['count(pro_part_id) count','pro_part_id'],$where.' group by pro_part_id');
		$total=count($res['data']);
		if($total>0)
		{
			$where .=sprintf(" group by pro_part_id order by %s limit %d,%d", $orderBy, ($page-1)*$perPage, $perPage);
			$res=$B2cBase->get($table1,['pro_part_id,sum(orp_money) total,sum(orp_count) count'], $where);
			$lists=$res['data'];
			$partArr=[];
			if(!empty($lists))
			{
				$partIdArr=array_column($lists, 'pro_part_id');
				$res=$B2cBase->get('bc_part',['part_id','part_name'],sprintf(' and part_id in(%s)',implode(',',$partIdArr)));
				$partArr=$res['data'];
				$partArr=array_column($partArr,null,'part_id');
			}
			LibTpl::Set('lists',$lists);
			LibTpl::Set('partArr',$partArr);
		}
		$Page = LibPage::Show($total, $perPage);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('title', '分类销售排行榜');
		LibTpl::Put();
	}
}