<?php
/**
 * @link         http://www.openzc.cn/
 * @author       hexipeng | e-mail:2017412656@qq.com
 * @copyright    Copyright (c) 2020, Openzc, Inc.
 * @license      http://www.openzc.cn/license.txt
 */
class product {
    private $parameter=[];

	/*获取商品列表*/
	function get_product_list($GET,$parameter=[]){
		$this->parameter=$parameter;
		if($parameter['flag'] && $parameter['page']!=true){
			$sql=$this->get_flag_products($GET,$parameter);
		}else{
			$sql=$this->get_filter_search($GET,$parameter);
		}

		return $this->show_products_list($GET,$sql,$this->parameter);
	}
	
	//调用标签商品列表：特价，推荐，最新，促销
	function get_flag_products($GET=[],$parameter=[]){
		global $predata_class;
		$orderby=$parameter['orderby'][0].$parameter['orderby'][1]." ".$parameter['orderby'][2];
		
		$limit=$parameter['row'];
		$field="pd.products_name,p.*";
		if($parameter['desclen']){
			$field.=",left(pd.products_description,".$parameter['desclen'].") as products_description";
		}else{
			//$field.=",pd.products_description";
		}
		$categories=$predata_class->getPredata(TABLE_CATEGORIES);
		$parameter['cid']=str_replace("'","",$parameter['cid']);

		//优化产品随机排序查询效率
		if(strstr($orderby,"rand") && $parameter['flag']=="true"){

			if($parameter['cid']=="all"){
				$rand_sql="SELECT * FROM `".TABLE_PRODUCTS."` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(products_id) FROM `".TABLE_PRODUCTS."`)-(SELECT MIN(products_id) FROM `".TABLE_PRODUCTS."`))+(SELECT MIN(products_id) FROM `".TABLE_PRODUCTS."`)) AS products_id from `".TABLE_PRODUCTS."` limit 50) AS t2 on t1.products_id=t2.products_id left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=t1.products_id where t1.products_status=1 and pd.language_id=".$_SESSION['languages_id']." ORDER BY t1.products_id LIMIT ". rand(0,25).",".$limit;
			}else{
				$parameter['cid']=str_replace("'","",$parameter['cid']);
				$rand_sql="SELECT * FROM `".TABLE_PRODUCTS."` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(products_id) FROM `".TABLE_PRODUCTS."`)-(SELECT MIN(products_id) FROM `".TABLE_PRODUCTS."`))+(SELECT MIN(products_id) FROM `".TABLE_PRODUCTS."`)) AS products_id from `".TABLE_PRODUCTS."` limit 50) AS t2 on t1.products_id=t2.products_id where t1.products_status=1 and t1.master_categories_id in(".$parameter['cid'].") and t1.products_id in(select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id=".$_SESSION['languages_id'].") ORDER BY t1.products_id LIMIT ". rand(0,25).",".$limit;
			}
			
			$rand_data=openzcQuery($rand_sql);
			$rand_data=openzc_table_to_list($rand_data,"products_id");
			$parameter['pid']=$this->getAllpid($rand_data);
			
		}
		
		if($parameter['pid']){
			$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_id in(".$parameter['pid'].") and p.products_status='1' and pd.language_id=".(int)$_SESSION['languages_id'];
			return $sql;
		}

		//优化产品随机排序查询效率

		//catelist-prolist 优化类目循环嵌套调用产品-2021-10-18
		if($parameter['cateloop']==true){

			$cateloopname=md5($parameter['allcids']);
			
			if(!isset($GLOBALS[$cateloopname])){
				foreach(explode(",",$parameter['allcids']) as $k => $v){
					if($categories[$v]['categories_sub_id']=="none"){
						$allcids[$v]=$v;
					}else{
						$allcids[$v]=$categories[$v]['categories_sub_all_id'];
					}
				}

				$cateloopdata=[];
				//print_r($allcids);
				foreach($allcids as $k => $v){
					if($GLOBALS['products_count']>10000){
						$num=$categories[$k]['count'];
						$range_sql="select max(products_id) as max,min(products_id) as min from ".TABLE_PRODUCTS." where master_categories_id in(".$v.")";
						$range=openzcQuery($range_sql);
						$max=$range->fields['max'];
						$min=$range->fields['min'];
						
						if(!$min||!$max){
							if($num>$limit){$center=ceil($num/2);$rand_id=rand($min,($min+$center));}
							else{$rand_id=$min;}
							$rand_sql="select products_id from ".TABLE_PRODUCTS." where products_status=1 and products_id>=".$rand_id." and products_id in(select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id=".$_SESSION['languages_id'].") and master_categories_id in(".$v.") order by products_id asc limit 0,".$limit;
						
						    $cateloopdata[$k]=openzcQuery($rand_sql);
						    $cateloopdata[$k]=openzc_table_to_list($cateloopdata[$k],"products_id");
						}
					}else{
						$rand_sql="select products_id from ".TABLE_PRODUCTS." where products_status=1 and products_id in(select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id=".$_SESSION['languages_id'].") and master_categories_id in(".$v.") order by rand() asc limit 0,".$limit;
						$cateloopdata[$k]=openzcQuery($rand_sql);
						$cateloopdata[$k]=openzc_table_to_list($cateloopdata[$k],"products_id");
					}
					
				}

				$allcids_data=[];
				
				foreach($cateloopdata as $k => $v){
				    $str=[];
				    if(count($v)>0){
				        foreach($v as $a => $b){
    				        $str[]=$b['products_id'];
    				    }
    				    $allcids_data[$k]=join(",",$str);
				    }
				}
				$GLOBALS[$cateloopname]=$allcids_data;
				
			}else{
				$allcids_data=$GLOBALS[$cateloopname];
			}
			
			$pids=$allcids_data[$parameter['current_loop_cid']];
			
			if(!$pids){$pids=0;}

			$sql="select p.*,pd.products_name,pd.products_description from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_id in(".$pids.") and p.products_status=1 and pd.language_id=".(int)$_SESSION['languages_id'];

			return $sql;
		}
		//catelist-prolist 类目循环嵌套调用产品-2021-10-18

		if($parameter['flag']=="true"){$parameter['flag']="";}
		if($parameter['cid']!="all" && $parameter['cid']){
			$cid=str_replace("'","",$parameter['cid']);
			$cid=array_unique(array_filter(explode(",",$cid)));
			foreach ($cid as $k => $v) {
				if(isset($categories[$v])){
					if($categories[$v]['categories_sub_all_id']=="none"){
						$cids.=$v.",";
					}else{
						$cids.=$categories[$v]['categories_sub_all_id'].",";
					}
				}
			}
			$cids=array_unique(array_filter(explode(",",$cids)));
		}else{
			$cids=[];
		}
		if(count($cids)>0){
			$cid_where=" and p.master_categories_id in(".join(",",$cids).")";
		}else{
			$cid_where="";
		}
		switch ($parameter['flag']){
			case 'sale'://促销商品列表
				if($parameter['saleid']){
					$parameter['saleid']=join("','",array_unique(array_filter(explode(",",$parameter['saleid']))));
					$sql="select group_concat(sale_categories_all) as sale_categories_all from ".TABLE_SALEMAKER_SALES." where sale_status='1' and sale_id in('".$parameter['saleid']."')";
				}else{
					$sql="select group_concat(sale_categories_all) as sale_categories_all from ".TABLE_SALEMAKER_SALES." where sale_status='1'";
				}

				$sale=openzcQuery($sql);
				$sale=array_unique(array_filter(explode(",",$sale->fields['sale_categories_all'])));

				$sale_cids="";
				if(count($sale)>0){
					foreach($sale as $k => $v){
						if(isset($categories[$v])){
							if($categories[$v]['categories_sub_all_id']=="none"){
								$sale_cids.=$v;
							}else{
								$sale_cids.=$categories[$v]['categories_sub_all_id'];
							}
						}
					}
				}

				$cids=array_unique(array_filter(explode(",",$sale_cids)));

				if($parameter['cid'] && count($cids)>0){
					$active_cids=openzc_field_to_key(explode(",",$parameter['cid']));
					foreach($cids as $k => $v){
						if(!isset($active_cids[$v])){
							unset($cids[$k]);
						}
					}
				}

				if(count($cids)>0){
					$cid_where="and p.master_categories_id in(".join(",",$cids).")";
				}else{
					$cid_where="";
				}
				$table=TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id";
				if(strstr($orderby,"rand")){
					if(!$cid_where){
						$parameter['pid']=0;
					}else{
						$parameter['cid']=join(",",$cids);
						$rand_sql="SELECT * FROM `".TABLE_PRODUCTS."` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(products_id) FROM `".TABLE_PRODUCTS."`)-(SELECT MIN(products_id) FROM `".TABLE_PRODUCTS."`))+(SELECT MIN(products_id) FROM `".TABLE_PRODUCTS."`)) AS products_id from `".TABLE_PRODUCTS."` limit 50) AS t2 on t1.products_id=t2.products_id where t1.products_status=1 and t1.master_categories_id in(".$parameter['cid'].") and t1.products_id in(select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id=".$_SESSION['languages_id'].") ORDER BY t1.products_id LIMIT ". rand(0,25).",".$limit;
						$rand_data=openzcQuery($rand_sql); 
						$rand_data=openzc_table_to_list($rand_data,"products_id");
						$parameter['pid']=$this->getAllpid($rand_data);
					}
					$sql="select ".$field." from ".$table." where p.products_status='1' and p.products_id in(".$parameter['pid'].") and pd.language_id='".(int)$_SESSION['languages_id']."' order by ".$orderby." limit ".$limit;
				}else{
					$sql="select ".$field." from ".$table." where p.products_status='1' and p.master_categories_id='0' and pd.language_id='".(int)$_SESSION['languages_id']."' order by ".$orderby." limit ".$limit;
				}
			break;
			case 'featured'://推荐商品列表
				if(strstr($orderby,"rand")){
					if($parameter['cid']=="all"){
						$rand_sql="SELECT * FROM `".TABLE_FEATURED."` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(products_id) FROM `".TABLE_FEATURED."`)-(SELECT MIN(products_id) FROM `".TABLE_FEATURED."`))+(SELECT MIN(products_id) FROM `".TABLE_FEATURED."`)) AS products_id from `".TABLE_FEATURED."` limit 50) AS t2 on t1.products_id=t2.products_id left join ".TABLE_PRODUCTS." as p on t1.products_id=p.products_id where t1.status=1 and p.products_status=1 and p.products_id in(select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id=".$_SESSION['languages_id'].") ORDER BY t1.products_id LIMIT ". rand(0,10).",".$limit;

					}else{
						$parameter['cid']=str_replace("'","",$parameter['cid']);
						$rand_sql="SELECT * FROM `".TABLE_FEATURED."` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(products_id) FROM `".TABLE_FEATURED."`)-(SELECT MIN(products_id) FROM `".TABLE_FEATURED."`))+(SELECT MIN(products_id) FROM `".TABLE_FEATURED."`)) AS products_id from `".TABLE_FEATURED."` limit 50) AS t2 on t1.products_id=t2.products_id left join ".TABLE_PRODUCTS." as p on t1.products_id=p.products_id where p.products_status=1 and p.master_categories_id in(".$parameter['cid'].") ORDER BY t1.products_id LIMIT ". rand(0,10).",".$limit;
					}
					$rand_data=openzcQuery($rand_sql);
					$rand_data=openzc_table_to_list($rand_data,"products_id");
					$parameter['pid']=$this->getAllpid($rand_data);
				}
				if($parameter['pid']){
					$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id left join ".TABLE_SPECIALS." f on p.products_id=f.products_id where p.products_status='1' and pd.language_id=".(int)$_SESSION['languages_id']." and f.status=1 and p.products_id in(".$parameter['pid'].") limit ".$limit;
				}else{
					$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id left join ".TABLE_FEATURED." f on p.products_id=f.products_id where p.products_status='1' and pd.language_id=".(int)$_SESSION['languages_id']." and f.status=1 order by ".$orderby." limit ".$limit;
				}

			break;
			case 'specials'://特价商品列表
				if(strstr($orderby,"rand")){
					if($parameter['cid']=="all"){
						$rand_sql="SELECT * FROM `".TABLE_SPECIALS."` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(products_id) FROM `".TABLE_SPECIALS."`)-(SELECT MIN(products_id) FROM `".TABLE_SPECIALS."`))+(SELECT MIN(products_id) FROM `".TABLE_SPECIALS."`)) AS products_id from `".TABLE_SPECIALS."` limit 50) AS t2 on t1.products_id=t2.products_id left join ".TABLE_PRODUCTS." as p on t1.products_id=p.products_id where t1.status=1 and p.products_status=1 and p.products_id in(select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id=".$_SESSION['languages_id'].") ORDER BY t1.products_id LIMIT ". rand(0,10).",".$limit;

					}else{
						$parameter['cid']=str_replace("'","",$parameter['cid']);
						$rand_sql="SELECT * FROM `".TABLE_SPECIALS."` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(products_id) FROM `".TABLE_SPECIALS."`)-(SELECT MIN(products_id) FROM `".TABLE_SPECIALS."`))+(SELECT MIN(products_id) FROM `".TABLE_SPECIALS."`)) AS products_id from `".TABLE_SPECIALS."` limit 50) AS t2 on t1.products_id=t2.products_id left join ".TABLE_PRODUCTS." as p on t1.products_id=p.products_id where p.products_status=1 and p.master_categories_id in(".$parameter['cid'].") ORDER BY t1.products_id LIMIT ". rand(0,10).",".$limit;
					}
					$rand_data=openzcQuery($rand_sql);
					$rand_data=openzc_table_to_list($rand_data,"products_id");
					$parameter['pid']=$this->getAllpid($rand_data);
					if(!$parameter['pid']){$parameter['pid']='0';}
					$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id left join ".TABLE_SPECIALS." s on p.products_id=s.products_id where p.products_status='1' and pd.language_id=".(int)$_SESSION['languages_id']." and s.status=1 and p.products_id in(".$parameter['pid'].") limit ".$limit;
				}else{
					$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id left join ".TABLE_SPECIALS." s on p.products_id=s.products_id where p.products_status='1' and pd.language_id=".(int)$_SESSION['languages_id']." and s.status=1 order by ".$orderby." limit ".$limit;
				}
				
			break;
			case 'bestsell':
				$sql="select count(*) as count from ".TABLE_ORDERS_PRODUCTS;
				$order_count=openzcQuery($sql);
				if($order_count->fields['count']>0){
					$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id left join (select sum(products_quantity) as products_orders_count,products_id from ".TABLE_ORDERS_PRODUCTS." group by products_id ) op on op.products_id=p.products_id where p.products_id=pd.products_id and p.products_status='1' and pd.language_id=".(int)$_SESSION['languages_id'].$cid_where." order by op.products_orders_count desc limit ".$limit;
				}else{
					$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_id=pd.products_id and p.products_status='1' and pd.language_id=".(int)$_SESSION['languages_id'].$cid_where." order by p.products_date_added desc limit ".$limit;
				}
			break;
			case "rating":
				$sql="select count(*) as count from ".TABLE_REVIEWS;
				$order_count=openzcQuery($sql);
				if($order_count->fields['count']>0){
					$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd left join (select avg(reviews_rating) as products_rating,products_id from ".TABLE_REVIEWS." group by products_id) r where p.products_id=pd.products_id and p.products_status='1' and pd.language_id=".(int)$_SESSION['languages_id'].$cid_where." order by r.products_rating desc limit ".$limit;
				}else{
					$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd where p.products_id=pd.products_id and p.products_status='1' and pd.language_id=".(int)$_SESSION['languages_id'].$cid_where." order by p.products_date_added desc limit ".$limit;
				}
			break;
			case "relate":
				$cid=openzc_get_current_cpath($_GET['cPath']);
				if(isset($categories[$cid])){
					if($categories[$cid]['categories_sub_all_id']!="none"){
						$cid.=",".$categories[$cid]['categories_sub_all_id'];
					}
				}

				if($_GET['main_page']==FILENAME_PRODUCT_INFO){
					switch($parameter['type']){
						case "viewed":
							$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_status='1' and p.master_categories_id in(".$cid.") and pd.language_id='".(int)$_SESSION['languages_id']."' order by pd.products_viewed desc limit ".$limit;
						break;
						case "week":

						break;
						case "month":
						break;
						case "quarter":
						break;
						case "price":
							$price=openzcQuery("select products_price_sorter from ".TABLE_PRODUCTS." where products_id='".$_GET['products_id']."'");
							$price=$price->fields['products_price_sorter'];
							if($parameter['range']){
								$range=explode(",",$parameter['range']);
								$range[0]=$price-$range[0];
								$range[1]=$price+$range[1];
								$between="p.products_price_sorter >='".$range[0]."' and p.products_price_sorter<='".$range[1]."'";
								$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.master_categories_id in(".$cid.") and p.products_status='1' and pd.language_id='".(int)$_SESSION['languages_id']."' and ".$between." order by ".$orderby." limit ".$limit;
							}else{
								$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.master_categories_id in(".$cid.") and p.products_price_sorter='".$price."' and p.products_status='1' and pd.language_id='".(int)$_SESSION['languages_id']."' group by p.products_id order by ".$orderby." limit ".$limit;
							}
						break;
						default:
							$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.master_categories_id in(".$cid.") and p.products_status='1' and pd.language_id='".(int)$_SESSION['languages_id']."' order by ".$orderby." limit ".$limit;
						break;
					}
				}else{
					return false;
				}
			break;
			case 'new':
				$table=TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id";
				$sql="select ".$field." from ".$table." where p.products_status='1'".$cid_where." and pd.language_id=".(int)$_SESSION['languages_id']." order by p.products_date_added desc limit ".$limit;
			break;
			case 'price':
				if($parameter['range']){
					$range=explode(",",$parameter['range']);
					if($range[0]==0){$range[0]=1;}
					$between="p.products_price_sorter>='".$range[0]."' and p.products_price_sorter<='".$range[1]."'";
					$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_status='1'".$cid_where." and pd.language_id='".(int)$_SESSION['languages_id']."' and ".$between." order by ".$orderby." limit ".$limit;
				}else{
					die('Error:请添加价格范围参数：range！');
				}
			break;
			case "attr":
				if($parameter['options_id']){
					$options_id=array_filter(explode(",",$parameter['options_id']));
					$options_id=join(",",$options_id);
					$attr_pids_sql="select pa.products_id from ".TABLE_PRODUCTS_ATTRIBUTES." pa where pa.options_id in(".$options_id.") and pa.products_id in (select products_id from ".TABLE_PRODUCTS." where products_status=1) and pa.products_id in (select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id=".$_SESSION['languages_id'].") group by pa.products_id order by pa.products_id desc limit ".$limit;
					$attr_pids=openzcQuery($attr_pids_sql);
					$attr_pids=openzc_table_to_list($attr_pids);
					$attr_pids=$this->getAllpid($attr_pids);
				}
				if($parameter['options_values_id']){
					$options_values_id=array_filter(explode(",",$parameter['options_values_id']));
					$options_values_id=join(",",$options_values_id);
					
					$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_status='1'".$cid_where." and p.products_id in(select products_id from ".TABLE_PRODUCTS_ATTRIBUTES." where options_values_id in(".$options_values_id.")) and pd.language_id=".$_SESSION['languages_id']." order by ".$orderby." limit ".$limit;
				}
				$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_status='1' and pd.language_id=".$_SESSION['languages_id']." and p.products_id in(".$attr_pids.")";
				//echo $sql;exit;
			break;
			default:
				
				if(!$sql){
					if($parameter['cid'] && $parameter['cid']!="all"){
						$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id where p.products_status='1' and pd.language_id='".(int)$_SESSION['languages_id']."' and p.master_categories_id in(".$parameter['cid'].") order by ".$orderby." limit ".$limit;
					}else{
						$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id where p.products_status='1' and pd.language_id='".(int)$_SESSION['languages_id']."' order by ".$orderby." limit ".$limit;
					}
				}
			break;
		}
		return $sql;
	}
	
	//调用多条件商品列表：按品牌、属性、价格
	function get_filter_search($GET=[],$parameter=[]){
		global $predata_class;
		$categories=$predata_class->getPredata(TABLE_CATEGORIES);
		$limit=$parameter['row'];
		if($parameter['page']==true && isset($_GET["page"])){
			$limit=($parameter['row']*($_GET['page']-1)).",".$parameter['row'];
		}
		$field="pd.products_name,pd.products_viewed,p.*";
		if($parameter['desclen']){
			$field.=",left(pd.products_description,".$parameter['desclen'].") as products_description";
		}
		$table="";
		//$where="p.products_id=pd.products_id and pd.language_id=".(int)$_SESSION['languages_id'];
		$where="";
		$between="";
		$filter=array();
		//按商品价格/属性/品牌查询
		if($GET['price']){$filter['price']=explode("|",$GET['price']);}
		if($GET['brand']){$filter['brand']=$GET['brand'];}
		if($GET['options'] || $GET['options']=='0'){$filter['attr']=$GET['options'];}
		if(count($filter)>0){
			foreach($filter as $k => $v){
				switch($k){
					case 'price':
						foreach($v as $a => $b){
							$b=explode(",",$b);
							if($where_price){$where_price .=" or ";}
							if($categories[$_GET['cPath']]['max']<=$b[1]){$symob="<=";}else{$symob="<";}
							switch($_GET['main_page']){
								case FILENAME_SPECIALS:
									$maxsql="select max(p.products_price_sorter) as max from ".TABLE_SPECIALS." s left join ".TABLE_PRODUCTS." p on s.products_id=p.products_id left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=s.products_id where s.status='1' and pd.language_id='".(int)$_SESSION['languages_id']."'";
								break;
								case FILENAME_PRODUCTS_ALL:
									$maxsql="select max(p.products_price_sorter) as max from ".TABLE_PRODUCTS." p left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id where pd.language_id='".(int)$_SESSION['languages_id']."'";
								break;
								case FILENAME_FEATURED_PRODUCTS:
									$maxsql="select max(p.products_price_sorter) as max from ".TABLE_FEATURED." f left join ".TABLE_PRODUCTS." p on f.products_id=p.products_id left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=f.products_id where f.status='1' and pd.language_id='".(int)$_SESSION['languages_id']."'";
								break;
							}
							if(!empty($maxsql)){
								$max=openzcQuery($maxsql);
								if($max->fields['max']<=$b[1]){$symob="<=";}else{$symob="<";}
							}
							$where_price.="(products_price_sorter >= '".$b[0]."' and products_price_sorter ".$symob." '".$b[1]."')";
							$where_price_flag=" and (p.products_price_sorter >= '".$b[0]."' and p.products_price_sorter ".$symob." '".$b[1]."')";
						}
						$between=" p.products_price_sorter >= '".$b[0]."' and p.products_price_sorter ".$symob." '".$b[1]."' and";
						if($parameter['flag']=="featured"){
							$where_price_flag="and p.products_price_sorter >= '".$b[0]."' and p.products_price_sorter ".$symob." '".$b[1]."'";
						}
					break;
					case 'brand':
						$v=str_replace(",","','",$v);
						$where.=" and p.manufacturers_id in('".$v."')";
						if($parameter['flag']=="specials" || $parameter['flag']=="featured" || $parameter['flag']=="search"){
							$where_brand_flag.=" and p.manufacturers_id in('".$v."')";
						}
					break;
					case 'attr':
						$table=" left join ".TABLE_PRODUCTS_ATTRIBUTES." pa on p.products_id=pa.products_id";
						$v=array_filter(explode("|",$v));

						//$vtp=$predata_class->getPredata(TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS);
						foreach($v as $a => $b){
							$b=array_filter(explode(":",$b));
							$options_id[]=$b[0];
							$b[1]=array_filter(explode(",",$b[1]));
							foreach($b[1] as $c => $d){
								$options[$b[0]]['values'][]=$d;
							}
						}
						
						foreach($options as $a => $b){ 
							$b=join(",",$b['values']);
							//$sql.=" and pa.options_values_id in(".$b.")";
							$sql.=" and p.products_id in(select products_id from ".TABLE_PRODUCTS_ATTRIBUTES." where options_id in(".$a.") and options_values_id in(".$b."))";
							$where_attr_flag.=" and p.products_id in(select products_id from ".TABLE_PRODUCTS_ATTRIBUTES." where options_id in(".$a.") and options_values_id in(".$b."))";
							
						}
						
						//$table=TABLE_PRODUCTS_ATTRIBUTES." pa,";
						$where.=" and pa.options_id in(".join(",",$options_id).")".$sql;
					break;
				}
			}
		}

		//判断是否存在副栏目产品关联（已废弃）
		if($parameter['cid']!="all" && $parameter['cid']){
			$where.=" and p.master_categories_id in(".$parameter['cid'].")";
		}
		
		$orderby=$parameter['orderby'];
		///////////列表指定flag产品
		if($parameter['flag']){
			switch($parameter['flag']){
				case "specials": 
					$table = TABLE_SPECIALS." flag";
					if(explode(",",$_GET['orderby'])[0]=="price"){
						$orderby[0]="flag";
						$orderby[1]="specials_new_products_price";
					}
				break;
				case "featured": 
					$table = TABLE_FEATURED." flag";
				break;
			}
			if($parameter['flag']=="search"){
				$table.= TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id = p.products_id";
			}else{
				$table.=" inner join ".TABLE_PRODUCTS." p on p.products_id=flag.products_id inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id = p.products_id";
			}

			if($where_attr_flag){
				if($parameter['flag']=="search"){
					$table.=" left join ".TABLE_PRODUCTS_ATTRIBUTES." pa on p.products_id=pa.products_id";
				}else{
					$table.=" left join ".TABLE_PRODUCTS_ATTRIBUTES." pa on flag.products_id=pa.products_id";
				}
			}

			if($orderby[3]==TABLE_ORDERS_PRODUCTS){
				$table.=" left join (select sum(products_quantity) as products_orders_count,products_id from ".TABLE_ORDERS_PRODUCTS.") op on p.products_id=op.products_id";
			}
			$where=$where_price_flag.$where_brand_flag.$where_attr_flag;
			
			if($parameter['flag']=="search"){
				$where="and p.products_id in (select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where products_name like '%".$_GET['keyword']."%')";
				if(isset($_GET['cPath']) && $_GET['cPath']){
					if(count($deputy)>0){
						$where.=" and p.products_id in(select products_id from ".TABLE_PRODUCTS_TO_CATEGORIES." where categories_id in(".$parameter['cid']."))";
					}else{
						$where.=" and p.master_categories_id in(".$parameter['cid'].")";
					}
				}
			}
			
			$GLOBALS['page_sql']=$where;
			if($parameter['flag']=="search"){
				$sql="select p.*,pd.products_name from ".$table." where p.products_status='1' and pd.language_id=".(int)$_SESSION['languages_id']." ".$where." order by ".$orderby[0].".".$orderby[1]." ".$orderby[2]." limit ".$limit;
			}else{
				$sql="select p.*,pd.products_name from ".$table." where p.products_status='1' and flag.status='1' and pd.language_id=".(int)$_SESSION['languages_id']." ".$where." order by ".$orderby[0].".".$orderby[1]." ".$orderby[2]." limit ".$limit;
			}
		}else{
			$GLOBALS['page_sql']=$where.$where_price_flag.$where_brand_flag.$where_attr_flag;
			//$specials="left join ".TABLE_SPECIALS." s on s.products_id=p.products_id";
			switch($orderby[3]){
				case TABLE_ORDERS_PRODUCTS:
					$table.="inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id left join (select sum(products_quantity) as products_orders_count,products_id from ".TABLE_ORDERS_PRODUCTS." group by products_id) op on op.products_id=p.products_id";
				break;
				default:
				break;
			}
			//大数据临界线40000，优化大数据分页查询效率
			$critical_num=round(40000/$parameter['row']);
			$critical_num=$parameter['row']*$critical_num;
			$rows=($_GET['page']-1)*$parameter['row'];
			
			if($rows>$critical_num){
				if($orderby[1]=="products_price_sorter"){
					$price_group_sql="select count(*) as count,products_price_sorter from ".TABLE_PRODUCTS." where master_categories_id in(".$parameter['cid'].") group by products_price_sorter order by ".$orderby[1]." ".$orderby[2];
					$price_group=openzcQuery($price_group_sql);
					$price_group=openzc_table_to_list($price_group,"products_price_sorter");
					$sort=0;
					foreach ($price_group as $k => $v) {
						$price_group[$k]['sort']=$sort;
						$sort+=$v['count'];
					}
					//print_r($price_group);exit;
					$current_price_sql="select products_price_sorter from ".TABLE_PRODUCTS." where master_categories_id in(".$parameter['cid'].") order by ".$orderby[1]." ".$orderby[2]." limit ".$rows.",1";
					$current_price=openzcQuery($current_price_sql);
					$current_price=$current_price->fields['products_price_sorter'];

					$price_start=$rows-$price_group[$current_price]['sort'];
					
					$list_pids_sql="select p.products_id from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_price_sorter>=".$current_price." and pd.language_id=".$_SESSION['languages_id']." and p.master_categories_id in(".$parameter['cid'].") and p.products_status=1 order by ".$orderby[0].".".$orderby[1]." ".$orderby[2]." limit ".$price_start.",".$parameter['row'];
				}else{

					$orderby[1]="products_id";
					if($orderby[2]=="asc"){$m=">=";}else{$m="<=";}
					//$rows=$rows+$parameter['row'];

					$current_id_sql="select a.products_id from ".TABLE_PRODUCTS." a where a.products_id in(select products_id from ".TABLE_PRODUCTS." where master_categories_id in(".$parameter['cid'].") and products_status=1) order by a.".$orderby[1]." ".$orderby[2]." limit ".$rows.",1";

					$current_id=openzcQuery($current_id_sql);
					$current_id=$current_id->fields['products_id'];

					$list_pids_sql="select p.products_id from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_id ".$m.$current_id." and pd.language_id=".$_SESSION['languages_id']." and p.master_categories_id in(".$parameter['cid'].") and p.products_status=1 order by ".$orderby[0].".".$orderby[1]." ".$orderby[2]." limit ".$parameter['row'];

				}
				
				$list_pids_data=openzcQuery($list_pids_sql);
				$list_pids=openzc_table_to_list($list_pids_data);
				$list_pids=$this->getAllpid($list_pids);

				$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id".$table." where".$between." pd.language_id='".(int)$_SESSION['languages_id']."' and p.products_id in(".$list_pids.") order by ".$orderby[0].".".$orderby[1]." ".$orderby[2];

			}else{
				$sql="select ".$field." from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id".$table." where".$between." p.products_status='1' and pd.language_id='".(int)$_SESSION['languages_id']."'".$where." order by ".$orderby[0].".".$orderby[1]." ".$orderby[2]." limit ".$limit;
			}
		}
		//echo $sql;exit;
		return $sql;
	}
	
	//商品列表展示
	function show_products_list($GET=[],$sql="",$parameter=[]){
		global $predata_class,$skuPriceClass,$currencies;
	
		$data=openzcQuery($sql);
		if($parameter['index_field']){
			$data=openzc_table_to_list($data,$parameter['index_field']);
		}else{
			$data=openzc_table_to_list($data);
		}
		$allpid=$this->getAllpid($data);
		
		if(!$allpid){return false;}

		$manufacturers=$predata_class->getPredata(TABLE_MANUFACTURERS);
		$categories=$predata_class->getPredata(TABLE_CATEGORIES);
	    $products_rating=$this->get_products_reviews_rating($data,$allpid);
		
	    $currencies_symbol_left=$predata_class->getPredata(TABLE_CURRENCIES);
		$featured=openzcQuery("select * from ".TABLE_FEATURED." where products_id in(".$allpid.") and status='1'");
		$featured=openzc_table_to_list($featured,"products_id");
		//2021-11-10*******
		$specials_sql="select * from ".TABLE_SPECIALS." where products_id in(".$allpid.")";
		$specials=openzcQuery($specials_sql);
		$specials=openzc_table_to_list($specials,"products_id");
		//2021-11-10*******
		//$specials=$predata_class->getPredata(TABLE_SPECIALS);
		$attrStatus=openzcQuery("select count(products_attributes_id) as attr_count,products_id from ".TABLE_PRODUCTS_ATTRIBUTES." where products_id in(".$allpid.") group by products_id");
		$attrStatus=openzc_table_to_list($attrStatus,"products_id");
		
		foreach($data as $k => $v){
			$v['list_count']=count($data);
			$v["sort_index"]=$k+1;
			if($v["sort_index"]%2==0){
				$v["sort_index_type"]="even";
			}else{
				$v["sort_index_type"]="odd";
			}
			
			if(isset($parameter['type']) && $parameter['type']=="compare"){
				$v['products_compare']=true;
			}
			$v['allpid']=$allpid;
			
			$v["products_price"]="";
			$v['products_price_string']=$this->get_display_price($v['products_id']);
			
			$v['categories_name']=$categories[$v['master_categories_id']]['categories_name'];
			$v['categories_link']=$categories[$v['master_categories_id']]['categories_link'];
			if(isset($manufacturers[$v['manufacturers_id']])){
				$v['manufacturers_name']=$manufacturers[$v['manufacturers_id']]['manufacturers_name'];
				$v['manufacturers_image']=DIR_WS_CATALOG."images/".$manufacturers[$v['manufacturers_id']]['manufacturers_image'];
				$v['manufacturers_url']=$manufacturers[$v['manufacturers_id']]['manufacturers_url'];
			}
			
			foreach($GLOBALS['products_price_array'][$v['products_id']] as $a => $b){
				$v[$a]=$b;
				if($a=="normal_price" || $a=="products_base_price"){
					$v['products_original_price']=$b;
				}
				else if($a=="products_special_price" || $a=="products_special_price_sale" || $a=="products_sale_price"){
					$v['products_price']=$b;
				}
				if($a=="products_sale_price"){
					$v['products_flag'].=",sale";
					$sale = openzcQuery("select * from " . TABLE_SALEMAKER_SALES . " where sale_categories_all like '%," . $v['master_categories_id'] . ",%' and sale_status = '1' and (sale_date_start <= now() or sale_date_start = '0001-01-01') and (sale_date_end >= now() or sale_date_end = '0001-01-01') and (sale_pricerange_from <= '" . $GLOBALS['products_price_array'][$v['products_id']]['products_normal_price'] . "' or sale_pricerange_from = '0') and (sale_pricerange_to >= '" . $GLOBALS['products_price_array'][$v['products_id']]['products_normal_price'] . "' or sale_pricerange_to = '0')");
					$v['expires_date']=$sale->fields['sale_date_end'];
				}
				if($a=="products_special_price"){
					$v['expires_date']=$specials[$v['products_id']]['expires_date'];
					$v['products_flag'].=",special";
				}
			}
			
			if(isset($featured[$v['products_id']])){$v['products_flag'].=",featured";}
			if(isset($v["expires_date"])){
				$expires_date=strtotime($v['expires_date']);
				$v['expires_date_secound']=$expires_date*1000;
			}
			if($v['product_is_free']==1){
				$v['products_price']=$currencies->format(0);
				$v['products_price_discount']="Is free!";
				$v['products_original_price']=$v['products_price_string'];
			}
			if(!$v['products_price']){
				$v['products_price']=$v['products_original_price'];
			}

			if(!isset($v['products_original_price']) && isset($v['normalprice'])){
				$v['products_original_price']=$v['normalprice'];
			}
			$v['products_price']=str_replace("Sale:&nbsp;","",$v['products_price']);
			$v['products_price_number']=str_replace($currencies_symbol_left[$_SESSION['currency']]['symbol_left'],"",$v['products_price']);
			$v['products_price_number']=str_replace(",","",$v['products_price_number']);

			//**products_image
			if($parameter['separator']){
				$separator=$parameter['separator'];
			}else{
				$separator="|||";
			}
			$allImages=array_filter(explode($separator,$v['products_image'].$separator.$v['products_image_detail']));
			if(count($allImages)>1){
				$flip_image=$allImages[1];
			}else{
				$flip_image=$allImages[0];
			}
			
			//**products_name length
			if($parameter["titlelen"]){$v['products_name']=mb_substr($v['products_name'],0,$parameter["titlelen"],"utf-8");}
			$v['products_image_full']=$this->get_products_image($allImages[0],"","",$separator);
			$v['products_image']=$this->get_products_image($allImages[0],$parameter['imgsizer'],$parameter['bgcolor'],$separator);
			$v['products_image_size']="";

			if(is_array($v['products_image'])){
				$v['products_image_size']=$v['products_image'][1];
				$v['products_image']=$v['products_image'][0];
			}
			$v['products_image_flip_full']=$this->get_products_image($flip_image);
			$v['products_image_flip_full_size']="";
			if(is_array($v['products_image_flip_full'])){
				$v['products_image_flip_full_size']=$v['products_image_flip_full'][1];
				$v['products_image_flip_full']=$v['products_image_flip_full'][0];
			}
			$v['products_image_flip']=$this->get_products_image($v['products_image_flip_full'],$parameter['imgsizer'],$parameter['bgcolor'],$separator);
			$v['products_image_flip_size']="";
			if(is_array($v['products_image_flip'])){
				$v['products_image_flip_size']=$v['products_image_flip'][1];
				$v['products_image_flip']=$v['products_image_flip'][0];
			}

			$cPath=$categories[$v['master_categories_id']]['path'];
			$v['products_link']=zen_href_link(FILENAME_PRODUCT_INFO,'cPath='.$cPath.'&products_id='.$v['products_id']);
			$v['buy_now']=false;
			if(!isset($attrStatus[$v['products_id']])){
				$v['buy_now']=zen_href_link(FILENAME_PRODUCT_INFO, 'products_id='.$v['products_id'].'&action=buy_now');
			}
			$v['products_rating']=$products_rating[$v["products_id"]]['products_rating']?:0;
			$v['products_rating']=number_format($v['products_rating'],1);
			$v['products_reviews_count']=$products_rating[$v["products_id"]]['products_reviews_count']?:0;
			$v['products_customers_count']=$products_rating[$v["products_id"]]['products_customers_count']?:0;
			
			$v['sku_price_class']=$skuPriceClass."-".$v['products_id'];
			if(isset($v['products_description'])){
				$v['products_description_preview']=strip_tags($v['products_description']);
			}
			$v['products_wishlist']=false;
			$v['products_compare']=false;
			$wishlist=array_unique(array_filter(explode(",",$_SESSION['wishlist']['list'])));
			foreach($wishlist as $c => $d){if($v['products_id']==$d){$v['products_wishlist']=true;}}
			$compare=array_unique(array_filter(explode(",",$_SESSION['compare']['list'])));
			foreach($compare as $c => $d){if($v['products_id']==$d){$v['products_compare']=true;}}
			if($parameter['type']=="compare" && $parameter['fields']){$v['products_compare']=true;$v['compare_options_id']=$parameter['fields']['products_options_id'];}

			if(empty($v['products_price'])){
				$v['products_price']=$currencies->display_price(0,"");
			}

			$datalist[$k]=$v;
		}
		
		if($parameter['page']==true){
			$list['total']=$GLOBALS['listCount'];
			$list['datalist']=$datalist;
			$datalist=$list;
		}
		return $datalist;
	}
	private function getAllpid($products=""){
		foreach($products as $k => $v){$pids[]=$v['products_id'];}
		if(count($pids)>0){
			$pids="'".join("','",$pids)."'";
		}else{
			$pids="";
		}
		return $pids;
	}

	public function get_display_price($products_id=""){
		global $currencies,$db;
		switch (true) {
	        case (CUSTOMERS_APPROVAL == '1' and $_SESSION['customer_id'] == ''):
	        // customer must be logged in to browse
	        return '';
	        break;
	        case (CUSTOMERS_APPROVAL == '2' and $_SESSION['customer_id'] == ''):
	        // customer may browse but no prices
	        return TEXT_LOGIN_FOR_PRICE_PRICE;
	        break;
	        case (CUSTOMERS_APPROVAL == '3' and TEXT_LOGIN_FOR_PRICE_PRICE_SHOWROOM != ''):
	        // customer may browse but no prices
	        return TEXT_LOGIN_FOR_PRICE_PRICE_SHOWROOM;
	        break;
	        case ((CUSTOMERS_APPROVAL_AUTHORIZATION != '0' and CUSTOMERS_APPROVAL_AUTHORIZATION != '3') and $_SESSION['customer_id'] == ''):
	        // customer must be logged in to browse
	        return TEXT_AUTHORIZATION_PENDING_PRICE;
	        break;
	        case ((CUSTOMERS_APPROVAL_AUTHORIZATION != '0' and CUSTOMERS_APPROVAL_AUTHORIZATION != '3') and $_SESSION['customers_authorization'] > '0'):
	        // customer must be logged in to browse
	        return TEXT_AUTHORIZATION_PENDING_PRICE;
	        break;
	      case (isset($_SESSION['customers_authorization']) && (int)$_SESSION['customers_authorization'] == 2):
	        // customer is logged in and was changed to must be approved to see prices
	        return TEXT_AUTHORIZATION_PENDING_PRICE;
	        break;
	        default:
	        // proceed normally
	        break;
	      }

	// show case only
	    if (STORE_STATUS != '0') {
	      if (STORE_STATUS == '1') {
	        return '';
	      }
	    }

	    // $new_fields = ', product_is_free, product_is_call, product_is_showroom_only';
	    $product_check = $db->Execute("select products_tax_class_id, products_price, products_priced_by_attribute, product_is_free, product_is_call, products_type from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'" . " limit 1");

	    // no prices on Document General
	    if ($product_check->fields['products_type'] == 3) {
	      return '';
	    }
		if(isset($GLOBALS['products_price_array'][$products_id])){return false;}
		
		$display_normal_price = zen_get_products_base_price($products_id);
		$GLOBALS['products_price_array'][$products_id]['products_normal_price']=$display_normal_price;
		$display_special_price = zen_get_products_special_price($products_id, true);
		$display_sale_price = zen_get_products_special_price($products_id,false);
		if (SHOW_SALE_DISCOUNT_STATUS == '1' and ($display_special_price != 0 or $display_sale_price != 0)) {
			if ($display_sale_price) {
				if (SHOW_SALE_DISCOUNT == 1) {
					if ($display_normal_price != 0) {
						$show_discount_amount = number_format(100 - (($display_sale_price / $display_normal_price) * 100),SHOW_SALE_DISCOUNT_DECIMALS);
					} else {
						$show_discount_amount = '';
					}
					$string=PRODUCT_PRICE_DISCOUNT_PREFIX . $show_discount_amount . PRODUCT_PRICE_DISCOUNT_PERCENTAGE;
					$GLOBALS['products_price_array'][$products_id]['products_price_discount']=$string;
				}else{
					$string=PRODUCT_PRICE_DISCOUNT_PREFIX . $currencies->display_price(($display_normal_price - $display_sale_price), zen_get_tax_rate($product_check->fields['products_tax_class_id'])) . PRODUCT_PRICE_DISCOUNT_AMOUNT;
					$GLOBALS['products_price_array'][$products_id]['products_price_discount']=$string;
				}
			} else {
				if (SHOW_SALE_DISCOUNT == 1) {
					$string=PRODUCT_PRICE_DISCOUNT_PREFIX . number_format(100 - (($display_special_price / $display_normal_price) * 100),SHOW_SALE_DISCOUNT_DECIMALS) . PRODUCT_PRICE_DISCOUNT_PERCENTAGE;
					$GLOBALS['products_price_array'][$products_id]['products_price_discount']=$string;
				} else {
					$string=PRODUCT_PRICE_DISCOUNT_PREFIX . $currencies->display_price(($display_normal_price - $display_special_price), zen_get_tax_rate($product_check->fields['products_tax_class_id'])) . PRODUCT_PRICE_DISCOUNT_AMOUNT;
					$GLOBALS['products_price_array'][$products_id]['products_price_discount']=$string;
				}
			}
		}
		if ($display_special_price) {
			$string=$currencies->display_price($display_normal_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
			$GLOBALS['products_price_array'][$products_id]['normalprice']=$string;
			if ($display_sale_price && $display_sale_price != $display_special_price) {
				$string=$currencies->display_price($display_special_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
				$GLOBALS['products_price_array'][$products_id]['products_special_price_sale']=$string;
				if ($product_check->fields['product_is_free'] == '1') {
					$string=PRODUCT_PRICE_SALE . '<s>' . $currencies->display_price($display_sale_price, zen_get_tax_rate($product_check->fields['products_tax_class_id'])) . '</s>';
					$GLOBALS['products_price_array'][$products_id]['products_sale_price']=$string;
				} else {
					$string=PRODUCT_PRICE_SALE . $currencies->display_price($display_sale_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
					$GLOBALS['products_price_array'][$products_id]['products_sale_price']=$string;
				}
			} else {
				if ($product_check->fields['product_is_free'] == '1') {
					$string='<s>' . $currencies->display_price($display_special_price, zen_get_tax_rate($product_check->fields['products_tax_class_id'])) . '</s>';
					$GLOBALS['products_price_array'][$products_id]['products_special_price']=$string;
				} else {
					$string=$currencies->display_price($display_special_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
					$GLOBALS['products_price_array'][$products_id]['products_special_price']=$string;
				}
				$show_sale_price = '';
			}
		} else {
			if ($display_sale_price) {
				$string=$currencies->display_price($display_normal_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
				$GLOBALS['products_price_array'][$products_id]['normal_price']=$string;
				$show_special_price = '';
				$string=PRODUCT_PRICE_SALE . $currencies->display_price($display_sale_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
				$GLOBALS['products_price_array'][$products_id]['products_special_price']=$string;
			} else {
				if ($product_check->fields['product_is_free'] == '1') {
					$string='<s>' . $currencies->display_price($display_normal_price, zen_get_tax_rate($product_check->fields['products_tax_class_id'])) . '</s>';
					$GLOBALS['products_price_array'][$products_id]['products_free_price']=$string;
				} else {
					$string=$currencies->display_price($display_normal_price, zen_get_tax_rate($product_check->fields['products_tax_class_id']));
					$GLOBALS['products_price_array'][$products_id]['products_base_price']=$string;
				}
			}
		}
		return $string;
	}
	public function get_price_number($price){
		global $predata_class;
		$price=str_replace("Sale:&nbsp;","",$price);
		$currencies_symbol_left=$predata_class->getPredata(TABLE_CURRENCIES);
		$price=str_replace($currencies_symbol_left[$_SESSION['currency']]['symbol_left'],"",$price);
		$price=str_replace($currencies_symbol_left[$_SESSION['currency']]['symbol_right'],"",$price);
		$price=str_replace(",","",$price);
		return $price;
	}
	public function get_products_reviews_rating($data,$allpid=""){
		foreach($data as $k => $v){
			$pids[]=$v['products_id'];
		}
		if(!$allpid){
			$pids="'".join("','",$pids)."'";
		}else{
			$pids=$allpid;
		}
		
		$sql="select count(distinct customers_id) as products_customers_count,count(reviews_id) as products_reviews_count,sum(reviews_rating) as sum,products_id from ".TABLE_REVIEWS." where status='1' and products_id in(".$pids.") group by products_id";
		$data=openzcQuery($sql);
		$data=openzc_table_to_list($data,"products_id");
		
		foreach($data as $k => $v){
			$result[$k]['products_rating']=number_format($v['sum']/$v['products_reviews_count'],1);
			$result[$k]['products_customers_count']=$v['products_customers_count'];
			$result[$k]['products_reviews_count']=$v['products_reviews_count'];
		}
		return $result;
	}
	//获取主图
	function get_products_image($images='',$sizer='',$bgcolor='',$separator=""){
		global $ImageSizer;
		$result="";
		if(!is_dir(IMGCACHE_DIR)){mkdir(IMGCACHE_DIR);}
		if($separator){
			$images=explode($separator,$images);
			$remote=$this->checkRemoteimg($images[0]);
			if($remote==true){
				if(isset($_SESSION['remote_images_speed']) && $_SESSION['remote_images_speed']==true){
					$result="/webp.php?name=".base64_encode($images[0]).".webp";
				}else{
					$result=$images[0];
				}
			}else{
				if(is_file("./images/".$images[0])){
					$result="images/".$images[0];
				}else if(is_file("./".$images[0])){
					$result=$images[0];
				}
			}
			
			if($sizer && $remote==false){
				$sizer=explode(",",$sizer);
				$imgname=getCacheImgname(basename($result));
				$imgdir=IMGCACHE_DIR.$sizer[0]."-".$sizer[1]."/";
				$image_new=$imgdir.$imgname;
				if(!is_dir($imgdir)){
					mkdir($imgdir);
				}
				if(getCacheImgcheck($image_new)==true){
					$ImageSizer->Run("./".$result);
					$ImageSizer->resize($sizer[0],$sizer[1],$bgcolor);
					$ImageSizer->save($image_new);
				}
				$result=DIR_WS_CATALOG.str_replace(ROOT_PATH,"",$imgdir).$imgname;
			}
		}

		return $result;
	}
	
	//远程图片处理
	function checkRemoteimg($images=""){
		if(strstr($images,"http://") || strstr($images,"https://")){
			return true;
		}else{
			return false;
		}
	}
	
	//商品列表分页
	function get_products_list_page($GET,$parameter){
		
		if(array_key_exists("limit",$GET)){
			$pernum=$GET['limit'];
		}else{
			$pernum=$parameter['pernum'];
		}
		
		$total=$parameter['total'];
		if(!$pernum){$pernum=20;}
		$rows=ceil($total / $pernum);//获取页数
        if(!array_key_exists("page",$GET)){$GET['page']=1;}
		
		if($parameter['listitem']){
			foreach($GET as $k => $v){
				if($k!="main_page" && $k!="page" && $k != "sort"){$str.=$k."=".$v."&";}
			}
			
			$str.="#";
			$str=str_replace("&#","",$str);
			$str=str_replace("#","",$str);
			if(isset($parameter['listsize'])){
				$listsize=$parameter["listsize"];
				if($listsize<5) $listsize=5;
			}else{
				$listsize="5";
			}
			if($listsize%2==0){
				$n1=($listsize/2)-1;
				$n2=$listsize/2;
			}else{
				$n1=$n2=($listsize-1)/2;
			}
			
			$a=$GET['page']-$n1;
			if($a<=0){$n2=$n2+abs($a)+$GET['page']+1;$n1=1;}
			else{$n1=$GET['page']-$n1;$n2=$n2+$GET['page']+1;}
		    if($rows<=$listsize){
				$n1=1;$n2=$rows;
			}
			
			for($i=1;$i<=$rows;$i++){
				if( $n1 <= $i && $i <= $n2 ){
					$list['list'][$i]['text']=$i;
					$list['list'][$i]['link']=zen_href_link($GET['main_page'],$str."&page=".$i);
					if($i==$GET['page']){
						$list['list'][$i]['status']="active";
					}
				}
			}
			if($GET['page']==1){
				$list['next']['text']="Next";
				$list['next']['link']=$list['list'][$GET['page']+1]['link'];
			}
			else if($GET['page']>1 && $GET['page']<$rows){
				$list['prev']['text']="Previous";
				$list['prev']['link']=$list['list'][$GET['page']-1]['link'];
				$list['next']['text']="Next";
				$list['next']['link']=$list['list'][$GET['page']+1]['link'];
			}
			else if($GET['page']==$rows){
				$list['prev']['text']="Previou";
				$list['prev']['link']=$list['list'][$GET['page']-1]['link'];
			}
		
			$list['first']=array('text'=>'Home page','link'=>zen_href_link($GET['main_page'],$str."&page=1"));
			$list['last']=array('text'=>'Last page','link'=>zen_href_link($GET['main_page'],$str."&page=".$rows));
		
			if($GET['page']==1){unset($list['first']);unset($list['prev']);}
			if($GET['page']==$rows){unset($list['last']);unset($list['next']);}
			
		}
		if($parameter['info']){
			$list['info']['count']=$rows;
			$list['info']['prototal']=$total;
			$list['info']['pernum']=$pernum;
			if($total < $GET['page']*$pernum){
				$list['info']['range']=((($GET['page']-1)*$pernum)+1)."-".$total;
			}else{
				$list['info']['range']=((($GET['page']-1)*$pernum)+1)."-".$GET['page']*$pernum;
			}
		}
		
		return $list;
	}
	//获取商品详情
	function get_products_info($pid,$separator=""){
		
		$sql="select p.*,pd.* from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id where p.products_id=".$pid." and pd.language_id=".(int)$_SESSION['languages_id'];
		$products=$this->show_products_list($_GET,$sql,["separator"=>$separator,"products_info"=>true])[0];
		
		if(!$separator){$separator="|||";}
		if(!strstr($products['products_image'],$separator)){$separator="|||";}
		$products['products_image']=array_filter(explode($separator,$products['products_image']))[0];
	
		return $products;
	}
	
	function get_products_detail_image($pid="",$separator=''){
		$sql="select products_image,products_image_detail from ".TABLE_PRODUCTS." where products_id='".$pid."'";
		$products=openzcQuery($sql);
		$products=openzc_table_to_list($products)[0];
		if(!$separator){$separator="|||";}
		if(!strstr($products['products_image'],$separator)){$separator="|||";}

		$index_image=array_filter(explode($separator,$products["products_image"]));
		if(count($index_image)>1){
			//$products["products_image"]=str_replace($index_image[0].$separator,"",$products["products_image"]);
		}else{
			$products["products_image"]=$index_image[0];
		}
		
		$images=array_unique(array_filter(explode($separator,$products["products_image"].$separator.$products["products_image_detail"])));
		
	    $images=$this->get_products_detail_dirimage($index_image[0],$images);
		
		$images=array_filter($images);
		return $images;
	}

	function get_products_detail_dirimage($index_image="",$detail=[]){
		
		if(!$index_image){return false;}
		else{
			$info=explode("/",$index_image);
			$size=count($info);
			
			$images=explode(".",$info[($size-1)]);
			unset($info[($size-1)]);
			foreach($info as $k => $v){
				@$path.=$v."/";
			}
			$images_name=$images[0];
			$images_suffix=$images[1];

			for($i=1;$i<10;$i++){
				$img=$path.$images_name."_0".$i.".".$images_suffix;
				if(is_file("./images/".$img)){$detail[]=$img;}
				$imgs=$path.$images_name."-0".$i.".".$images_suffix;
				if(is_file("./images/".$imgs)){$detail[]=$imgs;}
			}
			$detail=array_unique($detail);
		
			return $detail;
		}
	}
	function get_pagelist_total(){
		global $predata_class;
		$categories=$predata_class->getPredata(TABLE_CATEGORIES);
		switch($_GET['main_page']){
			case "index":
				if(isset($_GET['cPath']) && $_GET['cPath']){
					$current_cid=openzc_get_current_cpath($_GET['cPath']);
					if(!isset($_GET['price']) && !isset($_GET['options']) && !isset($_GET['brand'])){
						return $categories[$current_cid]['count'];
					}
				}else{
					return 0;
				}
			break;
			case FILENAME_SPECIALS:
				$table=" left join ".TABLE_SPECIALS." s on s.products_id=p.products_id ";
				$where=" and s.status=1";
			break;
			case FILENAME_FEATURED_PRODUCTS:
				$table=" left join ".TABLE_FEATURED." f on f.products_id=p.products_id ";
				$where=" and f.status=1";
			break;
			case FILENAME_ADVANCED_SEARCH_RESULT:

				if(!isset($_GET['keyword'])){return 0;}

				$sql="select count(distinct(p.products_id)) as count from products p inner join (select products_id from products_description where language_id=".$_SESSION['languages_id']." and products_name like '%".$_GET['keyword']."%' ) pd on pd.products_id=p.products_id ";
	            
				
			break;
			default:
				return 0;
			break;
		}
		if(isset($_GET['cPath']) && $_GET['cPath']){
			$cid=openzc_get_current_cpath($_GET['cPath']);
			if($categories[$cid]['categories_sub_all_id']!="none"){
				$cid=$categories[$cid]['categories_sub_all_id'];
			}
			$where=" p.master_categories_id in(".$cid.")";
		}
		foreach($_GET as $k => $v){
			switch($k){
				case "brand":
					$brand=array_filter(explode(",",$v));
					$where.=" and p.manufacturers_id in(".join(",",$brand).")";
				break;
				case "price":
					$price=explode(",",$_GET['price']);
					$where.=" and p.products_price_sorter>=".$price[0]." and p.products_price_sorter<=".$price[1];
				break;
				case "options":
					$options=array_filter(explode("|",$v));
					$options_id=[];
					$values_id=[];
					foreach($options as $k => $v){
						$array=array_filter(explode(":",$v));
						$options_id[]=$array[0];
						$values_id[]=join(",",array_filter(explode(",",$array[1])));
					}
					$table="left join ".TABLE_PRODUCTS_ATTRIBUTES." pa on pa.products_id=p.products_id";
					$where.=" and pa.options_id in(".join(",",$options_id).") and pa.options_values_id in(".join(",",$values_id).")";
				break;
			}
		}
		if(!$sql){
			$sql="select count(distinct(p.products_id)) as count from ".TABLE_PRODUCTS." p inner join ".TABLE_PRODUCTS_DESCRIPTION." pd on p.products_id=pd.products_id ".$table." where ".$where." and p.products_status=1 and pd.language_id=".$_SESSION['languages_id'];
		}else{
			$sql.=$table;
			if($where){
				$sql.=" where ".$where;
			}
		}
		//echo $sql;exit;
		$data=openzcQuery($sql);
		
		return $data->fields['count'];
	}
	
	function get_pagelist_pernum(){
		if(array_key_exists("limit",$_GET)){
			$pernum=$_GET['limit'];
		}else{
			$file=TPLCACHE_TPL."tplCacheCount_".md5("tplCacheCount").".inc";
			$json=file_get_contents($file);
			$json=json_decode($json,true);
			$pernum=$json[$_GET['main_page']]['pagesize'];
		}
		return $pernum;
	}
	
}
?>