<?php
// +----------------------------------------------------------------------
// | Sunnyi 多语商城建站系统 (Build on ThinkPHP)
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://www.sunnyi.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 商易网络(admin@sunnyi.cn)
// +----------------------------------------------------------------------

//商品
class GoodsModel extends MultiLangModel  {
	/**
	 * 查询商品列表
	 */
	public function getGoodsList($condition='',$limit=10,$order='sort desc')
	{
		$curr_lang_id = D("LangConf")->where("lang_name ='".FANWE_LANG_SET."'")->getField('id');
		$list = $this->where($condition)->order($order)->limit($limit)->findAll();
		foreach($list as $k=>$v)
		{
			if(sunnyiC("URL_ROUTE")==1)
			$list[$k]['url'] = U("goods/".$v['id']);
			elseif(sunnyiC("URL_ROUTE")==2)
			{
				$arr = explode(" ",$v['name_'.FANWE_LANG_ID]);
				$url = '';
				$py = new Pinyin();
				foreach($arr as $idx => $ar)
				{
					$ar = $py->complie($ar);
					$prefix = "";
					$prefix = preg_replace("/\d/","",$ar);
					$prefix = preg_replace("/[^a-zA-Z-]/","",$prefix);
					$url.=$prefix.C("URL_PATHINFO_DEPR");
				}
				$url=strtolower($url);
				$list[$k]['url'] = 'g'.C("URL_PATHINFO_DEPR").$url.$v['id'].C("URL_HTML_SUFFIX"); 
			}
			else
			$list[$k]['url'] = U("Goods/show",array('id'=>$v['id']));
			$list[$k]['short'] = msubstr($v['name_'.$curr_lang_id],0,sunnyiC("GOODS_SHORT_NAME"));
			$list[$k]['update_time_format']  = toDate($v['update_time']);
			$list[$k]['create_time_format']  = toDate($v['create_time']);
			$list[$k]['promote_begin_time_format']  = toDate($v['promote_begin_time']);
			$list[$k]['promote_end_time_format']  = toDate($v['promote_end_time']);			
			$list[$k]['promote_price_format'] = formatPrice($v['promote_price']);
			$list[$k]['market_price_format'] = formatPrice($v['market_price']);
			$list[$k]['shop_price_format'] = formatPrice($v['shop_price']);
			$list[$k]['score_format'] = formatScore($v['score']);
			$list[$k]['max_score_format'] = formatScore($v['max_score']);
			
			//开始处理会员价
			if($_SESSION['user_id']&&$_SESSION['user_id']>0)
			{
				$user_group = D("UserGroup")->where("id=".$_SESSION['group_id'])->find();				
				$user_discount = floatval($user_group['discount'])==0?1:floatval($user_group['discount']);
				$define_price = floatval(D("UserGroupPrice")->where("goods_id=".$v['id']." and user_group_id=".$user_group['id']." and spec_item_id = 0")->getField("user_price"));
				if($define_price>0)
				{
					$list[$k]['member_price']	=	$define_price;
					$list[$k]['member_price_format']	=	formatPrice($define_price);
				}
				else 
				{
					$list[$k]['member_price']	=	$list[$k]['shop_price']*$user_discount;
					$list[$k]['member_price_format']	=	formatPrice($list[$k]['member_price']);
				}
			}
			
			//开始输出商品积分			
			$list[$k]['score'] = round(D("Message")->where("status=1 and rec_module='Goods' and rec_id=".$list[$k]['id'])->avg("score"),0);
			
			if($v['small_img']=='')
				$list[$k]['small_img'] = sunnyiC("NO_PIC");
			if($v['big_img']=='')
				$list[$k]['big_img'] = sunnyiC("NO_PIC");
			if($v['origin_img']=='')
				$list[$k]['origin_img'] = sunnyiC("NO_PIC");
				
			$list[$k]['review'] = D("Message")->where("status=1 and rec_module='Goods' and rec_id=".$list[$k]['id'])->count();
		}
		return $list;
	}
	
	/**
	 * 查询单款商品
	 */
	public function getGoodsItem($condition='',$is_full=false)
	{
		$curr_lang_id = D("LangConf")->where("lang_name ='".FANWE_LANG_SET."'")->getField('id');
		$item = $this->where($condition)->find();
		if($item)
		{
			if(sunnyiC("URL_ROUTE")==1)
			$item['url'] = U("goods/".$item['id']);
			elseif(sunnyiC("URL_ROUTE")==2)
			{
				$arr = explode(" ",$item['name_'.FANWE_LANG_ID]);
				$url = '';
				$py=new Pinyin();
				foreach($arr as $idx => $ar)
				{
					$ar = $py->complie($ar);
					$prefix = "";
					$prefix = preg_replace("/\d/","",$ar);
					$prefix = preg_replace("/[^a-zA-Z-]/","",$prefix);
					$url.=$prefix.C("URL_PATHINFO_DEPR");
				}
				$url=strtolower($url);
				$item['url'] = 'g'.C("URL_PATHINFO_DEPR").$url.$item['id'].C("URL_HTML_SUFFIX"); 
			}
			else
			$item['url'] = U("Goods/show",array('id'=>$item['id']));
			$item['short'] = msubstr($item['name_'.$curr_lang_id],0,sunnyiC("GOODS_SHORT_NAME"));
			$item['update_time_format']  = toDate($item['update_time']);
			$item['create_time_format']  = toDate($item['create_time']);
			$item['promote_begin_time_format']  = toDate($item['promote_begin_time']);
			$item['promote_end_time_format']  = toDate($item['promote_end_time']);			
			$item['promote_price_format'] = formatPrice($item['promote_price']);
			$item['market_price_format'] = formatPrice($item['market_price']);
			$item['shop_price_format'] = formatPrice($item['shop_price']);
			$item['weight_format'] = formatWeight($item['weight'],$item['id']);
			$item['score_format'] = formatScore($item['score']);
			$item['max_score_format'] = formatScore($item['max_score']);
			
			//开始处理会员价
			if($_SESSION['user_id']&&$_SESSION['user_id']>0)
			{
				$user_group = D("UserGroup")->where("id=".$_SESSION['group_id'])->find();				
				$user_discount = floatval($user_group['discount'])==0?1:floatval($user_group['discount']);
				$define_price = floatval(D("UserGroupPrice")->where("goods_id=".$item['id']." and user_group_id=".$user_group['id']." and spec_item_id = 0")->getField("user_price"));
				if($define_price>0)
				{
					$item['member_price']	=	$define_price;
					$item['member_price_format']	=	formatPrice($define_price);
				}
				else 
				{
					$item['member_price']	=	$item['shop_price']*$user_discount;
					$item['member_price_format']	=	formatPrice($item['member_price']);
				}
			}
			if($item['small_img']=='')
				$item['small_img'] = sunnyiC("NO_PIC");
			if($item['big_img']=='')
				$item['big_img'] = sunnyiC("NO_PIC");
			if($item['origin_img']=='')
				$item['origin_img'] = sunnyiC("NO_PIC");
			if($is_full) //全部查询
			{	
				//扩展查询相关数据
				$item['brand_info'] = D("Brand")->getBrandItem(array('id'=>$item['brand_id']));
				$item['cate_info'] = D("GoodsCate")->getGoodsCateItem(array('id'=>$item['cate_id']));
				$gallery = D("GoodsGallery")->where('goods_id='.$item['id'])->findAll();
				if($gallery)
				$item['gallery_info'] = $gallery;
				else 
				$item['gallery_info'] = array(array('small_img'=>$item['small_img'],'big_img'=>$item['big_img'],'origin_img'=>$item['origin_img']));
				$item['type_info'] = D("GoodsType")->getGoodsTypeItem(array('id'=>$item['type_id']));
				
				//获取可选与唯一属性
				$attr_ids = D("GoodsAttr")->where(array('goods_id'=>$item['id']))->field("attr_id")->findAll();
				$only_attr_ids = array();
				$select_attr_ids = array();
				
				foreach($attr_ids as $row)
				{
					if(D("GoodsTypeAttr")->where("id=".$row['attr_id'])->getField("attr_type")==1)
					{
						$select_attr_ids[]=$row['attr_id'];
					}
					else 
					{
						$only_attr_ids[]=$row['attr_id'];
					}
				}
				$item['attr_list'] = D("GoodsAttr")->getGoodsAttrList(array('goods_id'=>$item['id'],'attr_id'=>array('in',$select_attr_ids)));
				$item['only_attr_list'] = D("GoodsAttr")->getGoodsAttrList(array('goods_id'=>$item['id'],'attr_id'=>array('in',$only_attr_ids)));
				//开始输出商品积分			
				$item['score'] = round(D("Message")->where("status=1 and rec_module='Goods' and rec_id=".$item['id'])->avg("score"),0);
				$item['review'] = D("Message")->where("status=1 and rec_module='Goods' and rec_id=".$item['id'])->count();
				}
	
		}
		return $item;
	}

	/**
	 * 用于搜索商品列表的通用方法
	 *
	 * @param integer $cate_id 			分类ID
	 * @param integer $brand_id 		品牌ID
	 * @param integer $type_id			商品类型ID
	 * @param string $keywords			关键词
	 * @param array $attr_value			属性值 结构为 array(attr_id=>attr_value,attr_id=>attr_value)
	 * @param string $rec_type			推荐商品的属性词 is_best/is_hot/is_promote
	 * @param float $min_price			价格区间最小值
	 * @param float $max_price			价格区间最大值
	 * @param int $page					当前页
	 * @param string $sort				排序
	 * @param array spec_search_list    规格
	 */
	public function searchGoodsList($cate_id=0, $brand_id=0, $type_id=0, $keywords='', $attr_value='', $rec_type='', $min_price=0, $max_price=0, $page=1, $sort='sort desc',$spec_search_list='')
	{
		$condition['status'] = 1;
		//分类条件
		if($cate_id>0)
		{
			$childIds = D("GoodsCate")->getChildIds($cate_id);
			$childIds[] = $cate_id;
			$condition['cate_id'] = array('in',$childIds);
		}
		//品牌条件
		if($brand_id>0)
		{
			$condition['brand_id'] = $brand_id;
		}
		// 商品类型
		if($type_id>0)
		{
			$condition['type_id'] = $type_id;
		}
		//价格区间
		if($min_price>0||$max_price>0)
		{
			//处理当前价格的比率
			$currency_item = Session::get("sunnyi_currency");
			$min_price /= $currency_item['radio'];
			$max_price /= $currency_item['radio']; 
			if($min_price>0&&$max_price==0)
			{
				$condition['shop_price'] = array('gt',$min_price);
			}
			if($min_price==0&&$max_price>0)
			{
				$condition['shop_price'] = array('lt',$max_price);
			}
			if($min_price>0&&$max_price>0)
			{
				$condition['shop_price'] = array(array('gt',$min_price),array('lt',$max_price));
			}			
		}
		
		//推荐类型
		if($rec_type!='')
		{
			if($rec_type!='is_promote')
			{
				$condition[$rec_type]=1;
			}
			else 
			{
				$now = gmtTime();
				$condition['promote_begin_time'] = array('lt',$now);
				$condition['promote_end_time'] = array('gt',$now);
			}
		}
		
		$lang_env_id = FANWE_LANG_ID;
		//关键词
		if($keywords!='')
		{
			$keywords = urldecode($keywords);
			$keywords_arr = explode(" ",$keywords);
			$condition_or['name_'.$lang_env_id] = array();
			$condition_or['brief_'.$lang_env_id] = array();
			$condition_or['goods_desc_'.$lang_env_id] = array();
			$condition_or['sn'] = array();
			//实现检索数据，从品名/关键词/商品属性中进行like检索
			foreach($keywords_arr as $keyword_item)
			{
				array_push($condition_or['name_'.$lang_env_id],array('like',"%".$keyword_item."%"));
				array_push($condition_or['brief_'.$lang_env_id],array('like',"%".$keyword_item."%"));
				array_push($condition_or['goods_desc_'.$lang_env_id],array('like',"%".$keyword_item."%"));	
				array_push($condition_or['sn'],array('like',"%".$keyword_item."%"));				
			}
				array_push($condition_or['name_'.$lang_env_id],'or');
				array_push($condition_or['brief_'.$lang_env_id],'or');
				array_push($condition_or['goods_desc_'.$lang_env_id],'or');	
				array_push($condition_or['sn'],'or');	
				
				$condition_or['_logic'] = 'or';
				$condition['_complex'] = $condition_or;
		}

		//属性
		if($attr_value&&$attr_value!=""&&is_array($attr_value))
		{			
			$count_idx = 0;
			foreach($attr_value as $attr_id=>$value)
			{
				if($value&&$value!="")
				{
					$attr_condition_str = "attr_id=".$attr_id." and attr_value_".$lang_env_id." like '%".$value."%'";
					$result = D("GoodsAttr")->where($attr_condition_str)->findAll();
					
					if($count_idx==0)
					{
						$goods_ids = array();
						foreach($result as $row)
						{
							$goods_ids[] = $row['goods_id'];
						}
						
					}
					else
					{
						$current_goods_ids = array();
						foreach($result as $row)
						{
							$current_goods_ids[] = $row['goods_id'];
						}
						$goods_ids = array_intersect($goods_ids,$current_goods_ids);
					}
					
					$count_idx++;
				}
				
			}
		}
		
		
		//规格
		if($spec_search_list&&$spec_search_list!=""&&is_array($spec_search_list))
		{
			$count_idx = 0;
			foreach($spec_search_list as $spec_type_id=>$spec_value)
			{
				$spec_res = D("GoodsSpec")->where("session_id='' and spec_name_".FANWE_LANG_ID."='".$spec_value."'")->findAll();
				$spec_ids = array();
				foreach($spec_res as $row)
				{
					$spec_ids[] = $row['id'];
				}
				if(count($spec_ids)>0)
				{
					$spec_ids = implode(",",$spec_ids);
				}

				if(count($spec_ids)>0)
				{
					$result = D("GoodsSpecItem")->where("(spec1_type_id=".$spec_type_id." and spec1_id in(".$spec_ids.")) or (spec2_type_id=".$spec_type_id." and spec2_id in(".$spec_ids."))")->field("goods_id")->findAll();
									
					if($count_idx==0&&!isset($goods_ids))
					{
						$goods_ids = array();
						foreach($result as $row)
						{
							$goods_ids[] = $row['goods_id'];
						}						
					}
					else
					{
						$current_spec_goods_ids = array();
						foreach($result as $row)
						{
							$current_spec_goods_ids[] = $row['goods_id'];
						}					
						$goods_ids = array_intersect($goods_ids,$current_spec_goods_ids);
					}					
					$count_idx++;
				}
			}
		}
		
		if(isset($goods_ids))
		$condition['id'] = array('in',$goods_ids);
		
		
		//开始处理分页
		$page_size = $page;
		$page_count = sunnyiC("GOODS_PAGE_LISTROWS");
		$limit = ($page_size-1)*$page_count.",".$page_count;
		
		if($sort=='')
		{
			$sort = 'sort desc';
		}

		$result['goods_list'] = $this->getGoodsList($condition,$limit,$sort);
		$result['goods_total']	= $this->where($condition)->count();
		
		if($result['goods_list'])
		{
			foreach($keywords_arr as $keywords_item)
			{
				if(A("Sunnyi")->check_ip_operation(get_client_ip(),"Keywords",30,$keywords_item))
		    	{
		    		if(M("Keywords")->where("keywords='".$keywords_item."' and lang_id=".FANWE_LANG_ID)->count()==0)
		    		{
		    			M("Keywords")->add(array('keywords'=>$keywords_item,'lang_id'=>FANWE_LANG_ID));
		    		}
		    		else 
		    		{
		    			M("Keywords")->where("keywords='".$keywords_item."' and lang_id=".FANWE_LANG_ID)->setInc("click_count");
		    		}
		    	}
			}
			foreach($attr_value as $attr_v)
			{
				if(A("Sunnyi")->check_ip_operation(get_client_ip(),"Keywords",30,$attr_v))
		    	{
		    		if(M("Keywords")->where("keywords='".$attr_v."' and lang_id=".FANWE_LANG_ID)->count()==0)
		    		{
		    			M("Keywords")->add(array('keywords'=>$attr_v,'lang_id'=>FANWE_LANG_ID));
		    		}
		    		else 
		    		{
		    			M("Keywords")->where("keywords='".$attr_v."' and lang_id=".FANWE_LANG_ID)->setInc("click_count");
		    		}
		    	}
			}
		}
    	
		return $result;
	}
	
//销售排行
	public function getTopSale($limit='10',$cate_id = 0)
	{
		$where = " where o.status = 1 ";
		if($cate_id>0)
		{
			
			$ids = D("GoodsCate")->getChildIds($cate_id);
			$ids[] = $cate_id;
			
			$condition['cate_id'] = array("in",$ids);
			$condition['status'] = 1;
			$goods_list = D("Goods")->where($condition)->findAll();
			foreach($goods_list as $v)
			{
				$goods_ids[] = $v['id'];
			}
	
			
			if(count($goods_ids)>0) 
				$goods_ids = implode(",",$goods_ids);
			else
				$goods_ids = 0;
			
			$where.=" and gsi.goods_id in (".$goods_ids.")";
			
		}
		$sql = "select sum(number) as total_number,gsi.goods_id as gid from ".C("DB_PREFIX")."order_goods as og left join ".
				C("DB_PREFIX")."order as o on og.order_id=o.id left join ".
				C("DB_PREFIX")."goods_spec_item as gsi on og.rec_id=gsi.id ".				
				$where.
				" group by gsi.goods_id order by sum(number) desc limit ".$limit;

		
		$list = D()->query($sql);
		foreach($list as $k=>$v)
		{
			$list[$k] = $this->getGoodsItem("id=".$v['gid']);
		}
		return $list;
	}
	
	//指定商品的优惠
	public function getGoodsPromote($goods_id)
	{
		$now = gmtTime();
		$session_id = Session::id();
		//获取使用的优惠券并取得相关促销ID
	    	$sql = " select promote.id as id from ".C("DB_PREFIX")."cart_card as cart_card ".
	    		   " left join ".C("DB_PREFIX")."promote_card as promote_card on cart_card.card_code = promote_card.card_code".
	    		   " left join ".C("DB_PREFIX")."promote as promote on promote_card.promote_id = promote.id ".
	    		   " where cart_card.session_id='".$session_id."'";
	    	$card_promote = D()->query($sql);
	    	$card_promote_id = intval($card_promote[0]['id']);
	    	
		$sql = "select * from ".C("DB_PREFIX")."promote_user_group as promote_user_group ".
	    				   "left join ".C("DB_PREFIX")."promote as promote on promote_user_group.promote_id = promote.id ".
	    				   " where promote_user_group.user_group_id = ".intval($_SESSION['group_id']).
	    				   " and promote.id in (select promote_child.promote_id from ".C("DB_PREFIX")."promote_child as promote_child ".
	    				   " where promote_child.module_name='Goods' and rec_id=".$goods_id.")".
	    				   " and promote.promote_begin_time<=".$now.
	    				   " and promote.promote_end_time>=".$now.
	    			  	   " and (promote.is_card = 0 or promote.id = ".$card_promote_id.")".
	    				   " and promote.status = 1 ".
	    				   " and promote.promote_type_id in(2,3) ".
	    				   " order by promote.priority desc";
	    $promote_list = D()->query($sql);  
	    return $promote_list;  		
	}
}
?>