<?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 CartAction extends SunnyiAction{
   public function __construct()
   {  
		parent::__construct();
		if(sunnyiC("USER_CART"))
		{
			if(intval($_SESSION['user_id'])==0)
			{
				$this->error(L("PLEASE_LOGIN"),intval($_REQUEST['is_ajax']));
			}
		}		
   }
   
   //单品加入购物车 (规格购买，包括积分商品与普通商品)
   public function addGoodsToCart()
   {
   		$rec_id = intval($_REQUEST['rec_id']);  //购买的ID
   		$rec_module = trim($_REQUEST['rec_module']);  //购买的模块
   		$goods_id = intval($_REQUEST['goods_id']);  //商品ID

   		//验证是否需要登录
   		if($rec_module=='ScoreGoods'&&intval($_SESSION['user_id'])==0)
   		{
   			$return_res['status'] = 0;
   			$return_res['info'] = L("PLEASE_LOGIN");
   			echo json_encode($return_res);
   			exit;
   		}
   		
   		$number = intval($_REQUEST['number']);  //购买数量
   		
   		
   		//用于返回的数据
   		$return_res['status'] = 0;
   		$return_res['info'] = L("ADD_CART_FAILED");
   		$return_res['data'] = "";
      	if($number<=0) 
   		{	
   			$return_res['info'] = L("INVALID_NUMBER");
   			echo json_encode($return_res); exit;
   		}
   		  		
   		$session_id = Session::id();  //当前浏览的session_id   		   		
   	 	$goods_info = D("GoodsSpecItem")->getGoodsSpecItem($rec_id);
   	 	
		if(!$goods_info)
		{ 
			$return_res['info'] = L("NOT_SPEC_ITEM");
			$return_res['status'] = 0;
			echo json_encode($return_res);exit;
		}
  				
					
				
   				//开始获取单价
   				$now = gmtTime();
   				$unit_price = $goods_info['shop_price'];
   				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'];
   				}
   				
   				$unit_price+=$attr_price;
   				
   				//取出会员当前可用积分
   				$user_score = intval(D("User")->where("id=".intval($_SESSION['user_id']))->getField("score"));
   				
   				//取出同当前购买相同的数据
   				$cart_item = D("Cart")->where("session_id='".$session_id."' and rec_module='".$rec_module."' and rec_id=".$rec_id)->find();
   				if($cart_item)
   				{   		
	   				//验证积分是否足够
			   		if($rec_module == 'ScoreGoods')
			   		{
			   			if(abs($number*$cart_item['data_promote_score'])+abs(D("Cart")->where("session_id='".$session_id."' and rec_module='".$rec_module."'")->sum("data_total_score"))>$user_score)
			   			{
			   				$return_res['status'] = 0;
	   						$return_res['info'] = L("NOT_ENOUGH_SCORE");
	   						echo json_encode($return_res);
	   						exit;
			   			}
			   		}
   					
   					$cart_item['number'] = $cart_item['number'] + $number;
   					$cart_item['update_time'] = $now;
   					
   					//开始判断库存
   					if(sunnyiC("USE_STOCK"))
   					{
   						$number_exist = D("Cart")->where("session_id='".$session_id."' and rec_id=".$rec_id)->sum("number");   						

   						if($number_exist+$number>$goods_info['stock'])
   						{
   							$return_res['info'] = L("OUT_OF_STOCK");
   						}
   						else 
   						{
   							if(($goods_info['is_inquiry']==1||sunnyiC("IS_INQUIRY")==1)&&$rec_module != 'ScoreGoods')
   							{
   								$cart_item['data_unit_price'] = 0;
   								$cart_item['is_inquiry'] = 1;
   							}
	   						$rs = D("Cart")->save($cart_item);
		   					if($rs)
		   					{
		   						$return_res['status'] = 1;
		   						$return_res['info'] = 0;
		   					}
   						}
   					}
   					else 
   					{
   						if(($goods_info['is_inquiry']==1||sunnyiC("IS_INQUIRY")==1)&&$rec_module != 'ScoreGoods')
						{
   								$cart_item['data_unit_price'] = 0;
   								$cart_item['is_inquiry'] = 1;
   						}	   					
	   					$rs = D("Cart")->save($cart_item);
	   					if($rs)
	   					{
	   						$return_res['status'] = 1;
	   						$return_res['info'] = 0;
	   					}
   					}
   					D("Cart")->switchCart($cart_item['is_inquiry']);
   				}
   				else 
   				{
   					
   					$tmp_cart_item = D($rec_module)->getCartItem($rec_id);
   					
   					//验证积分是否足够
			   		if($rec_module == 'ScoreGoods')
			   		{
			   			if(abs($number*$tmp_cart_item['score'])+abs(D("Cart")->where("session_id='".$session_id."' and rec_module='".$rec_module."'")->sum("data_total_score"))>$user_score)
			   			{
			   				$return_res['status'] = 0;
	   						$return_res['info'] = L("NOT_ENOUGH_SCORE");
	   						echo json_encode($return_res);
	   						exit;
			   			}
			   		}
			   		
   					//新增
   					$cart_item['pid'] = 0;
   					$cart_item['rec_id'] = $rec_id;
   					$cart_item['rec_module'] = $rec_module;
   					$cart_item['session_id'] = $session_id;
   					$cart_item['user_id'] = intval($_SESSION['user_id']);
   					$cart_item['number'] = $number;
   					$cart_item['data_unit_price'] = floatval($tmp_cart_item['data_unit_price']);
   					$cart_item['data_score'] = $tmp_cart_item['score'];
   					$cart_item['total_price'] = floatval($tmp_cart_item['data_unit_price']) * $cart_item['number'];
   					$cart_item['create_time'] = $now;
   					$cart_item['update_time'] = $now;
   					$cart_item['data_name'] = $tmp_cart_item['name'];
   					$cart_item['data_sn'] = $tmp_cart_item['sn'];

   					//开始判断库存
   					if(sunnyiC("USE_STOCK"))
   					{
   						$number_exist = intval(D("Cart")->where("session_id='".$session_id."' and rec_id=".$rec_id)->sum("number"));   						
   						if($number_exist+$number>$goods_info['stock'])
   						{
   							$return_res['info'] = L("OUT_OF_STOCK");
   						}
   						else 
   						{
   							if(($goods_info['is_inquiry']==1||sunnyiC("IS_INQUIRY")==1)&&$rec_module != 'ScoreGoods')
   							{
   								$cart_item['data_unit_price'] = 0;
   								$cart_item['is_inquiry'] = 1;
   							}
	   						$rs = D("Cart")->add($cart_item);
	   						
		   					if($rs)
		   					{
		   						$return_res['status'] = 1;
		   						$return_res['info'] = 0;
		   					}
   						}
   					}
   					else 
   					{
   						if(($goods_info['is_inquiry']==1||sunnyiC("IS_INQUIRY")==1)&&$rec_module != 'ScoreGoods')
   							{
   								$cart_item['data_unit_price'] = 0;
   								$cart_item['is_inquiry'] = 1;
   							}
	   					$rs = D("Cart")->add($cart_item);
	   					if($rs)
	   					{
	   						$return_res['status'] = 1;
	   						$return_res['info'] = 0;
	   					}
   					}
   					D("Cart")->switchCart($cart_item['is_inquiry']);
   				} 
   		echo json_encode($return_res);
   }
   
   public function listCart()
   {
   		$this->checkCart();
   	 	$navs = array('name'=>L("CART_LIST"),'url'=>U("Cart/listCart"));
        //输出当前页seo内容
    	$data = array(
    		'navs' => array(
    			$navs,
    		),
    		'keyword'=>	'',
    		'content'=>	'',
    	);
    	$this->assignSeo($data);   
		
    	//输出促销
    	$result = D("Cart")->getCartPromoteList();
    	
    	$this->assign("cart_promote_list",$result['global_promote_list']);    	
    	$this->assign("use_card",$result['use_card']);
    	//输出商品
    	$this->assign("cart_list",D("Cart")->getCartGoodsList());    
    	//输出赠品
    	$this->assign("cart_promote_goods_list",D("Cart")->getPromoteGoodsList());
    	//输出积分商品
    	$this->assign("cart_score_goods_list",D("Cart")->getScoreGoodsList());
    	//输出小计
    	$this->assign("sub_total",D("Cart")->countSubTotal());
    	$this->assign("content_page","Inc:cart:list_cart");
   		$this->display("Page:cart_frame");
   }
   
   //修改购物车  暂实现商品类型的修改
   public function modifyCart()
   {
   		$this->checkCart();
   		$session_id = session_id();
   		
   		$result['status'] = 0;
   		$result['info'] = L("MODIFY_ERROR");
   		$result['data'] = NULL;
   		
   		$cart_id = intval($_REQUEST['cart_id']);
   		$number  = intval($_REQUEST['number']);
   		$cart_info = D("Cart")->getById($cart_id);
   		
   		if($number<=0) 
   		{	
   			$result['info'] = L("INVALID_NUMBER");
   			echo json_encode($result);
   			exit;
   		}
   		
		$cart_item = D($cart_info['rec_module'])->getCartItem($cart_info['rec_id']);

		$user_score = D("User")->where("id=".intval($_SESSION['user_id']))->getField("score");
		$session_id = Session::id();

		
   		//验证积分是否足够
		if($cart_info['rec_module'] == 'ScoreGoods')
		{
			
			  if(abs($number*$cart_info['data_promote_score'])+abs(D("Cart")->where("session_id='".$session_id."' and rec_module='".$cart_info['rec_module']."' and id<>".$cart_info['id'])->sum("data_total_score"))>$user_score)
			  {
			   		$result['status'] = 0;
	   				$result['info'] = L("NOT_ENOUGH_SCORE");
	   				echo json_encode($result);
	   				exit;
			   }
		}
			   		
  		if($cart_info['attr']!='')
  		{
  			//开始处理属性库存
		   		$attr_arr = explode(',',$cart_info['attr']);
		   		$attr_in_stock = true;  //属性组合初始为真
		   		if($attr_arr&&count($attr_arr)>0)
		   		{	   		 	
		   			foreach ($attr_arr  as $attr_item)
			    	{
			    		if($attr_item!='')
			    		{
				    		$curr_attr_stock = D("GoodsAttr")->where("goods_id=".$cart_item['goods_id']." and attr_value_".FANWE_LANG_ID."='".$attr_item."'")->getField("stock");
				    		$curr_attr_id = D("GoodsAttr")->where("goods_id=".$cart_item['goods_id']." and attr_value_".FANWE_LANG_ID."='".$attr_item."'")->getField("attr_id");
				    		$attr_type = D("GoodsTypeAttr")->where("id=".intval($curr_attr_id))->getField("attr_type");
				    		if($curr_attr_stock==0&&$attr_type>0)
				    		{
				    			$attr_in_stock = false;
				    			break;
				    		}
			    		}
			    	}
		   		}
  		}
				
   				
		   		
   				if(sunnyiC("USE_STOCK"))
   				{
   					//开始库存判断
   					$exist_number = intval(D("Cart")->where("session_id='".$session_id."' and rec_id=".$cart_info['rec_id']." and id <>".$cart_id)->sum("number"));  //除当前订购商品的其他商品数量和

   					if(sunnyiC("ATTR_STOCK")==1&&$attr_in_stock!=null&&$attr_in_stock==false)
   					{
   						$result['info'] = L("OUT_OF_STOCK");   						
   						echo json_encode($result); exit;
   					}
   					elseif($exist_number+$number > $cart_item['stock'])
   					{
   						$result['info'] = L("OUT_OF_STOCK");
   						echo json_encode($result); exit;
   					}   					
   				}
  				$rs = D("Cart")->where("id=".$cart_id)->setField('number',$number);
   				$result['status'] = 1;
   				$result['info'] = "";   			
   				
   			
   				
   			
   		
   		echo json_encode($result);
   		
   }
   
   public function delCart()
   {
   		$session_id = session_id();
   	   	$result['status'] = 0;
   		$result['info'] = L("DELETE_ERROR");
   		$result['data'] = NULL;
   		
   		$cart_id = intval($_REQUEST['cart_id']);
   		if($cart_id>0)
   		{
   			$rs = D("Cart")->where("id=".$cart_id)->delete();
   			$result['status'] = 1;
   			$result['info'] = '';   			
   		}
   		else
   		{
   			$rs = D("Cart")->where("session_id='".$session_id."'")->delete();
   			$result['status'] = 1;
   			$result['info'] = '';
   			
   		}
   		$result['count'] = D("Cart")->where("session_id='".$session_id."'")->count();
   		echo json_encode($result);
   }
   
   //配送地址
   public function consignee()
   {
   		$this->checkCart();
   		if(intval($_SESSION['user_id'])>0)  //已登录
   		{
	   		//初始化分页
	    	$page = intval($_REQUEST[C("VAR_PAGE")]);
	    	if($page==0)
	    	$page = 1;
	    	$result = D("UserConsignee")->getConsigneeList(intval($_SESSION['user_id']),$page); 
	    	if($result['total']==0)
	    	{
	    		$this->checkOut();
	    		exit;
	    	}   	
	    	$this->assign("consignee_list",$result['list']);
	    	//分页
			$page = new Page($result['total'],sunnyiC("ARTICLE_PAGE_LISTROWS"));   //初始化分页对象 		
			$p  =  $page->show();
	        $this->assign('pages',$p);
	        //end 分页  
	        
			$navs = array('name'=>L("SELECT_CONSIGNEE"),'url'=>U("Cart/consignee"));
	        //输出当前页seo内容
	    	$data = array(
	    		'navs' => array(
	    			$navs,
	    		),
	    		'keyword'=>	'',
	    		'content'=>	'',
	    	);
	    	$this->assignSeo($data);   
	    	$this->assign("content_page","Inc:cart:consignee");
			$this->display("Page:cart_frame");
   		}
   		else
   		{
   			$this->checkOut();
   		} 
   }
   
   //订单结算
   public function checkOut()
   {
   		$this->checkCart();
   		$navs = array('name'=>L("CHECK_OUT"),'url'=>U("Cart/checkOut"));
        //输出当前页seo内容
    	$data = array(
    		'navs' => array(
    			$navs,
    		),
    		'keyword'=>	'',
    		'content'=>	'',
    	);
    	$this->assignSeo($data);   

    	//输出商品
    	$this->assign("cart_list",D("Cart")->getCartGoodsList());    
    	//输出赠品
    	$this->assign("cart_promote_goods_list",D("Cart")->getPromoteGoodsList());
    	//输出积分商品
    	$this->assign("cart_score_goods_list",D("Cart")->getScoreGoodsList());
    	//输出总小计
    	$this->assign("sub_total",D("Cart")->countSubTotal());
	
		
    	$consignee_id = intval($_REQUEST['consignee_id']);
    	$consignee_info = D("UserConsignee")->getConsigneeItem($consignee_id);
    	
    	$user_info = D("User")->where("id=".intval($_SESSION['user_id']))->find();
    	
    	//输出当前可用的会员积分与可用的积分
    	$max_score = 0;
    	foreach ($cart_goods_list as $g_item)
    	{
    		if($g_item['is_inquiry']==0)
    			$max_score += ($g_item['rec_data']['max_score']*$g_item['number']);
    	}
    	$this->assign("max_score",formatScore($max_score));
    	$this->assign("current_score",formatScore($user_info['score']));
    	$this->assign("score_money",formatPrice(countScore($max_score)));
    	
    	if($consignee_info)
    	{    		
    		$consignee_info['qq'] = $user_info['qq'];
    		$consignee_info['msn'] = $user_info['msn'];
    		$consignee_info['alim'] = $user_info['alim'];
    		$consignee_info['email'] = $user_info['email'];
    		$this->assign("consignee_info",$consignee_info);
    		
    		//输出一级地区
			$region_lv1_list = D("RegionConf")->where("pid=0")->order('name asc')->findAll();
			$this->assign("region_lv1_list",$region_lv1_list);
			
			//输出二级地区
			$region_lv2_list = D("RegionConf")->where("pid=".$consignee_info['region_lv1'])->order('name asc')->findAll();
			$this->assign("region_lv2_list",$region_lv2_list);
			
			//输出三级地区
			$region_lv3_list = D("RegionConf")->where("pid=".$consignee_info['region_lv2'])->order('name asc')->findAll();
			$this->assign("region_lv3_list",$region_lv3_list);
			
			//输出四级地区
			$region_lv4_list = D("RegionConf")->where("pid=".$consignee_info['region_lv3'])->order('name asc')->findAll();
			$this->assign("region_lv4_list",$region_lv4_list);
    	}
    	else 
    	{    		
    		$user_info['consignee'] = $user_info['nickname'];
    		$this->assign("consignee_info",$user_info);
    		    	
	    	//输出一级地区
			$region_lv1_list = D("RegionConf")->where("pid=0")->order('name asc')->findAll();
			$this->assign("region_lv1_list",$region_lv1_list);
    	}
    	
    	//输出支付方式
    	$payment_list = D("Payment")->where("status=1")->findAll();    		
    	foreach($payment_list as $kk=>$vv)
    	{
    		$currency_item = M("Currency")->getById($vv['currency']);
    		$payment_list[$kk]['currency_type'] = $currency_item['name_'.FANWE_LANG_ID];
    		if($vv['fee_type']==0)
    		$payment_list[$kk]['fee_format'] = $currency_item['unit']." ".getBaseMoney($vv['fee'],$vv['currency']);
    		else 
    		$payment_list[$kk]['fee_format'] = floatval($vv['fee'])."%";
    	}  	
    	$this->assign("payment_list",$payment_list);
    	
    	//输出配送列表
    	if($consignee_info)
    	{
    		if($consignee_info['region_lv4']>0)
    		{
    			$end_region_id = $consignee_info['region_lv4'];
    		}
    		elseif($consignee_info['region_lv3']>0)
    		{
    			$end_region_id = $consignee_info['region_lv3'];
    		}
    		elseif($consignee_info['region_lv2']>0)
    		{
    			$end_region_id = $consignee_info['region_lv2'];
    		}
    		elseif($consignee_info['region_lv1']>0)
    		{
    			$end_region_id = $consignee_info['region_lv1'];
    		}
    	}
    	else
    	{
    		$end_region_id = 0;
    	}
   		$delivery_ids = D("Delivery")->loadDelivery($end_region_id);
    	$delivery_list = D("Delivery")->where("status=1")->findAll();
    	foreach($delivery_list as $k=>$v)
    	{
    		if(!in_array($v['id'],$delivery_ids))
    		{
    			unset($delivery_list[$k]);
    		}
    		else
    		$delivery_list[$k]['protect_radio'] = $v['protect_radio']."%";
    	}
    	$this->assign('delivery_list',$delivery_list);
    	
    	$this->assign("content_page","Inc:cart:check_out");
   		$this->display("Page:cart_frame");
   }
   
	//完成订单
   public function done()
   { 
   		if(sunnyiC("TOKEN_ON")&&!M()->autoCheckToken($_POST))
		{
			$this->error(L("TOKEN_ERROR"));
		}  
   			$session_id = Session::id();
   			$user_id = intval($_SESSION['user_id']);
			$this->checkCart();

	   		$now = gmtTime();
	   		
	   		//开始获取提交的数据
	   		$payment_id = intval($_POST['payment']);
	   		$delivery_id = intval($_POST['delivery']);
	   		//提交的地区
	   		$region_lv1 = intval($_POST['region_lv1']);
	   		$region_lv2 = intval($_POST['region_lv2']);
	   		$region_lv3 = intval($_POST['region_lv3']);
	   		$region_lv4 = intval($_POST['region_lv4']);
	   		//保价
	   		$is_protect = intval($_POST['protect']);
	   		//是否开票
	   		$tax = intval($_POST['tax']);
	   		
	   		//统计购物车
	   		$cart_total = D("Cart")->countCartTotal($payment_id,$delivery_id,$is_protect,array('region_lv1'=>$region_lv1,'region_lv2'=>$region_lv2,'region_lv3'=>$region_lv3,'region_lv4'=>$region_lv4),$tax);
	   		$promote_list = D("Cart")->getCartPromoteList();

	   		//开始生成计单	   		
	   		$order['sn'] = date('ymdhis', gmtTime()).rand_string(2,0);
	   		$order['money_status'] = 0;
	   		$order['goods_status'] = 0;
	   		$order['status'] = 0;
	   		$order['create_time'] = $now;
	   		$order['update_time'] = $now;
	   		
	   		$order['zip'] = $_POST['zip']?$_POST['zip']:'';
	   		
	   		//配送地区
	   		$order['region_lv1'] = $region_lv1;
	   		$order['region_lv2'] = $region_lv2;
	   		$order['region_lv3'] = $region_lv3;
	   		$order['region_lv4'] = $region_lv4;
	   		
	   		$order['address'] = $_POST['address']?$_POST['address']:'';
	   		$order['email'] = $_POST['email']?$_POST['email']:'';
	   		$order['fix_phone'] = $_POST['fix_phone']?$_POST['fix_phone']:'';
	   		$order['fax_phone'] = $_POST['fax_phone']?$_POST['fax_phone']:'';
	   		$order['mobile_phone'] = $_POST['mobile_phone']?$_POST['mobile_phone']:'';	   		
	   		$order['qq'] = $_POST['qq']?$_POST['qq']:'';
	   		$order['msn'] = $_POST['msn']?$_POST['msn']:'';
	   		$order['alim'] = $_POST['alim']?$_POST['alim']:'';
	   		
	   		$order['consignee'] = $_POST['consignee']?$_POST['consignee']:'';
	   		$order['user_id'] = intval($_SESSION['user_id']);		   		
	   		$order['memo'] = $_POST['memo']?$_POST['memo']:'';
	   		
	   		$order['payment'] = $payment_id;	
	   		$order['total_price'] = $cart_total['goods_total_price'] + $cart_total['promote_money'];
	   		$order['delivery'] = $delivery_id;
	   		$order['protect'] = $is_protect;
	   		$order['order_score'] = $cart_total['total_score'];  //计算订单最终产生的积分
	   		$card_code = D("CartCard")->where("session_id='".$session_id."' and user_id=".$user_id)->getField("card_code");
	   		$order['card_code'] = $card_code?$card_code:'';
	   		$order['delivery_fee'] = $cart_total['delivery_free']==1?0:$cart_total['delivery_fee'];
	   		$order['protect_fee'] = $cart_total['protect_fee'];
	   		$order['payment_fee'] = $cart_total['payment_fee'];
	   		
	   		$order['tax'] = $tax;
	   		$order['tax_content'] = $_POST['tax_content']?$_POST['tax_content']:'';
	   		$order['tax_money'] = $cart_total['tax_money'];
	   		
	   		$order['order_weight'] = $cart_total['total_weight'];
	   		$order['currency_id'] = intval(D("Payment")->where("id=".$payment_id)->getField("currency"));
	   		$order['currency_radio'] = D("Currency")->where("id=".$order['currency_id'])->getField("radio");
	   		
	   		$order['promote_money'] = $cart_total['promote_money'];
	   		$order['order_total_price'] = $cart_total['total_price'];
	   		
	   		$order['lang_conf_id'] = FANWE_LANG_ID;
	   		
	   		
	   		
	   		//开始验证
   			if(D("Payment")->where("status=1")->count()>0&&$order['payment']==0)
	   		{
	   			$this->error(L("SELECT_PAYMENT"));
	   		}
   			if(D("Delivery")->where("status=1")->count()>0&&$order['delivery']==0)
	   		{
	   			$this->error(L("SELECT_DELIVERY"));
	   		}
	   		if($order['consignee']=="")
	   		{
	   			$this->error(L("CONSIGNEE_EMPTY"));
	   		}
   			if($order['email']=="")
	   		{
	   			$this->error(L("EMAIL_EMPTY"));
	   		}
   			if(!preg_match("/\w+@\w+\.\w{2,3}\b/",$order['email']))
	   		{
	   			$this->error(L("EMAIL_FORMAT_ERROR"));
	   		}
   			if($order['fix_phone']=="")
	   		{
	   			$this->error(L("FIXPHONE_EMPTY"));
	   		}
   			if($order['zip']=="")
	   		{
	   			$this->error(L("ZIP_EMPTY"));
	   		}
   			if($order['address']=="")
	   		{
	   			$this->error(L("ADDRESS_EMPTY"));
	   		}
	   		//开始验证是否支持保价
	   		if($is_protect==1 && D("Delivery")->where("id=".$delivery_id)->getField("protect")==0)
	   		{
	   			$this->error(L("PROTECT_NOT_SUPPORT"));
	   		}	
   			//开始验证余额
	   		if(D("Payment")->where("id=".$payment_id)->getField("class_name")=='Accountpay')
	   		{
	   			if(floatval(D("User")->where("id=".intval($_SESSION['user_id']))->getField("money"))<$order['total_price'])
	   			{
	   				$this->error(L("MONEY_NOT_ENOUGH"));
	   				exit;
	   			}
	   		}
	   		
	   		$order_id = D("Order")->add($order); 

	   		//更新优惠券使用次数
	   		$card_sn = D("Order")->where("id=".$order_id)->getField("card_code");
	   		if($card_sn)
	   		{
	   			M("PromoteCard")->where("card_code='".$card_sn."'")->setInc("card_used");
	   		}
	   		
	   		if($order_id) //提交成功后提交订单商品
	   		{
	   			$cart_list = D("Cart")->where("session_id='".$session_id."' and user_id=".$user_id)->findAll();
	   			foreach($cart_list as $k=>$v)
	   			{
	   				$order_goods['id'] = 0;
	   				$order_goods['pid'] = 0;
	   				$order_goods['order_id'] = $order_id;
	   				$order_goods['rec_module'] = $v['rec_module'];
	   				$order_goods['rec_id'] = $v['rec_id'];
	   				$order_goods['data_name'] = $v['data_name'];
	   				$order_goods['data_sn'] = $v['data_sn'];
	   				$order_goods['data_score'] = $v['data_promote_score'];
	   				$order_goods['data_total_score'] = $v['data_total_score'];
	   				$order_goods['data_price'] = $v['data_promote_unit_price'];
	   				$order_goods['data_total_price'] = $v['data_total_price'];
	   				$order_goods['data_score'] = $v['data_promote_score'];
	   				$order_goods['data_total_score'] = $v['data_total_score'];
	   				
	   				$order_goods['attr'] = $v['attr'];
	   				$order_goods['number'] = $v['number'];
	   				$order_goods['is_inquiry'] = $v['is_inquiry'];
	   				$order_goods['create_time'] = $now;
	   				$order_goods['status'] = 0;
	   				$order_goods['data_weight'] = $v['data_weight'];
	   					   				
	   				D("OrderGoods")->add($order_goods);
	   			}
	   		}
	   		//开始写入订单促销表
	   		
	   		foreach($promote_list['global_promote_list'] as $row=>$item)
	   		{
	   			if($item['promote_type_id'] == 5) //赠送购物券
	   			{
	   				foreach($item['child_list'] as $card_item)
	   				{
	   					if(M("OrderPromote")->where("order_id=".$order_id." and card_id=".$card_item['id'])->count()>0)//当已有同张购物优惠券时更新数量
	   					{
	   						$o_num = M("OrderPromote")->where("order_id=".$order_id." and card_id=".$card_item['id'])->getField("promote_data_number");
	   						M("OrderPromote")->where("order_id=".$order_id." and card_id=".$card_item['id'])->setField("promote_data_number",$o_num+1);
	   	
	   					}
	   					else //新增购物券与相关的促销规则
	   					{
	   						$order_promote_item = array();
				   			$order_promote_item['order_id'] = $order_id;
				   			$order_promote_item['promote_id'] = $item['promote_id'];
				   			$order_promote_item['memo'] = $item['memo_'.FANWE_LANG_ID];
				   			$order_promote_item['promote_money'] = floatval($item['promote_money']);
				   			$order_promote_item['card_id'] = $card_item['id'];
				   			$order_promote_item['promote_data_name']	=  $card_item['card_name'.FANWE_LANG_ID];
				   			$order_promote_item['promote_data_number'] = 1;
				   			$order_promote_item['priority'] = $item['priority'];
				   			M("OrderPromote")->add($order_promote_item);
	   					} 
	   				}
	   			}
	   			else
	   			{
		   			$order_promote_item = array();
		   			$order_promote_item['order_id'] = $order_id;
		   			$order_promote_item['promote_id'] = $item['promote_id'];
		   			$order_promote_item['memo'] = $item['memo_'.FANWE_LANG_ID];
		   			if($item['promote_type_id'] == 4)
		   			{
		   				//免运费
		   				$order_promote_item['promote_money'] = $cart_total['delivery_fee'];
		   			}
		   			else
		   			{
		   				$order_promote_item['promote_money'] = floatval($item['promote_money']);
		   			}
		   			$order_promote_item['priority'] = $item['priority'];
		   			if($item['promote_type_id'] == 1)  //赠送赠品
		   			{
		   				$promote_data_name = "";
		   				$promote_goods_list = D("Cart")->where("session_id='".$session_id."' and user_id=".$user_id." and rec_module='PromoteGoods'")->findAll();
		   				foreach($promote_goods_list as $goods_item)
		   				{
		   					$promote_data_name .= $goods_item['data_name']."(".$goods_item['number']."),";
		   				}
		   				if($promote_data_name!="")$promote_data_name = substr($promote_data_name,0,-1);
		   				$order_promote_item['promote_data_name'] = $promote_data_name;
		   			}
					M("OrderPromote")->add($order_promote_item);
			
	   			}	   			
	   		}

	   		$navs = array('name'=>L("ORDER_SUCCESS"),'url'=>U("Cart/done"));
	        //输出当前页seo内容
	    	$data = array(
	    		'navs' => array(
	    			$navs,
	    		),
	    		'keyword'=>	'',
	    		'content'=>	'',
	    	);
	   		$this->assignSeo($data);   
	   		//生成支付按钮
	   		
	   		$payment_str = D("Payment")->getPayment($order_id);
	   		$this->assign("payment_str",$payment_str);	   		
	   		
	   		D("Cart")->where("session_id='".$session_id."'")->delete();
			
			$this->assign("order_info",L("ORDER_SUBMIT_SUCCESS")." [&nbsp;&nbsp;".L("ORDER_SN")."：<span style='color:#f30; font-weight:bold;'>".$order['sn']."</span>&nbsp;&nbsp;]");
			
	   		$this->display("Page:cart_done");
   		
   }
   
   private function checkCart()
   {
		$session_id=Session::id();
   		if(D("Cart")->where("session_id='".$session_id."'")->count()==0)
   		{   			
   			$this->assign("jumpUrl",U("Index/index"));
   			$this->error(L("CART_LIST_EMPTY"));
   			exit;
   		}
   }
   
   //根据地区ID取出可用的配送方式
	public function loadDelivery()
	{
		$region_id = intval($_REQUEST['id']);
		//输出配送列表
    	
   		$delivery_ids = D("Delivery")->loadDelivery($region_id);
    	$delivery_list = D("Delivery")->where("status=1")->findAll();
    	foreach($delivery_list as $k=>$v)
    	{
    		if(!in_array($v['id'],$delivery_ids))
    		{
    			unset($delivery_list[$k]);
    		}
    		else
    		$delivery_list[$k]['protect_radio'] = $v['protect_radio']."%";
    	}
    	$this->assign('delivery_list',$delivery_list);
    	$this->display("Inc:cart:cart_delivery");
	}

 	//根据地区ID与配送方式ID读取是否支付COD
   public function checkCod()
   {
   		$region_id = intval($_REQUEST['region_id']);
   		$delivery_id = intval($_REQUEST['delivery_id']);
   		$ids = '';
   		$delivery_info = D("Delivery")->where("status=1 and id=".$delivery_id)->find();
   		$allow_cod = 0;

   		if($delivery_info)
   		{
   			
   			if($delivery_info['allow_default'] == 1&&D("DeliveryRegion")->where("delivery_id=".$delivery_info['id'])->count()==0)
   			{
   				//允许默认
   				$allow_cod = $delivery_info['allow_cod'];
   			}
   			else 
   			{
   				$delivery_region = D("DeliveryRegion")->where("delivery_id=".$delivery_info['id'])->findAll();
   				$tag = true;
   				foreach($delivery_region as $vv)
   				{
   					$region_ids = explode(",",$vv['region_ids']);
   					$tmp_ids = array();
   					foreach($region_ids as $vvv)
   					{
   						$tmp_ids = array_merge($tmp_ids,D("RegionConf")->getChildIds($vvv));
   					}
   					$region_ids = array_merge($region_ids,$tmp_ids);
   					if(in_array($region_id,$region_ids))
   					{
   						$allow_cod = $vv['allow_cod'];
   						$tag = false;
   						break;
   					}
   				} 
   				if($tag)
   				{
   					if($v['allow_default'] == 1)
   					{
   						//允许默认
   						$allow_cod = $delivery_info['allow_cod'];
   					}
   				}  				
   			}   			

   		}
   		echo $allow_cod;
   }
   
   /**
    * 添加赠品
    */
   public function addGift()
   {
   		$spec_item_ids =  urldecode($_REQUEST['spec_item_ids']);
   		$promote_id = intval($_REQUEST['promote_id']);
   		$spec_item_array = array();
   		if($spec_item_ids!='')
   		{
   			$spec_item_array = explode(",",$spec_item_ids);
   		}
    	D("Cart")->where("session_id='".Session::id()."' and rec_module='PromoteGoods' and promote_id=".$promote_id)->delete();
   		foreach($spec_item_array as $k=>$v)
   		{
   			$cart_goods_item = D("PromoteGoods")->getCartItem($v);
   			$cart_item['rec_id'] = $v;
   			$cart_item['rec_module'] = 'PromoteGoods';
   			$cart_item['session_id'] = Session::id();
   			$cart_item['user_id'] = intval($_SESSION['user_id']);
   			$cart_item['number'] = 1;
   			$cart_item['create_time'] = gmtTime();  
   			$cart_item['update_time'] = gmtTime();  	
   			$cart_item['data_sn'] = $cart_goods_item['sn'];	    			
   			$cart_item['data_name'] = $cart_goods_item['name'];		
   			$cart_item['promote_id'] = $promote_id;
   			$exist_data = D("Cart")->where("session_id='".$cart_item['session_id']."' and rec_module='".$cart_item['rec_module']."' and rec_id=".$cart_item['rec_id'])->find();
   			if($exist_data)
   			{
   				$exist_data['number'] += 1;
   				$exist_data['update_time'] = gmtTime();
   				D("Cart")->save($exist_data);
   			}
   			else
   			D("Cart")->add($cart_item);	
   		}
   		$cart_promote_goods_list = D("Cart")->getPromoteGoodsList();
   		if($cart_promote_goods_list)
   		{
	   		$this->assign("cart_promote_goods_list",$cart_promote_goods_list);
	   		$this->display("Inc:cart:cart_promote_goods_list");
   		}
   }
   
   /**
    * 使用优惠券
    */
   public function useCard()
   {
   		$card_code = $_REQUEST['card_code'];
   		$rs = array('status'=>1,'info'=>'');
   		//开始验证卡号
   		$sql = "select count(*) as rs from ".
   			   C("DB_PREFIX")."promote_user_card as promote_user_card left join ".
   			   C("DB_PREFIX")."promote_card as promote_card on promote_user_card.card_id = promote_card.id ".
   			   " left join ".C("DB_PREFIX")."promote as promote on promote_card.promote_id = promote.id ".
   			   " left join ".C("DB_PREFIX")."promote_user_group as promote_user_group on promote_user_group.promote_id = promote.id ".
   			   " where promote_user_card.user_id = ".intval($_SESSION['user_id']).
   			   " and promote_user_group.user_group_id = ".intval($_SESSION['group_id']).
   			   " and promote_card.card_code = '".$card_code."' ".
   			   " and promote_card.card_limit - promote_card.card_used > 0" ;
   			    
   		$result = D()->query($sql);

   		$result = $result[0]['rs'];
   		if($result==0)
   		{
   			$rs['status'] = 0;
   			$rs['info'] = L("INVALID_PROMOTE_CARD");
   		}
   		else 
   		{
   			$session_id = Session::id();
   			M("CartCard")->where("session_id='".$session_id."' or user_id =".intval($_SESSION['user_id']))->delete();  //添加时删除原有促销卡
   			D("Cart")->where("session_id='".$session_id."' and rec_module='PromoteGoods'")->delete();  //删除原有促销券时清空所有赠品
   			$data['card_code'] = $card_code;
   			$data['user_id'] = intval($_SESSION['user_id']);
   			$data['session_id'] = $session_id;
   			$data['create_time'] = gmtTime();
   			$data['update_time'] = gmtTime();
   			M("CartCard")->add($data);
   		}
   		echo json_encode($rs);
   }
   
   /**
    * 用于计算所有的购物总计
    */
   public function getCartTotal()
   {
   		$payment_id = intval($_REQUEST['payment_id']);
   		$delivery_id = intval($_REQUEST['delivery_id']);
   		$is_protect = intval($_REQUEST['is_protect']);
   		$delivery_region = array(
   			'region_lv1'=>intval($_REQUEST['region_lv1']),
   			'region_lv2'=>intval($_REQUEST['region_lv2']),
   			'region_lv3'=>intval($_REQUEST['region_lv3']),
   			'region_lv4'=>intval($_REQUEST['region_lv4'])
   		);
   		$tax = intval($_REQUEST['tax']);
   		
   		$cart_total = D("Cart")->countCartTotal($payment_id,$delivery_id,$is_protect,$delivery_region,$tax);
   		$this->assign("cart_total",$cart_total);
   		$this->display("Inc:cart:cart_total");
   }
}
?>