<?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 CartModel extends MultiLangModel  {
	
	//获取购物车普通列表 
	public function getCartGoodsList()
	{
		$session_id = Session::id();
		$condition['session_id'] = $session_id;
		$condition['rec_module'] = 'GoodsSpecItem';
		$list = $this->where($condition)->findAll();
		foreach($list as $k=>$v)
		{
			$list[$k]['rec_data'] = D($v['rec_module'])->getCartItem($v['rec_id']);	

			$list[$k]['data_promote_unit_price'] = $v['data_unit_price'];
    		$list[$k]['data_promote_score'] = $v['data_score'];
    			
  			$list[$k]['data_total_price'] = $v['data_promote_unit_price']*$v['number'];
    		$list[$k]['data_total_score'] = $v['data_promote_score']*$v['number'];
   			$list[$k]['data_unit_price_format'] = formatPrice($v['data_unit_price']);
    		$list[$k]['data_promote_unit_price_format'] = formatPrice($v['data_promote_unit_price']);
			$list[$k]['data_total_price_format'] = formatPrice($v['data_total_price']);
			$list[$k]['data_score_format'] = formatScore($v['data_score']);
			$list[$k]['data_promote_score_format'] = formatScore($v['data_promote_score']);	
			$list[$k]['data_total_score_format'] = formatScore($v['data_total_score']);

			//规格
			$spec_goods_item = D("GoodsSpecItem")->getById($v['rec_id']);
						
			$spec_conf_str = '';
			if($spec_goods_item['spec1_id']!=0)
			$spec_conf_str.=D("GoodsSpec")->where("id=".$spec_goods_item['spec1_id'])->getField("spec_name_".FANWE_LANG_ID).",";
						
			if($spec_goods_item['spec2_id']!=0)
			$spec_conf_str.=D("GoodsSpec")->where("id=".$spec_goods_item['spec2_id'])->getField("spec_name_".FANWE_LANG_ID).",";
						
			$spec_conf_str = substr($spec_conf_str,0,-1);
			$list[$k]['spec'] = $spec_conf_str;

		}		
		
		return $list;
	}
	//获取购物车列表 赠品
	public function getPromoteGoodsList($promote_id=0)
	{
		$session_id = Session::id();
		$condition['session_id'] = $session_id;
		$condition['rec_module'] = 'PromoteGoods';
		if($promote_id>0)
		$condition['promote_id'] = $promote_id;
		$list = $this->where($condition)->findAll();
		foreach($list as $k=>$v)
		{
			$list[$k]['rec_data'] = D($v['rec_module'])->getCartItem($v['rec_id']);					
		}
		return $list;
	}
	//获取购物车列表 积分商品
	public function getScoreGoodsList()
	{
		$session_id = session_id();
		$condition['session_id'] = $session_id;
		$condition['rec_module'] = 'ScoreGoods';
		$list = $this->where($condition)->findAll();
		foreach($list as $k=>$v)
		{
			$spec_goods_item = D("GoodsSpecItem")->getById($v['rec_id']);
						
			$spec_conf_str = '';
			if($spec_goods_item['spec1_id']!=0)
			$spec_conf_str.=D("GoodsSpec")->where("id=".$spec_goods_item['spec1_id'])->getField("spec_name_".FANWE_LANG_ID).",";
						
			if($spec_goods_item['spec2_id']!=0)
			$spec_conf_str.=D("GoodsSpec")->where("id=".$spec_goods_item['spec2_id'])->getField("spec_name_".FANWE_LANG_ID).",";
						
			$spec_conf_str = substr($spec_conf_str,0,-1);
			$list[$k]['spec'] = $spec_conf_str;
			
			$cart_item = D($v['rec_module'])->getCartItem($v['rec_id']);	
			$list[$k]['data_score_format'] = formatScore($cart_item['score']);
			$list[$k]['data_promote_score_format'] = formatScore($cart_item['score']);
			$list[$k]['data_total_score_format'] = formatScore($cart_item['score']*$v['number']);
			$list[$k]['rec_data'] = $cart_item;			
		}
		return $list;
	}
	
	
	public function getCartPromoteList()
	{
		//取出购物车中的列表
		$session_id = Session::id();	    	
		$user_id = intval($_SESSION['user_id']);
		if(D("Cart")->where("session_id='".$session_id."' and is_inquiry = 1")->count()==0)  //当无询价商品时输出促销列表
		{
	    	$cart_list = D("Cart")->where("session_id='".$session_id."'")->findAll();
	    	$now = gmtTime();    	
	    	$result = array();
	    	
	    	//是否可使用促销券
	    	if($user_id==0)
	    	$user_card = 0;
	    	else
	    	$use_card = 1;
	    	//获取使用的优惠券并取得相关促销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']);
	    	
	    	
	    	
	    	//开始处理全局促销
	    	$order_price_total = D("Cart")->where("session_id='".$session_id."'")->sum("data_total_price");
	    	$sql_global = "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 order_price_min<=".$order_price_total.
	    				  " and order_price_max>=".$order_price_total.
	    				  " 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(1,4,5,6,7) ".
	    				  " order by promote.priority desc";
	    	
	    	$global_promote_list = D()->query($sql_global);
	    	foreach($global_promote_list as $k=>$v)
	    	{
	    		switch($v['promote_type_id'])
	    		{
	    			case '1':    //赠送的可选商品
	    				$child_list = array();
	    				$child_list_sql = "select goods.* from ".C("DB_PREFIX")."promote as promote ".
	    								  "left join ".C("DB_PREFIX")."promote_child as promote_child on promote.id = promote_child.promote_id ".
	    								  "left join ".C("DB_PREFIX")."goods as goods on goods.id = promote_child.rec_id ".
	    				                  "where promote_id=".$v['id']." ".
	    								  "and module_name='Goods' ".
	    								  "and goods.status=1 ".
	    								  "order by goods.sort desc";
	    				$child_list = D()->query($child_list_sql);
	    				//开始格式化商品
	    				foreach($child_list as $kk=>$vv)
						{
							if(sunnyiC("URL_ROUTE")==1)
							$child_list[$kk]['url'] = U("goods/".$vv['id']);
							elseif(sunnyiC("URL_ROUTE")==2)
							{
								$arr = explode(" ",$vv['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);
								$child_list[$kk]['url'] = 'g'.C("URL_PATHINFO_DEPR").$url.$vv['id'].C("URL_HTML_SUFFIX"); 
							}
							else
							$child_list[$kk]['url'] = U("Goods/show",array('id'=>$vv['id']));
							$child_list[$kk]['short'] = msubstr($vv['name_'.FANWE_LANG_ID],0,sunnyiC("GOODS_SHORT_NAME"));
							$child_list[$kk]['update_time_format']  = toDate($vv['update_time']);
							$child_list[$kk]['create_time_format']  = toDate($vv['create_time']);
							$child_list[$kk]['promote_begin_time_format']  = toDate($vv['promote_begin_time']);
							$child_list[$kk]['promote_end_time_format']  = toDate($vv['promote_end_time']);			
							$child_list[$kk]['promote_price_format'] = formatPrice($vv['promote_price']);
							$child_list[$kk]['market_price_format'] = formatPrice($vv['market_price']);
							$child_list[$kk]['shop_price_format'] = formatPrice($vv['shop_price']);
							$child_list[$kk]['score_format'] = formatScore($vv['score']);
							$child_list[$kk]['max_score_format'] = formatScore($vv['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=".$vv['id']." and user_group_id=".$user_group['id']." and spec_item_id = 0")->getField("user_price"));
								if($define_price>0)
								{
									$child_list[$kk]['member_price']	=	$define_price;
									$child_list[$kk]['member_price_format']	=	formatPrice($define_price);
								}
								else 
								{
									$child_list[$kk]['member_price']	=	$child_list[$kk]['shop_price']*$user_discount;
									$child_list[$kk]['member_price_format']	=	formatPrice($child_list[$kk]['member_price']);
								}
							}
							
							//开始输出商品积分			
							$child_list[$kk]['score'] = round(D("Message")->where("status=1 and rec_module='Goods' and rec_id=".$child_list[$kk]['id'])->avg("score"),0);
							
							if($vv['small_img']=='')
								$child_list[$kk]['small_img'] = sunnyiC("NO_PIC");
							if($vv['big_img']=='')
								$child_list[$kk]['big_img'] = sunnyiC("NO_PIC");
							if($vv['origin_img']=='')
								$child_list[$kk]['origin_img'] = sunnyiC("NO_PIC");
								
							$child_list[$kk]['review'] = D("Message")->where("status=1 and rec_module='Goods' and rec_id=".$child_list[$kk]['id'])->count();
								
							//开始输出已选的赠品
							$cart_promote_goods_list = D("Cart")->getPromoteGoodsList($v['id']);
							foreach($cart_promote_goods_list as $kkk=>$vvv)
							{
								if($child_list[$kk]['id'] == $vvv['rec_data']['goods_id'])
								{
									$child_list[$kk]['spec_item_id'] = $vvv['rec_id'];
								}							
							}
						
						}
				
	    				//格式化结束
	    				
	    				$global_promote_list[$k]['child_list'] = $child_list;
	    				break;
	    			case '5':    //赠送的优惠券
	    				$child_list_sql = "select promote_goods.* from ".C("DB_PREFIX")."promote as promote ".
	    								  "left join ".C("DB_PREFIX")."promote_child as promote_child on promote.id = promote_child.promote_id ".
	    								  "left join ".C("DB_PREFIX")."promote as promote_goods on promote_goods.id = promote_child.rec_id ".
	    				                  "where promote_id=".$v['id']." ".
	    								  "and module_name='Promote' ";
	
	    				$child_list = D()->query($child_list_sql);  				
	    				$global_promote_list[$k]['child_list'] = $child_list;
	    				break;
	    			case '6': 	//总价打折
	    				$promote_money = $order_price_total * (1-$v['discount_radio']);
	    				$global_promote_list[$k]['promote_money'] = $promote_money;
	    				break;
	    			case '7': 	//总价减免
	    				$promote_money = $v['discount_radio'];
	    				$global_promote_list[$k]['promote_money'] = $promote_money;
	    				break;
	    		}
	    		if($v['use_card']==0)
	    		{
	    				$use_card = 0;    				
	    		}
	    	}
	    	
	    	
			//开始处理单品促销
	    	foreach($cart_list as $k=>$v)
	    	{    		
	    		if($v['rec_module']=='GoodsSpecItem')
	    		{
	    			$goods_id = D("GoodsSpecItem")->where("id=".$v['rec_id'])->getField("goods_id");  //获取当前规格的商品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);    	    						
	    			$global_promote_list =  array_merge($global_promote_list,$promote_list);    			
	    		}   		
	    	}
	    	
	    	//过滤相同主键的促销规则
	    	$result_promote_list = array();
	    	foreach($global_promote_list as $k=>$v)
	    	{
	    		$result_promote_list[$v['promote_id']] = $v;
	    	}
	    	
	    	$result['global_promote_list'] = $result_promote_list;
	    	$result['use_card'] = $use_card;
		} //判断是否有询价商品结束
		
    	return $result;
	}
	
	/**
	 * 初始化购物车，计算非促销的价格与积分
	 */
	public function countCart()
	{	
    	$session_id = Session::id();	    	
    	$cart_list = D("Cart")->where("session_id='".$session_id."'")->findAll();
    	
    	foreach($cart_list as $k=>$v)
    	{
    				$cart_item = D($v['rec_module'])->getCartItem($v['rec_id']);
    				
    				$v['data_unit_price'] = $cart_item['data_unit_price'];     				
    				$v['data_score'] = $cart_item['score'];   
    				$v['data_weight'] = $cart_item['data_weight'];
    				 				
    				if($v['attr']!='')
    				{       					  								
			    		$attr_arr = explode(',',$v['attr']);			    		
					   	$attr_price = 0;   
					   	if($attr_arr&&count($attr_arr)>0)
					   	{	 
					   		$lang_envs = D("LangConf")->findAll();				   		 	
					   		foreach ($attr_arr  as $attr_item)
						   	{
						   		$attr_add_price = 0;
						   		foreach($lang_envs as $lang_item)
						   		{
						   			$attr_add_price = D("GoodsAttr")->where("goods_id=".intval($cart_item['goods_id'])." and attr_value_".$lang_item['id']."='".$attr_item."'")->getField("price");	
						   			if($attr_add_price!=0)
						   			break;
						   		}
					    		$attr_price+=$attr_add_price;
						   	}
						   	
					   	}
					   	$v['data_unit_price']+=floatval($attr_price);   
    				}      			

    				$v['data_prommote_unit_price'] = $v['data_unit_price'];
    				$v['data_promote_score'] = $cart_item['score'];
    				
    				$v['data_total_price'] = $v['data_prommote_unit_price'] * $v['number'];
    				$v['data_total_score'] = $v['data_promote_score'] * $v['number'];
    				
    				$v['data_total_weight'] = $v['data_weight']*$v['number'];
    				if($v['is_inquiry']==1)
   					{
   								$v['data_total_price'] = 0;
   								$v['data_promote_unit_price'] = 0;
   								$v['data_unit_price'] = 0;
   								if($v['rec_module']=='ScoreGoods')
   								$v['is_inquiry'] = 0;
   								else
   								$v['is_inquiry'] = 1;
   					}
   							
   					$v['data_name'] = $cart_item['name'];
   					D("Cart")->save($v);
 		    		
    	}   	
	}
	
	/**
	 * 计算购物车中促销模式，单品促销价与积分计算
	 */
	public function countPromoteCart()
	{
		//取出购物车中的列表
		$session_id = Session::id();	    	
		$user_id = intval($_SESSION['user_id']);
    	$cart_list = D("Cart")->where("session_id='".$session_id."'")->findAll();
    	$now = gmtTime();    	
    	$result = array();
    	
    	//是否可使用促销券
    	if($user_id==0)
    	$user_card = 0;
    	else
    	$use_card = 1;
    	//获取使用的优惠券并取得相关促销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']);
    	//开始处理单品促销
    	foreach($cart_list as $k=>$v)
    	{    		
    		if($v['rec_module']=='GoodsSpecItem')
    		{
    			$goods_id = D("GoodsSpecItem")->where("id=".$v['rec_id'])->getField("goods_id");  //获取当前规格的商品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);
    			
    			
    			$v['data_promote_unit_price'] = $v['data_unit_price'];
    			$v['data_promote_score'] = $v['data_score'];
    			
    			foreach($promote_list as $kk=>$vv)
    			{
    				switch($vv['promote_type_id'])
    				{
    					case '2': //打折
    						$v['data_promote_unit_price'] = $v['data_promote_unit_price'] * $vv['discount_radio'];
    						break;
    					case '3': //积分翻倍
    						$v['data_promote_score'] = $v['data_promote_score'] * $vv['discount_radio'];
    						break;
    				}
	    			if($vv['use_card']==0)
	    			{
	    				$use_card = 0;
	    			}
    			}
    			
    			$v['data_total_price'] = $v['data_promote_unit_price']*$v['number'];
    			$v['data_total_score'] = $v['data_promote_score']*$v['number'];
    			
    			D("Cart")->save($v);
    		}   		
    	}
    	
	}
	
	//切换购物车，清空其余不相关的商品
	public function switchCart($is_inquiry = 0)
	{
		$session_id = Session::id();
		if(D("Cart")->where("session_id='".$session_id."' and rec_module<>'ScoreGoods' and is_inquiry<>".intval($is_inquiry))->count()>0)
		{			
			D("Cart")->where("session_id='".$session_id."' and rec_module<>'ScoreGoods' and is_inquiry<>".intval($is_inquiry))->delete();
			M("CartCard")->where("session_id='".$session_id."'")->delete();
		}
	}
	
	//显示购物车价格与积分小计（不计算运费与支付手续费）
	public function countSubTotal()
	{
		//取出全局促销列表
		$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 ".
	    		   " and cart_card.session_id='".$session_id."'";
	    	$card_promote = D()->query($sql);
	    	$card_promote_id = intval($card_promote[0]['id']);
	    	
	    	$now = gmtTime();
	    	
	    	//开始处理全局促销6.7 全场打折与全场减免
	    	$order_price_total = $order_price_origin_total = D("Cart")->where("session_id='".$session_id."'")->sum("data_total_price");  //订单总价
	    	$order_weight_total = D("Cart")->where("session_id='".$session_id."'")->sum("data_total_weight");  //订单总重
	    	$order_score_use_total = D("Cart")->where("session_id='".$session_id."' and data_total_score<0")->sum("data_total_score");  //订单消费积分
	    	$order_score_add_total = D("Cart")->where("session_id='".$session_id."' and data_total_score>=0")->sum("data_total_score");  //订单增加积分
	    	$order_total_number = D("Cart")->where("session_id='".$session_id."'")->sum("number");   //总数量
	    	$sql_global = "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 order_price_min<=".$order_price_total.
	    				  " and order_price_max>=".$order_price_total.
	    				  " 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(6,7) ".
	    				  " order by promote.priority desc";
	    	$global_promote_list = D()->query($sql_global);
	    	
	    	foreach($global_promote_list as $k=>$v)
	    	{
	    			switch($v['promote_type_id'])
    				{
    					case '6': //打折
    						if($order_price_total>0)
    						$order_price_total = $order_price_total * $v['discount_radio'];
    						break;
    					case '7': //减免
    						if($order_price_total>0)
    						$order_price_total = $order_price_total - $v['discount_radio'];
    						break;
    				}
	    	}
	    	
	    	//全局优惠总价
	   		//购物车中单品促销折扣过的总价 - 购物车中单品促销折扣过的总价再经全场折扣过的总价
	    	$promote_money = $order_price_origin_total - $order_price_total;
	    
	    	return array(
	    		'goods_total_price'=>$order_price_total,
	    		'goods_total_price_format'=> formatPrice($order_price_total),
	    		'total_use_score' => $order_score_use_total,
	    		'total_use_score_format' => formatScore($order_score_use_total),
	    		'total_add_score' => $order_score_add_total,
	    		'total_add_score_format' => formatScore($order_score_add_total),
	    		'total_score' => $order_score_add_total+$order_score_use_total,
	    		'total_score_format' => formatScore($order_score_add_total+$order_score_use_total),
	    		'total_weight' =>	$order_weight_total,
	    		'total_number' =>  $order_total_number,
	    		'promote_money' => $promote_money
	    	);
	}
	
	//计算订单所有总额（包含促销计算，运费与支付手续费）
	public function countCartTotal($payment_id=0,$delivery_id=0,$is_protect=0,$delivery_region=array(),$tax)
	{
		$sub_total = $this->countSubTotal();  //取出商品小计
		
		//开始计算全场促销
		$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 ".
	    		   " and cart_card.session_id='".$session_id."'";
	    	$card_promote = D()->query($sql);
	    	$card_promote_id = intval($card_promote[0]['id']);
	    	
	    	$now = gmtTime();
	    	
	    	//开始处理全局促销4 全场免运费

	    	$sql_global = "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 order_price_min<=".$sub_total['goods_total_price'].
	    				  " and order_price_max>=".$sub_total['goods_total_price'].
	    				  " 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(4,5) ".
	    				  " order by promote.priority desc";
	    	$global_promote_list = D()->query($sql_global);
	    	
		$delivery_free = 0;  //全场免运费
		$delivery_fee = $fee['delivery_fee'];
	    foreach($global_promote_list as $k=>$v)
	    {
	    	switch($v['promote_type_id'])
	    	{
	    		case '4': //全场免运费
	    			$delivery_free = 1;
	    			$delivery_fee = 0;
	    			break;
	    		case '5': //赠送优惠券
	    			$child_list_sql = "select promote_goods.* from ".C("DB_PREFIX")."promote as promote ".
	    								  "left join ".C("DB_PREFIX")."promote_child as promote_child on promote.id = promote_child.promote_id ".
	    								  "left join ".C("DB_PREFIX")."promote as promote_goods on promote_goods.id = promote_child.rec_id ".
	    				                  "where promote_id=".$v['id']." ".
	    								  "and module_name='Promote' ";
	    			
	    			$promote_card = D()->query($child_list_sql);
	    	}
	    }
	    $payment_info = D("Payment")->getById($payment_id);
	    $payment_currency = D("Currency")->getById($payment_info['currency']); //支付方式的货币
	    
		$fee = $this->countFee($sub_total['goods_total_price'],$payment_id,$sub_total['total_weight'],$delivery_id,$is_protect,$delivery_region,$tax,$delivery_fee);
		
		
	    return array(
			'goods_total_price' => $sub_total['goods_total_price'],
			'goods_total_price_format' => $sub_total['goods_total_price_format'],	
			'delivery_fee' =>	$fee['delivery_fee'],
			'delivery_fee_format' => formatPrice($fee['delivery_fee']),
			'protect_fee'	=> $fee['protect_fee'],
			'protect_fee_format' => formatPrice($fee['protect_fee']),
			'payment_fee' =>	$fee['payment_fee'],
			'payment_fee_format' => formatPrice($fee['payment_fee']),
			'total_price' =>	$sub_total['goods_total_price']+$delivery_fee+$fee['payment_fee']+$fee['tax_money']+$fee['protect_fee'],
			'total_price_format' =>	formatPrice($sub_total['goods_total_price']+$delivery_fee+$fee['payment_fee']+$fee['tax_money']+$fee['protect_fee']),
			'payment_name' =>	$payment_info['name_'.FANWE_LANG_ID],
			'payment_total_price_format'	=>	$payment_currency['unit']." ".number_format(round((($sub_total['goods_total_price']+$delivery_fee+$fee['payment_fee']+$fee['tax_money']+$fee['protect_fee'])*$payment_currency['radio']),2),2),
			'promote_card' =>	$promote_card,
			//积分
			'total_use_score' => $sub_total['total_use_score'],
	    	'total_use_score_format' => $sub_total['total_use_score_format'],
	    	'total_add_score' => $sub_total['total_add_score'],
	    	'total_add_score_format' => $sub_total['total_add_score_format'],
	    	'total_score' => $sub_total['total_score'],
	    	'total_score_format' => $sub_total['total_score_format'],
			//税款
			'tax' => $tax,
			'tax_money' =>	$fee['tax_money'],
			'tax_money_format' => formatPrice($fee['tax_money']),
			'delivery_free' => $delivery_free,
			//总重
			'total_weight' => $sub_total['total_weight'],
	    	//全局促销的优惠价
	    	'promote_money' =>	$sub_total['promote_money'],
	    	'promote_money_format' =>	formatPrice($sub_total['promote_money'])
		);
	}
	
	/**
	 * 计算相应的运费与手续费
	 *
	 * @param $total_price  总价
	 * @param $total_weight 总重
	 * @param $delivery_id  配送方式
	 * @param $payment_id   支付方式
	 * @param $is_protect   是否保价
	 * @param $delivery_region   配送地区 array('region_lv1'=>'','region_lv2'=>'','region_lv3'=>'','region_lv4'=>'')
	 * @param $tax 是否开票
	 * 
	 * 返回：支付手续费，运费,保价费, 税款 array('payment_fee'=>'','delivery_fee'=>'','protect_fee'=>'','tax_money'=>'')
	 */
	public function countFee($total_price,$payment_id,$total_weight,$delivery_id,$is_protect,$delivery_region,$tax,$count_delivery_fee)
	{
			
		//计算运费
		$order_delivery_region = 0;
		if($delivery_region['region_lv4']>0)
		{
			$order_delivery_region = $delivery_region['region_lv4'];
		}
		elseif($delivery_region['region_lv3']>0)
		{
			$order_delivery_region = $delivery_region['region_lv3'];
		}
		elseif($delivery_region['region_lv2']>0)
		{
			$order_delivery_region = $delivery_region['region_lv2'];
		}
		elseif($delivery_region['region_lv1']>0)
		{
			$order_delivery_region = $delivery_region['region_lv1'];
		}
		//至此查询出当前订定所配送的地址ID

		$delivery_fee = 0;  //用于返回的运费
		$protect_fee = 0;  //用于返回的保价费
		$delivery_info = D("Delivery")->getById($delivery_id);

		if($delivery_info)
		{
			$delivery_regions = D("DeliveryRegion")->where("delivery_id=".$delivery_id)->findAll();
						
			if($delivery_regions&&$order_delivery_region>0)
			{				
				//存在当前指定的配送地址
				foreach($delivery_regions as $k=>$v)
				{
					$region_ids = explode(",",$v['region_ids']);
					$tmp_arr = array();
					foreach($region_ids as $vv)
					{
						$arr = D("RegionConf")->getChildIds($vv);
						if($arr != 0)
						$tmp_arr = array_merge($tmp_arr,$arr);
					}
					$region_ids = array_merge($tmp_arr,$region_ids);
					
					if(in_array($order_delivery_region,$region_ids))
					{
						//查询出存在的计算地区
						$region_info = $v;	
														
						if($total_weight>$delivery_info['first_weight'])
						{
							//超过首重
							$delivery_fee += $region_info['first_price'];
							//计算续重
							$delivery_fee += ceil(($total_weight-$delivery_info['first_weight'])/$delivery_info['continue_weight'])*$region_info['continue_price'];
						}
						else 
						{
							$delivery_fee += $region_info['first_price'];
								
						}
						break;
					}
				}
				if(!$region_info)
				{
					//未查询出相应的计算地区判断时否按默认
					if($delivery_info['allow_default']==1)
					{
						//使用默认
						if($total_weight>$delivery_info['first_weight'])
						{
							//超过首重
							$delivery_fee += $delivery_info['first_price'];
							//计算续重
							$delivery_fee += ceil(($total_weight-$delivery_info['first_weight'])/$delivery_info['continue_weight'])*$delivery_info['continue_price'];
						}
						else 
						{
							$delivery_fee += $delivery_info['first_price'];
						}
					}
				}
				
			}
			else 
			{
				//无指定地区时按当前配送方式的默认值计算
				if($delivery_info['allow_default']==1)
					{
						//使用默认
						if($total_weight>$delivery_info['first_weight'])
						{
							//超过首重
							$delivery_fee += $delivery_info['first_price'];
							//计算续重
							$delivery_fee += ceil(($total_weight-$delivery_info['first_weight'])/$delivery_info['continue_weight'])*$delivery_info['continue_price'];
						}
						else 
						{
							$delivery_fee += $delivery_info['first_price'];
						}
					}
			}
			
			if($is_protect==1)
			{
				if($total_price*$delivery_info['protect_radio']/100>$delivery_info['protect_price'])
				{					
					//超过保价底价
					$protect_fee = $total_price*$delivery_info['protect_radio']/100;					
				}
				else 
				{					
					$protect_fee = $delivery_info['protect_price'];
				}
			}
		}
		
		//税率
		$tax_money = 0;
		if($tax==1)
		{
			$tax_money = $total_price*sunnyiC("TAX_RADIO");
		}
		
		
		//计算手续费
		$payment_info = D("Payment")->getById($payment_id);  //支付方式
		$payment_currency = D("Currency")->getById($payment_info['currency']); //支付方式的货币
		if($payment_info['fee_type']==0)
		{
			//定额
			$payment_fee = $payment_info['fee'];
		}
		else
		{
			$payment_fee = ($total_price+$protect_fee+$tax_money+$count_delivery_fee) * $payment_info['fee']/100;
		}
		
		return array('payment_fee'=>$payment_fee,'delivery_fee'=>$delivery_fee,'protect_fee'=>$protect_fee,'tax_money'=>$tax_money);
	}
}
?>