<?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 GoodsAction extends SunnyiAction{
	public function __construct()
	{
		parent::__construct();
		//输出显示方式
		$list_type = intval(Session::get("list_type"));
		$this->assign("list_type",$list_type);		
	}
	public function _index()
	{
		$this->index($_REQUEST);
	}
	//商品列表
    public function index($rec_type = '',$request){
    	    	
       	if($request)
		{
			$_REQUEST = $request;
		}
		
    	//初始化分页
    	$page = intval($_REQUEST[C("VAR_PAGE")]);
    	if($page==0)
    	$page = 1;
    	$this->assign("page",$page);
    	
    	//分类ID
    	$cate_id = intval($_REQUEST['id']);
    	$this->assign('cate_id',$cate_id);
    	
    	//排序
    	$sort = '';
    	if($_REQUEST['sort_field'])
    	{
    		$sort = $_REQUEST['sort_field'];  
    		$this->assign("sort_field",$_REQUEST['sort_field']);
    	}
    	if($_REQUEST['sort_type'])
    	{
    		$sort.=" ".$_REQUEST['sort_type']; 	
    		$this->assign("sort_type",$_REQUEST['sort_type']);
    	}

    	//推荐类型    	
    	if($_REQUEST['rec']&&$_REQUEST['rec']!='')
    	{
    		$rec_type = $_REQUEST['rec'];
    	}
    	
    	
    	//查询当前页商品数据
    	$goods_result = D("Goods")->searchGoodsList($cate_id,$brand_id=0,$type_id=0,$keywords='',$attr_value='',$rec_type, $min_price=0,$max_price=0,$page,$sort);
    	
    	//输出分类下的商品列表
    	$this->assign("goods_list",$goods_result['goods_list']);
    	
    	//输出分类信息
    	$cate_info = D("GoodsCate")->getGoodsCateItem(array('id'=>$cate_id));    	
    	if($cate_info&&$cate_info['id']!=0)
    	{
    		$this->assign("page_title",$cate_info['name_'.FANWE_LANG_ID]);
    		$navs = array('name'=>$cate_info['name_'.FANWE_LANG_ID],'url'=>$cate_info['url']);
    	}
    	elseif($rec_type!='')
    	{
    		$this->assign("page_title",L(strtoupper($rec_type)));
    		$navs = array('name'=>L(strtoupper($rec_type)),'url'=>U("Goods/index",array('rec'=>$rec_type)));
    	}
    	else
    	{
    		$this->assign("page_title",L("GOODS_LIST"));
    		$navs = array('name'=>L("GOODS_LIST"),'url'=>U("Goods/index"));
    	}
    	
    	
    	
    	//分页
		$page = new Page($goods_result['goods_total'],sunnyiC("GOODS_PAGE_LISTROWS"));   //初始化分页对象 		
		$p  =  $page->show();
        $this->assign('pages',$p);
        //end 分页  
        
        
        //输出当前页seo内容
    	$data = array(
    		'navs' => array(
    			$navs,
    		),
    		
    		'keyword'=>	$cate_info['seokeyword_'.FANWE_LANG_ID]!=''?$cate_info['seokeyword_'.FANWE_LANG_ID]:$cate_info['name_'.FANWE_LANG_ID].",".$cate_info['seokeyword_'.FANWE_LANG_ID],
    		'content'=>	$cate_info['seocontent_'.FANWE_LANG_ID]!=''?$cate_info['seocontent_'.FANWE_LANG_ID]:$cate_info['name_'.FANWE_LANG_ID].",".$cate_info['seokeyword_'.FANWE_LANG_ID],
    	);
    	$this->assignSeo($data);    	
    	$this->display("Page:goods_index");
    }
    
	
	//高级搜索页
    public function advSearch()
    {  
    	//初始化分页
	    $page = intval($_REQUEST[C("VAR_PAGE")]);
	    if($page==0) $page = 1;   
	    	 	
    	if($_REQUEST['base64']!='')
    	{    		
    		$str = base64_decode($_REQUEST['base64']);
    		$base64_request = unserialize($str);
    		foreach($base64_request as $k=>$v)
    		{
    			$_REQUEST[$k] = $v;
    		}
    	} 
    	else 
    	{    	
    		$request_str = base64_encode(serialize($_REQUEST));  
    		C("URL_MODEL",0);
			redirect(U("Goods/advSearch",array('base64'=>$request_str,C('VAR_PAGE')=>$page)));			
    	} 	    	    	
    	$navs = array('name'=>L("ADV_SEARCH"),'url'=>U("Goods/advSearch"));
    	$data = array(
    		'navs' => array(
    			$navs,
    		),
    		'keyword'=>	'',
    		'content'=>	'',
    	);
    	$this->assignSeo($data);  
    	
    	//输出分类列表
    	$cate_list = D("GoodsCate")->getGoodsCateList();
    	$cate_list = D("GoodsCate")->toFormatTree($cate_list,array('name_'.FANWE_LANG_ID));
    	$this->assign("cate_list",$cate_list);
    	
    	//输出品牌
    	$brand_list = D("Brand")->getBrandList();
    	$this->assign("brand_list",$brand_list);
    	
    	//输出类型
    	$type_list = D("GoodsType")->getGoodsTypeList();
    	$this->assign("type_list",$type_list);
		
    	//输出规格列表
    	$spec_list = D("GoodsSpec")->getSpecList();
    	$this->assign("spec_list",$spec_list);
    	
    	if($_REQUEST['search']||$_REQUEST[C("VAR_PAGE")])  //有提交按钮或有分页参数时
    	{
    	//开始处理搜索
		
    	$this->assign("page",$page);
    	
    	//分类ID
    	$cate_id = intval($_REQUEST['cate_id']);
    	$this->assign('cate_id',$cate_id);
    	
    	//品牌ID
    	$brand_id = intval($_REQUEST['brand_id']);
    	$this->assign('brand_id',$brand_id);
    	
    	//类型ID
    	$type_id = intval($_REQUEST['type_id']);
    	$this->assign('type_id',$type_id);

    	
    	//相关属性
    	$attr_list = D("GoodsTypeAttr")->where("type_id=".$type_id)->findAll();
    	foreach($attr_list as $k=>$v)
    	{    		
	    	$attr_value[$v['id']] = urldecode($_REQUEST['attr_value_'.$v['id']]);    	
    		$attr_list[$k]['value'] = $attr_value[$v['id']];
    	}
    	$this->assign('attr_list',$attr_list);

    	
    	//相关规格
    	$spec_search_list = $_REQUEST['spec_type'];
    	foreach($spec_search_list as $k=>$v)
    	{
    		$spec_search_list[$k] = urldecode($v);
    	}
    	$this->assign("spec_search_list",$spec_search_list);
    	
    	//关键词
    	$keywords = trim($_REQUEST['keywords']);
    	$keywords = urldecode($keywords);
    	$this->assign('keywords',$keywords);

    	
    	
    	
    	//最大价
    	$max_price = floatval($_REQUEST['max_price']);
    	$this->assign('max_price',$max_price);
    	
    	//最小价
    	$min_price = floatval($_REQUEST['min_price']);
    	$this->assign('min_price',$min_price);
    	
    	
    	//排序
    	$sort = '';
    	if($_REQUEST['sort_field'])
    	{
    		$sort = $_REQUEST['sort_field'];  
    		$this->assign("sort_field",$_REQUEST['sort_field']);
    	}
    	if($_REQUEST['sort_type'])
    	{
    		$sort.=" ".$_REQUEST['sort_type']; 	
    		$this->assign("sort_type",$_REQUEST['sort_type']);
    	}

    	//推荐类型
    	$rec_type = '';
    	
    	
    	
    	//查询当前页商品数据
    	$goods_result = D("Goods")->searchGoodsList($cate_id,$brand_id,$type_id,$keywords,$attr_value,$rec_type, $min_price,$max_price,$page,$sort,$spec_search_list);
    	
    	//输出分类下的商品列表
    	$this->assign("goods_list",$goods_result['goods_list']);
    	
    	   	
    	
    	
    	//分页
    	$current_url_model = C("URL_MODEL");
    	C("URL_MODEL",0);
		$page = new Page($goods_result['goods_total'],sunnyiC("GOODS_PAGE_LISTROWS"));   //初始化分页对象 		
		$p  =  $page->show();
        $this->assign('pages',$p);
        C("URL_MODEL",$current_url_model);
        //end 分页  
        
    	} //判断是否显示搜索结果 end

    	
    	
    	$this->display("Page:goods_adv_search");
    }
    
	//选购中心页
	public function pick()
	{    	
		$type_id = intval($_REQUEST['type_id']);    //类型ID		
		$attr_id = intval($_REQUEST['attr_id']);	//属性ID
		$value = trim($_REQUEST['attr_value']);    	
    	$value = urldecode($value);    	
		$attr_value = array($attr_id=>$value);  //用于搜索的属性条件
		
		if($attr_id>0)
		{
			$type_id = D("GoodsTypeAttr")->where("id=".$attr_id)->getField("type_id");
		}
		$this->assign('type_id',$type_id);
		$this->assign('attr_id',$attr_id);
		$this->assign('attr_value',$value);
		
		if($type_id>0)
		{
			$type_list = D("GoodsType")->getGoodsTypeList("id=".$type_id);
		}
		else
		{			
			$type_list = D("GoodsType")->getGoodsTypeList();			
		}
		
		//end 获取商品类型列表
		foreach($type_list as $k=>$v)
		{
			$attr_list = D("GoodsTypeAttr")->where("type_id=".$v['id'])->findAll();
			//开始查询每组属性的值
			foreach($attr_list as $kk=>$vv)
			{
				$value_list_res = D("GoodsAttr")->getGoodsAttrList(array('attr_id'=>$vv['id']));
				$value_list = array(); //清空上轮的赋值
				foreach($value_list_res as $attr_id_key=>$vvv)
				{
					//开始将同值的属性值过滤掉			
					
						foreach($vvv['attr_value'] as $attr_value_item)
						{
							foreach($attr_value_item['value_list'] as $value_item)
							{
								$value_list[$value_item['url']] = $value_item;   //按相同的筛选地址归档
							}
						}
					
				}
				$attr_list[$kk]['value_list'] = $value_list;
			}
			$type_list[$k]['attr_list'] = $attr_list;
		}
		
		$this->assign('type_list',$type_list);
		
		//开始搜索相关商品
		//查询当前页商品数据
	  	//初始化分页
    	$page = intval($_REQUEST[C("VAR_PAGE")]);
    	if($page==0)
    	$page = 1;
    	$this->assign("page",$page);
    	
    	//排序
    	$sort = '';
    	if($_REQUEST['sort_field'])
    	{
    		$sort = $_REQUEST['sort_field'];  
    		$this->assign("sort_field",$_REQUEST['sort_field']);
    	}
    	if($_REQUEST['sort_type'])
    	{
    		$sort.=" ".$_REQUEST['sort_type']; 	
    		$this->assign("sort_type",$_REQUEST['sort_type']);
    	}
    	$goods_result = D("Goods")->searchGoodsList($cate_id=0,$brand_id=0,$type_id,$keywords='',$attr_value,$rec_type='', $min_price=0,$max_price=0,$page,$sort);
		$this->assign("goods_list",$goods_result['goods_list']);
		
		//分页
		$page = new Page($goods_result['goods_total'],sunnyiC("GOODS_PAGE_LISTROWS"));   //初始化分页对象 		
		$p  =  $page->show();
        $this->assign('pages',$p);
        //end 分页  
        
        
        //输出当前页seo内容
        $navs = array('name'=>L("PICK_OUT"),'url'=>U("Goods/pick"));
    	$data = array(
    		'navs' => array(
    			$navs,
    		),
    		'keyword'=>	$cate_info['name_'.FANWE_LANG_ID].",".$cate_info['seokeyword_'.FANWE_LANG_ID],
    		'content'=>	$cate_info['name_'.FANWE_LANG_ID].",".$cate_info['seocontent_'.FANWE_LANG_ID],
    	);
    	$this->assignSeo($data);    
    	
    	$this->display("Page:goods_pick");
		
	}
    
    
    //获取相应类型下的属性列表，用于搜索
    public function getTypeAttrList()
    {
    	$type_id = intval($_REQUEST['type_id']);
    	$attr_list = D("GoodsTypeAttr")->where("type_id=".$type_id)->findAll();
    	foreach($attr_list as $k=>$v)
    	{
    		$attr_list[$k]['name'] = $v['name_'.FANWE_LANG_ID];
    	}
    	echo json_encode($attr_list);
    }
    
    //商品展示
    public function show()
    {
    	$goods_id = intval($_REQUEST['id']);
    	if($this->check_ip_operation(get_client_ip(),"Goods",1200,$goods_id))
    	D("Goods")->where(array('id'=>$goods_id,'status'=>1))->setInc("click_count");
    	$goods_item  = D("Goods")->getGoodsItem(array('id'=>$goods_id,'status'=>1),true);
    	if($goods_item&&intval($goods_item['id'])!=0)
    	{
    		$spec_list = D("GoodsSpec")->getGoodsSpecList($goods_id);
    		//有规格清空商品相关数据
    		if($spec_list)
    		{
    			//$goods_item['sn'] = '';
    			//$goods_item['market_price_format'] = '';
    			$goods_item['shop_price_format'] = '';
    			$goods_item['member_price_format'] = '';
    			$goods_item['stock'] = '';
    			$goods_item['weight_format'] = '';
    		}
    		$this->assign("goods_info",$goods_item);
    		
    		//输出当前商品的规格配置表
    		$this->assign("spec_list",$spec_list);
    		
    		$this->assign("promote_list",D("Goods")->getGoodsPromote($goods_id));
    		    		
    		$cate_navs = array('name'=>$goods_item['cate_info']['name_'.FANWE_LANG_ID],'url'=>$goods_item['cate_info']['url']);
    		$goods_navs = array('name'=>$goods_item['name_'.FANWE_LANG_ID],'url'=>$goods_item['url']);
    		//输出当前页seo内容
	    	$data = array(
	    		'navs' => array(
	    			$cate_navs,
	    			$goods_navs,
	    		),
	    		'keyword'=> $goods_item['seokeyword_'.FANWE_LANG_ID]!=''?$goods_item['seokeyword_'.FANWE_LANG_ID]:$goods_item['cate_info']['name_'.FANWE_LANG_ID].",".$goods_item['name_'.FANWE_LANG_ID],
	    		'content'=>	$goods_item['seocontent_'.FANWE_LANG_ID]!=''?$goods_item['seocontent_'.FANWE_LANG_ID]:$goods_item['cate_info']['name_'.FANWE_LANG_ID].",".$goods_item['name_'.FANWE_LANG_ID],
	    	);
	    	$this->assignSeo($data);  

	    	//上一款/下一款
//	    	$cate_ids = D("GoodsCate")->getChildIds($goods_item['cate_id']);
//	    	$cate_ids[] = $goods_item['cate_id'];
//	    	$cate_ids = implode(",",$cate_ids);
	    	
	    	$cate_ids = $goods_item['cate_id'];
	    	
			$next_id = D("Goods")->where("id>".$goods_item['id']." and cate_id in(".$cate_ids.")")->order("id asc")->getField("id");
			$prev_id = D("Goods")->where("id<".$goods_item['id']." and cate_id in(".$cate_ids.")")->order("id desc")->getField("id");
    		$this->assign("next_item",D("Goods")->getGoodsItem(array('id'=>$next_id,'status'=>1)));
    		$this->assign("prev_item",D("Goods")->getGoodsItem(array('id'=>$prev_id,'status'=>1)));
    	    
    		
    		$this->assign("relate_best_goods",$this->getRelateGoods($goods_item['id'],sunnyiC("RELATE_GOODS_COUNT"),'is_best'));
    		$this->assign("relate_hot_goods",$this->getRelateGoods($goods_item['id'],sunnyiC("RELATE_GOODS_COUNT"),'is_hot'));
    	}
    	else 
    	{
    		$this->error(L("NO_GOODS"));
    	}
    	
    	//初始化分页
    	$page = intval($_REQUEST[C("VAR_PAGE")]);
    	if($page==0)
    	$page = 1;
    	
    	$result = D("Message")->getMessageList('Goods',$goods_id,$page);
    	$this->assign("message_list",$result['message_list']);
    	//分页
		$page = new Page($result['message_total'],sunnyiC("ARTICLE_PAGE_LISTROWS"));   //初始化分页对象 		
		$p  =  $page->show();
        $this->assign('pages',$p);
        //end 分页  

		if(sunnyiC("IS_INQUIRY")!=1&&$goods_item['is_inquiry']!=1)
    	$this->display("Page:goods_show");
    	else
    	$this->display("Page:goods_inquiry_show");
    }

    public function isBest()
    {
    	$this->index('is_best');
    }
    public function isHot()
    {
    	$this->index('is_hot');
    }
	public function isPromote()
    {
    	$this->index('is_promote');
    }
    
    //获取相关商品
    private function getRelateGoods($goods_id=0,$limit=10,$rec_type='is_best')
    {
       $goods_item = D("Goods")->getById($goods_id);
	   $cate_ids = D("GoodsCate")->getChildIds($goods_item['cate_id']);
	   $cate_ids[] = $goods_item['cate_id'];
	   $cate_ids = implode(",",$cate_ids);
	   if($rec_type=="is_best"||$rec_type=="is_hot")
	   $relate_goods = D("Goods")->getGoodsList("cate_id in(".$cate_ids.") and status=1 and id<>$goods_id and ".$rec_type." =1",$limit);
	   else 
	   $relate_goods = D("Goods")->getGoodsList("cate_id in(".$cate_ids.") and status=1 and id<>$goods_id ",$limit);
	  
	   return $relate_goods;
    }
    
    
    
    
    public function getSpecItem()
    {
    	$goods_id = intval($_REQUEST['goods_id']);
    	$str = urldecode($_REQUEST['str']);
    	$spec_conf = array();
    	if($str!='')
    	{
    		$str_arr = explode(",",$str);
    		foreach($str_arr as $str_item)
    		{
    			$str_item = explode("_",$str_item);
    			$spec_conf[$str_item[0]] = $str_item[1];
    		}
    	}
    	
    	$spec_item_id = intval(D("GoodsSpecItem")->getSpecItemId($spec_conf,$goods_id));
    	
    	$num = intval($_REQUEST['num']);
    	$choose_msg = D("GoodsSpecItem")->makeChooseMsg($spec_conf,$goods_id);
    	$goods['choose_msg'] = $choose_msg;
    	$goods['status'] = true;
		if($spec_item_id!=0)
		{
			$goods_info = D("GoodsSpecItem")->getGoodsSpecItem($spec_item_id);
		}
		if(!$goods_info)
		{ 
			$msg = D("GoodsSpecItem")->makeErrorMsg($spec_conf,$goods_id);			
    		$goods['shop_price_format'] = $msg;
	    	//$goods['market_price_format'] = $msg;
	    	$goods['promote_price_format'] = $msg;
	    	$goods['weight_format'] = $msg;
	    	$goods['stock'] = $msg;
    		$goods['member_price_format'] = $msg;

	   		$goods['total_price_format']  =$msg;
	   		$goods['sn'] = D("Goods")->where("id=".$goods_id)->getField('sn');
   			$goods['spec_item_id'] = 0;
   			$goods['status'] = false;
			echo json_encode($goods);
			exit;
		}
		
    	
    	//库存
    	$goods['stock'] = $goods_info['stock']; //初始
    	
    	
    	
    	$goods['shop_price'] = $goods_info['shop_price'];
    	$goods['shop_price_format'] = formatPrice($goods['shop_price']);
    	$goods['market_price'] = $goods_info['market_price'];
    	$goods['market_price_format'] = formatPrice($goods['market_price']);
    	$goods['promote_price'] = $goods_info['promote_price'];
    	$goods['promote_price_format'] = formatPrice($goods['promote_price']);
    	$goods['weight'] = $goods_info['weight'];
    	$goods['weight_format'] = formatWeight($goods_info['weight'],$goods_id);
    	if($goods_info['member_price'])
    	{
    		$goods['member_price'] = $goods_info['member_price'];
    		$goods['member_price_format'] = formatPrice($goods['member_price']);
    	}
    	
    			$unit_price = $goods_info['shop_price'];
    			$now = gmtTime();
   				if($goods_info['promote_begin_time']<$now && $goods_info['promote_end_time']>$now)
   				{
   					$unit_price = $goods_info['promote_price'];
   				}
   				elseif(intval($_SESSION['user_id'])>0)
   				{
   					$unit_price = $goods_info['member_price'];
   				}

   		$goods['total_price'] = $unit_price*$num;
   		$goods['total_price_format']  = formatPrice($goods['total_price']);
   		$goods['sn'] = $goods_info['sn'];
   		$goods['spec_item_id'] = $spec_item_id;
  		echo json_encode($goods);
    }
    
    
    public function getGiftSpec()
    {
    	$goods_id = intval($_REQUEST['goods_id']);
    	$spec_item_id = intval($_REQUEST['spec_item_id']);
    	$spec_item = D("GoodsSpecItem")->getById($spec_item_id);
    	$spec_list = D("GoodsSpec")->getGoodsSpecList($goods_id);
    	if($spec_list)
    	{
    	$spec_type_select = array();
    	foreach($spec_list as $k=>$v)
    	{
    		foreach($v['spec_list'] as $kk=>$vv)
    		{
    			if($vv['id']==$spec_item['spec1_id']||$vv['id']==$spec_item['spec2_id'])
    			{
    				$spec_list[$k]['spec_list'][$kk]['style'] = 'act';
    				$spec_type_select[$v['spec_type']['id']] = $vv['id'];    				
    			}    			
    		}
    	}

    	$this->assign("spec_type_select",$spec_type_select);
    	$this->assign("spec_list",$spec_list);
    	
    	$this->assign("goods_id",$goods_id);
    	$this->display("Inc:cart:gift_spec_list");    	
    	}
    	else
    	{
    		echo '';
    	}
    }
	public function getGiftSpecItem()
    {
    	$goods_id = intval($_REQUEST['goods_id']);
    	$str = $_REQUEST['str'];
    	$spec_conf = array();
    	if($str!='')
    	{
    		$str_arr = explode(",",$str);
    		foreach($str_arr as $str_item)
    		{
    			$str_item = explode("_",$str_item);
    			$spec_conf[$str_item[0]] = $str_item[1];
    		}
    	}
    	$spec_item_id = intval(D("GoodsSpecItem")->getSpecItemId($spec_conf,$goods_id));
    	$cart_stock = intval(D("Cart")->where("rec_id=".$spec_item_id." and session_id='".Session::id()."'")->sum("number"));
    	if($spec_item_id==0)
    	{
    		$res['status'] = false;
    		$res['info'] = L("NOT_SPEC_ITEM");
    		$res['id'] = 0;
    	}
    	elseif(D("GoodsSpecItem")->where("id=".$spec_item_id)->getField("stock") - $cart_stock == 0)
    	{
    		$res['status'] = false;
    		$res['info'] = L("OUT_OF_STOCK");
    		$res['id'] = 0;
    	}
    	else
    	{
    		$res['status'] = true;
    		$res['id'] = $spec_item_id;
    	}
    	

    	echo json_encode($res);
    }
}
?>