<?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 OrderAction extends CommonAction{
	public function index() {
		//列表过滤器，生成查询Map对象
		$map = $this->_search ();
		if (method_exists ( $this, '_filter' )) {
			$this->_filter ( $map );
		}	
		
		$sql_str =  'SELECT a.*, (a.cost_total_price + a.cost_delivery_fee + a.cost_protect_fee + a.cost_payment_fee + a.cost_other_fee) as order_cost'.
					'  FROM '.C("DB_PREFIX").'order A ';
		
		//dump($sql_str);
         //创建数据对象
        $model = D($this->name);		
        $voList = $this->_Sql_list($model, $sql_str, $map, 'create_time', false);
        //总利润，订单数，
        $total_count = 0;
        $total_profit = 0.0;
        $total_cost = 0.0;
        foreach ($voList as $key=>$vo){
        	$total_count += 1;
        	$total_cost += $voList[$key]['order_cost'];
        	$total_profit += $voList[$key]['order_profit'];
        }
        		
        $this->assign ( 'total_count', $total_count );
        $this->assign ( 'total_cost', $total_cost );
        $this->assign ( 'total_profit', $total_profit );
        
		$this->display ();
		return;
	}

	//获得会员地址列表
	function getUserConsignee(){
		$UserConsignee_id = $_REQUEST ['UserConsignee_id'];//$_REQUEST ['memberAddress_id'];
		if (empty($UserConsignee_id)){
			$user_name = $_REQUEST ['user_name'];
			$user_name = json_decode($user_name);
			$User = D ( "User" );
			$sql_str = "select id from ".C("DB_PREFIX")."user a where user_name = '".$user_name."' limit 1";
	        $rs = $User->query($sql_str, false);
	        $user_id = $rs[0]['id'];
		        //dump($id);
			if (!empty($user_id)){
	        	$UserConsigneeList = $User->getUserConsignee($user_id);
				//dump($MemberAddressList);
				if (empty($UserConsigneeList)){
					echo json_encode($user_id);
				}else{
					echo json_encode($UserConsigneeList);
				}
			}else{
				echo json_encode("-1");
			}	        
		}else{
			$model = D ( "UserConsignee" );
			$vo = $model->getById ( $UserConsignee_id );			
			echo json_encode($vo);
		}
	}	
	
	//获取地区列表; 国家，省，地区/市，县/区
	public function getRegion3(){
		$pid = intval($_REQUEST ['pid']);
		$RegionConf = D ( "RegionConf" );
		$RegionList = $RegionConf->where("pid = ".$pid)->field("id,name")->findAll();
		//echo $RegionConf->getLastSql(); exit;
		echo json_encode($RegionList); 
	}	
	
	public function getChildData(){
		if($_REQUEST['ids']!='')
		{
			$ids = json_decode($_REQUEST['ids']);
			
			$LANG_ID = intval($_REQUEST['lang_conf_id']);
			if ($LANG_ID == 0){
				$LANG_ID = DEFAULT_LANG_ID;
			}
			
			$ids = implode(",",$ids);
			if (empty($ids)){
				$ids = "-1";
			}
			
			$sql_str = 'SELECT GoodsSpec.id AS id,'.
						'       GoodsSpec.sn AS goods_sn,'.
						'       GoodsSpec.goods_id AS goods_id,'.
						'       GoodsSpec.spec1_type_id AS spec1_type_id,'.
						'       GoodsSpec.spec1_id AS spec1_id,'.
						'       GoodsSpec.spec2_type_id AS spec2_type_id,'.
						'       GoodsSpec.spec2_id AS spec2_id,'.
						'       GoodsSpec.shop_price AS shop_price,'.
						'       GoodsSpec.cost_price AS cost_price,'.
						'       GoodsSpec.stock AS goods_stock,'.
						'       GoodsSpec.weight AS goods_weight,'.
						'       Goods.name_'.$LANG_ID.' AS goods_name,'.
						'       Goods.brand_id AS brand_id,'.
						'       Goods.cate_id AS cate_id,'.
						'       Goods.status AS status,'.
						'       Goods.score AS score,'.
						'       GoodsSpecDetail_A.spec_name_'.$LANG_ID.' AS spec_name1,'.
						'       GoodsSpecDetail_B.spec_name_'.$LANG_ID.' AS spec_name2,'.
						'       concat(CASE'.
						'                WHEN GoodsSpecDetail_A.spec_name_'.$LANG_ID.' IS NULL THEN'.
						'                 \'\''.
						'                ELSE'.
						'                 GoodsSpecDetail_A.spec_name_'.$LANG_ID.''.
						'              END,'.
						'              CASE'.
						'                WHEN GoodsSpecDetail_b.spec_name_'.$LANG_ID.' IS NULL THEN'.
						'                 \'\''.
						'                ELSE'.
						'                 concat(\'、\', GoodsSpecDetail_b.spec_name_'.$LANG_ID.')'.
						'              END) as specname'.
						'  FROM sunnyi_goods_spec_item GoodsSpec'.
						'  LEFT OUTER JOIN sunnyi_goods Goods ON Goods.id = GoodsSpec.goods_id'.
						'  LEFT OUTER JOIN sunnyi_goods_spec GoodsSpecDetail_A ON GoodsSpecDetail_A.id ='.
						'                                                        GoodsSpec.spec1_id'.
						'  LEFT OUTER JOIN sunnyi_goods_spec GoodsSpecDetail_B ON GoodsSpecDetail_B.id ='.
						'                                                        GoodsSpec.spec2_id'.
						' WHERE GoodsSpec.id in ('.$ids.')';
			
			
	         //创建数据对象
	        $model = D("Order");		
	        $voList = $model->query($sql_str);
	        foreach($voList as $k=>$vo){
	        	if (empty($vo['specname']))
	        	{
	        		$voList[$k]['specname'] = $vo['goods_name'];
	        	}else{
	        		$voList[$k]['specname'] = $vo['goods_name'].'('.$vo['specname'].')';
	        	}	
	        }
			echo json_encode($voList);
		}		
	}
		
	function commAssign(&$order, $calc_radio){
		$id = intval($order['id']);
		
		//货币
		$Currency = D ( "Currency" );
		$CurrencyList = $Currency->field('id,name_'.DEFAULT_LANG_ID.' as name')->findAll();
		$this->assign ( "currencyList", $CurrencyList );
		
		//支付方式
		$PaymentMode = D ( "Payment" );
		$PaymentModeList = $PaymentMode->field('id,name_'.DEFAULT_LANG_ID.' as name')->findAll();
		$this->assign ( "paymentModeList", $PaymentModeList );		
	
		//配送方式
		$FreightMode = D ( "Delivery" );
		$FreightModeList = $FreightMode->field('id,name_'.DEFAULT_LANG_ID.' as name')->findAll();
		$this->assign ( "freightModeList", $FreightModeList );

		//地区：国家
		$RegionConf = D ( "RegionConf" );
		$region_lv1List = $RegionConf->where("pid = 0")->field("id,name")->findAll();
		//dump($region_lv1List);
		$this->assign ( "region_lv1List", $region_lv1List);
				
		//语言列表
		$lang_envs = D("LangConf")->field("id, show_name as name")->findAll();
		$this->assign ( "langList", $lang_envs);
		
		//会员地址列表
		$User = D ( "User" );
		$UserConsigneeList = $User->getUserConsignee(intval($order['user_id']));
		$this->assign ( "userConsigneeList", json_encode($UserConsigneeList));		
		
		$this->assign ( 'user', $User->getById(intval($order['user_id'])));
				
		
		if ($id != 0){
			$OrderGoods = D ( "OrderGoods" );
			$OrderGoodsList = $OrderGoods->where('order_id='.intval($order['id']))->findAll();
			$this->assign ( "orderGoodsList", $OrderGoodsList);	
			//dump($OrderGoodsList);
			
			$lc_vo = D("LangConf")->field("id, show_name as name")->getById(intval($order['lang_conf_id']));
			$order['lang_name'] = $lc_vo['name'];
						
			$fm_vo = $FreightMode->field('id,name_'.DEFAULT_LANG_ID.' as name')->getById(intval($order['delivery']));
			$order['delivery_name'] = $fm_vo['name'];
			
			$cu_vo = $Currency->field('id,name_'.DEFAULT_LANG_ID.' as name')->getById(intval($order['currency_id']));
			$order['currency_name'] = $cu_vo['name'];			
			
			
			$pm_vo = $PaymentMode->field('id,name_'.DEFAULT_LANG_ID.' as name')->getById(intval($order['payment']));
			$order['payment_name'] = $pm_vo['name'];
			//$order['payment_fee'] = $pm_vo['fee'];
			
			if ($calc_radio == 1){
		         //商品总金额
		         $order['total_price'] = round($order['total_price'] * $order['currency_radio'], 3);
		         //配送费用
		         $order['delivery_fee'] = round($order['delivery_fee'] * $order['currency_radio'], 3);
		         //保价
		         $order['protect_fee'] = round($order['protect_fee'] * $order['currency_radio'], 3);
		         //促销优惠金额
		         $order['promote_money'] = round($order['promote_money'] * $order['currency_radio'], 3);
		         //税金
		         $order['tax_money'] = round($order['tax_money'] * $order['currency_radio'], 3); 
		         //支付手续费
		         $order['payment_fee'] = round($order['payment_fee'] * $order['currency_radio'], 3);         
		         //订单总金额
		         $order['order_total_price'] = round($order['order_total_price'] * $order['currency_radio'], 3); 					
			}
		}

		$order['money_status_name'] = L("ORDER_MONEY_STATUS_".intval($order['money_status']));
		$order['goods_status_name'] = L("ORDER_GOODS_STATUS_".intval($order['goods_status']));
		$order['status_name'] = L("ORDER_STATUS_".intval($order['status']));
		
	}
		
	function add() {
		$this->edit();
	}
		
    	
	public function edit() {
		$id = intval($_REQUEST['id']);
		
		$model = D("Order");
		if ($id == 0){//新增
			$this->assign ( 'isNew', json_encode(true) );
			$vo = $model->create();
			$vo['id'] = 0;		
			//下单时间
			$vo ['create_time'] = timeToLocalStr(time(), 'Y-m-d h:i:s');		
			//订单号
			$vo ['sn'] = timeToLocalStr(time(), 'Ymdhis');
			//送货日期 任意日期
			$vo ['money_status'] = 0;
			$vo ['goods_status'] = 0;
			$vo ['region_lv1'] = -1;
			$vo ['region_lv2'] = -1;
			$vo ['region_lv3'] = -1;
			$vo ['region_lv4'] = -1;
			$vo ['currency_radio'] = 1;		
		}else{//编辑
			$this->assign ( 'isNew', json_encode(false) );
			$vo = $model->getById ( $id );
			$vo ['create_time'] = timeToLocalStr($vo ['create_time'], 'Y-m-d h:i:s');
		}
		
		$this->commAssign($vo, 1);
		
		$this->assign ( 'vo', $vo );
		//dump($vo);
		$this->display ( 'edit' );		
	}

	public function show(){
		
		$id = intval($_REQUEST['id']);
		
		$model = D("Order");
				
		$vo = $model->getById ( $id );
		$vo ['create_time'] = timeToLocalStr($vo ['create_time'], 'Y-m-d h:i:s');
		
		$this->commAssign($vo, 0);
		
		$this->assign ( 'vo', $vo );
		
		//收款单
		$sql_str =  'SELECT A.*,'.
					'       b.sn as ORDER_SN,'.
					'       b.order_total_price as  final_amount,'.
					'       c.name_'.DEFAULT_LANG_ID.' as PName,'.
					'       d.name_'.DEFAULT_LANG_ID.' AS AName'.
					'  FROM '.C("DB_PREFIX").'order_incharge A'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'ORDER B ON B.ID = A.ORDER_ID'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'PAYMENT C ON C.ID = A.PAYMENT_ID'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'currency D ON D.ID = A.currency_id'.
					'  where b.id ='.$id.
					' ORDER BY a.create_time desc';
		
		$order_incharge_list = $model->query($sql_str);
		$this->assign ( 'order_incharge_list', $order_incharge_list );
		
		//退款单
		$sql_str =  'SELECT A.*,'.
					'       b.sn as ORDER_SN,'.
					'       b.order_total_price as  final_amount,'.
					'       c.name_'.DEFAULT_LANG_ID.' as PName,'.
					'       d.name_'.DEFAULT_LANG_ID.' AS AName'.
					'  FROM '.C("DB_PREFIX").'order_uncharge A'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'ORDER B ON B.ID = A.ORDER_ID'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'PAYMENT C ON C.ID = A.PAYMENT_ID'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'currency D ON D.ID = A.currency_id'.
					'  where b.id ='.$id.
					' ORDER BY a.create_time desc';		
		$order_uncharge_list = $model->query($sql_str);
		$this->assign ( 'order_uncharge_list', $order_uncharge_list );

		//发货单
		$sql_str =  'SELECT A.*,'.
					'       b.sn as order_sn,'.
					'       b.order_total_price as final_amount,'.
					'       c.name_'.DEFAULT_LANG_ID.' as fname,'.
					'       d.user_name as mname'.
					'  FROM '.C("DB_PREFIX").'order_consignment A'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'ORDER B ON A.ORDER_ID = B.ID'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'delivery C ON A.delivery_id = C.ID'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'user D ON B.user_id = D.ID'.
					'  where b.id ='.$id.
					' ORDER BY a.create_time desc';
		$order_consignment_list = $model->query($sql_str);
		$this->assign ( 'order_consignment_list', $order_consignment_list );
				
		//退货单
		$sql_str =  'SELECT A.*,'.
					'       b.sn as order_sn,'.
					'       b.order_total_price as final_amount,'.
					'       c.name_'.DEFAULT_LANG_ID.' as fname,'.
					'       d.user_name as mname'.
					'  FROM '.C("DB_PREFIX").'order_re_consignment A'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'ORDER B ON A.ORDER_ID = B.ID'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'delivery C ON A.delivery_id = C.ID'.
					'  LEFT OUTER JOIN '.C("DB_PREFIX").'user D ON B.user_id = D.ID'.
					'  where b.id ='.$id.
					' ORDER BY b.sn, a.id';
		$order_re_consignment_list = $model->query($sql_str);
		$this->assign ( 'order_re_consignment_list', $order_re_consignment_list );	

		//优惠方式
		$sql_str =  'SELECT A.*'.
					'  FROM '.C("DB_PREFIX").'order_promote A'.
					'  where a.order_id ='.$id.
					' ORDER BY a.priority desc';
		$order_promote_list = $model->query($sql_str);
		$this->assign ( 'order_promote_list', $order_promote_list );
				
		//dump($vo);
		$this->display ( 'show' );			
	}
	
	//添加，修改保存时公共调用的函数
	function commSave($model,&$vo, $currency_radio){
		
		$saveAddress = $_REQUEST['saveAddress'];
		import('ORG.Util.HashMap');
        $rec_module_list = array();
        $goods_id_list = array();
        $goods_sn_list = array();
        $goods_name_list = array();
        $goods_price_list = array();
        $goods_num_list = array();
        $price_sum_list = array();
        $goods_weight_list = array();
        $goods_score_list = array();
        
        $rec_module_list = $_REQUEST['rec_module_list'];
        $goods_id_list = $_REQUEST['goods_id_list'];
        $goods_sn_list = $_REQUEST['goods_sn_list'];
        $goods_name_list = $_REQUEST['goods_name_list'];
        $cost_price_list = $_REQUEST['cost_price_list'];
        $goods_price_list = $_REQUEST['goods_price_list'];
        $goods_num_list = $_REQUEST['goods_num_list'];
        $price_sum_list = $_REQUEST['price_sum_list'];
        $goods_weight_list = $_REQUEST['goods_weight_list'];
        $goods_score_list = $_REQUEST['goods_score_list'];
        //dump($calc_score);	

		//商品明细
		$order_id = intval($vo['id']);
        
		$sql_str = 'delete from '.C("DB_PREFIX").'order_goods where order_id = '.$order_id;
		
		$model->execute($sql_str);							 	
	
		$total = count($goods_id_list);
		for($i=0;$i<$total;$i++){
			$sql_str = 'insert into '.C("DB_PREFIX").'order_goods(order_id,rec_module, rec_id, data_sn,data_name,data_cost_price, data_price,number,data_total_price,data_weight,data_score,send_number) values('.
				$order_id.','.
				'\''.$rec_module_list[$i].'\','.
				'\''.$goods_id_list[$i].'\','.
				'\''.$goods_sn_list[$i].'\','.
				'\''.$goods_name_list[$i].'\','.
				'\''.$cost_price_list[$i]*$currency_radio.'\','.
				'\''.$goods_price_list[$i]*$currency_radio.'\','.
				'\''.$goods_num_list[$i].'\','.
				'\''.$price_sum_list[$i]*$currency_radio.'\','.
				'\''.$goods_weight_list[$i].'\','.
				'\''.$goods_score_list[$i].'\','.
				'0)';
			//dump($sql_str);
			$model->execute($sql_str);			
		}			        		

			        		
		//保存本次收货地址到会员地址列表
		if (($saveAddress == 1 || $saveAddress == true) && (!empty($vo['user_id']) && $vo['user_id'] > 0)){
			//MemberAddress
			$condition = array();
			
			$condition['user_id'] = $vo['user_id'];
			$condition['consignee'] = $vo['consignee'];
			$condition['region_lv1'] = $vo['region_lv1'];
			$condition['region_lv2'] = $vo['region_lv2'];
			$condition['region_lv3'] = $vo['region_lv3'];
			$condition['region_lv4'] = $vo['region_lv4'];
			$condition['address'] = $vo['address'];
			$condition['zip'] = $vo['zip'];
			$condition['mobile_phone'] = $vo['mobile_phone'];
			$condition['fix_phone'] = $vo['fix_phone'];
			
			$UserConsignee = D( "UserConsignee" );
			if ($UserConsignee->where($condition)->count() == 0){
				$ma_vo = $UserConsignee->create();
				$ma_vo['user_id'] = $vo['user_id'];
				$ma_vo['consignee'] = $vo['consignee'];
				$ma_vo['region_lv1'] = $vo['region_lv1'];
				$ma_vo['region_lv2'] = $vo['region_lv2'];
				$ma_vo['region_lv3'] = $vo['region_lv3'];
				$ma_vo['region_lv4'] = $vo['region_lv4'];
				$ma_vo['address'] = $vo['address'];
				$ma_vo['zip'] = $vo['zip'];
				$ma_vo['mobile_phone'] = $vo['mobile_phone'];
				$ma_vo['fix_phone'] = $vo['fix_phone'];
				$ma_vo['id'] = null;
				$UserConsignee->add($ma_vo);
			}				
		}
	}
		
   function save()
    {
		$model	=	D("Order");
        if(false === $vo = $model->create()) {
        	$this->error($model->getError());
        }
         //是否要保价
         $vo ['protect'] = ! empty($_POST ['protect']) ? 1:0;
         //是否开发票
         $vo ['tax'] = ! empty($_POST ['tax']) ? 1:0;

         $vo['create_time'] = ! empty ( $_POST ['create_time'] ) ? localStrToTime($_POST ['create_time'] ) : 0;
         
         $vo['update_time'] = gmtTime();
          
         if (empty($vo['currency_radio']) || $vo['currency_radio'] == 0){
         	$vo['currency_radio'] = 1;
         }
         $currency_radio = 1 / $vo['currency_radio'];
         
         
         //商品总金额
         $vo['total_price'] = $vo['total_price'] * $currency_radio;
         //配送费用
         $vo['delivery_fee'] = $vo['delivery_fee'] * $currency_radio;
         //保价
         $vo['protect_fee'] = $vo['protect_fee'] * $currency_radio;
         //促销优惠金额
         $vo['promote_money'] = $vo['promote_money'] * $currency_radio;
         //税金
         $vo['tax_money'] = $vo['tax_money'] * $currency_radio; 
         //支付手续费
         $vo['payment_fee'] = $vo['payment_fee'] * $currency_radio;         
         //订单总金额
         $vo['order_total_price'] = $vo['order_total_price'] * $currency_radio;          
         
         //商品成本  
	     $cost_price_list = $_REQUEST['cost_price_list'];
	     $goods_num_list = $_REQUEST['goods_num_list'];         
	     $cost_total_price = 0;
    	  for($i=0;$i<count($cost_price_list);$i++){
		  	$cost_total_price = $cost_total_price + floatval($cost_price_list[$i]) * floatval($goods_num_list[$i]) * $currency_radio;		
		  }
		 $vo['cost_total_price'] = $cost_total_price;      
         
        //保存当前数据对象
    	if (intval($_REQUEST['id']) == 0){
			$vo['id'] = $model->add($vo);
			
			//dump($model->getLastSql());
			if ($vo['id']!==false) { //保存成功
				$this->commSave($model, $vo, $currency_radio);
				$this->saveLog(1,$vo['id']);
				$this->assign ('jumpUrl', u('Order/show', array('id'=>intval($vo['id']))));
				$this->success (L('ADD_SUCCESS'));
			} else {
				//失败提示
				$this->saveLog(0,$vo['id']);
				$this->error (L('ADD_FAILED'));
			}			
		}else{
			// 更新数据
			$list = $model->save($vo);
			//dump($model->getLastSql());
			if (false !== $list) {
				//dump('aa');
				$this->commSave($model, $vo, $currency_radio);
				
				//成功提示
				$this->saveLog(1);
				$this->assign ('jumpUrl', u('Order/show', array('id'=>intval($vo['id']))));
				$this->success (L('EDIT_SUCCESS'));
			} else {
				//错误提示
				$this->saveLog(0);
				$this->error (L('EDIT_FAILED'));
			}			
		}
    }
	
	public function foreverdelete() {
		//删除指定记录
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if (isset ( $id )) {
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				if (false !== $model->where ( $condition )->delete ()) {
					//echo $model->getlastsql();
					D("OrderGoods")->where(array ("order_id" => array ('in', explode ( ',', $id ) ) ))->delete();  //同步删除礼包
					$msgList = D("Message")->where(array ("rec_module"=>'Order',"rec_id" => array ('in', explode ( ',', $id ) ) ))->findAll();  //同步删除礼包
					D("Message")->where(array ("rec_module"=>'Order',"rec_id" => array ('in', explode ( ',', $id ) ) ))->delete();  //删除订单留言
					foreach($msgList as $msg)
					{
						D("Message")->where("pid=".$msg['id'])->delete();  //删除订单留言的相关回复
					}
					$this->saveLog(1);
					$this->success (L('DEL_SUCCESS'));
				} else {
					$this->saveLog(0);
					$this->error (L('DEL_FAILED'));
				}
			} else {
				$this->saveLog(0);
				$this->error ( L('INVALID_OP') );
			}
		}
		$this->forward ();
	}
	
	
	function add_incharge() {
		
		$this->assign ( 'isNew', true );
		$id = intval($_REQUEST['id']);
		$OrderIncharge = D ("OrderIncharge");
		if ($id == 0){
			$vo = $OrderIncharge->create();
		}else{
			$vo = $OrderIncharge->getById ( $id );
		}
		
		$model = D ("Order");
		$order_id = $_REQUEST ['order_id'];
		$order_vo = $model->getById ( $order_id );
		//下单时间
		$order_vo['create_time'] = timeToLocalStr($order_vo ['create_time'], 'Y-m-d h:i:s');
		//收款状态：0:未收款; 1:部分收款; 2:全部收款; 3:部分退款; 4:全部退款
		$order_vo['money_status_name'] = L("ORDER_MONEY_STATUS_".intval($order_vo['money_status']));
         
	    //订单总金额
	    $order_vo['order_total_price'] = round($order_vo['order_total_price'] * $order_vo['currency_radio'], 3);
		//已收金额	
	    $order_vo['order_incharge'] = round($order_vo['order_incharge'] * $order_vo['currency_radio'], 3);
	         
		$this->assign ( 'order_vo', $order_vo );

		//支付方式
		$user_money = 0.0;//会员帐户余额
		$PaymentMode = D ( "Payment" );
		if ($order_vo['user_id'] > 0) //如果不是会员，则无法使用：余额支付
		{
		  $PaymentList = $PaymentMode->field('id,name_'.DEFAULT_LANG_ID.' as name')->findAll();
		  //$sql_str = 'select money from '.C("DB_PREFIX").'user where id = '.$order_vo['user_id'];
		  //$money = $model->getSqlValue($sql_str, 'money');
		  
		  $user =  D ('User')->getById ($order_vo['user_id']);
		  $user['money'] = round($user['money'] * $order_vo['currency_radio'], 3);
		  $user_money = $user['money']; 
		  $this->assign ( 'user', $user);
		}else{ 
		  $PaymentList = $PaymentMode->where('class_name <> \'Accountpay\'')->field('id,name_'.DEFAULT_LANG_ID.' as name')->findAll ();
		}	
		  
		//支付方式
		$this->assign ( "user_money", $user_money);  
		$this->assign ( "paymentList", $PaymentList );

		//dump($PaymentList);
		
		//货币
		$Currency = D ( "Currency" );
		$CurrencyList = $Currency->field('id,name_'.DEFAULT_LANG_ID.' as name')->findAll();
		$this->assign ( "currencyList", $CurrencyList );
		
		//dump($CurrencyList);
		
		
		$vo['order_id'] = $order_id;
		$vo['currency_id'] = $order_vo['currency_id'];
		$vo['currency_radio'] = $order_vo['currency_radio'];
		$vo['money'] = $order_vo['order_total_price'] - $order_vo['order_incharge'];
		
		
		$this->assign ( 'vo', $vo );
		
		$this->display ( 'incharge' );
	}
	
   function save_incharge()
    {
		$model	=	D("OrderIncharge");
        if(false === $vo = $model->create()) {
        	$this->error($model->getError());
        }
        
         if (empty($vo['currency_radio']) || $vo['currency_radio'] == 0){
         	$vo['currency_radio'] = 1;
         }
         $currency_radio = 1 / $vo['currency_radio'];
                 
         //收款金额
        $vo['money'] = $_REQUEST['money'] * $currency_radio;
        $vo['cost_payment_fee'] = $_REQUEST['cost_payment_fee'] * $currency_radio;
                
		$Payment = D ( "Payment" );
		$payment = $Payment->getById(intval($_REQUEST ['payment_id']));
		        
		$user_id = intval($_REQUEST ['user_id']);
    	if ($payment['class_name'] == 'Accountpay' && $user_id > 0){//会员使用预存款支付
		  $user = D ('User')->getById ($user_id);
		  if (($user['money'] < 0) || ($vo['money'] - $user['money'] > 0.01 )){
            //失败提示
            $this->error('会员帐户余额不足，请选择其它支付方式。');
            exit;	  	
		  } 
		}        
        
        //保存当前数据对象
        $vo['create_time'] = gmtTime();
		
        $id = $model->add($vo);
        
        if($id) { //保存成功
            //增加已收金额
            //dump('ccc');
			inc_order_incharge($id);
			//dump('ffff');
			//$this->
			
			$this->assign ('jumpUrl', u('Order/show', array('id'=>intval($vo['order_id']))));
            $this->success(L('ADD_SUCCESS'));
        }else {
            //失败提示
            $this->error(L('ADD_FAIL'));
        }
    }

	
	function add_uncharge() {
		
		$this->assign ( 'isNew', true );
		$id = intval($_REQUEST['id']);
		$OrderIncharge = D ("OrderIncharge");
		if ($id == 0){
			$vo = $OrderIncharge->create();
		}else{
			$vo = $OrderIncharge->getById ( $id );
		}
		
		$model = D ("Order");
		$order_id = $_REQUEST ['order_id'];
		$order_vo = $model->getById ( $order_id );
		//下单时间
		$order_vo['create_time'] = timeToLocalStr($order_vo ['create_time'], 'Y-m-d h:i:s');
		//收款状态：0:未收款; 1:部分收款; 2:全部收款; 3:部分退款; 4:全部退款
		$order_vo['money_status_name'] = L("ORDER_MONEY_STATUS_".intval($order_vo['money_status']));
         
	    //订单总金额
	    $order_vo['order_total_price'] = round($order_vo['order_total_price'] * $order_vo['currency_radio'], 3);
		//已收金额	
	    $order_vo['order_incharge'] = round($order_vo['order_incharge'] * $order_vo['currency_radio'], 3);
	         
		$this->assign ( 'order_vo', $order_vo );

		//支付方式
		$user_money = 0.0;//会员帐户余额
		$PaymentMode = D ( "Payment" );
		if ($order_vo['user_id'] > 0) //如果不是会员，则无法使用：余额支付
		{
		  $PaymentList = $PaymentMode->field('id,name_'.DEFAULT_LANG_ID.' as name')->findAll();
		  //$sql_str = 'select money from '.C("DB_PREFIX").'user where id = '.$order_vo['user_id'];
		  //$money = $model->getSqlValue($sql_str, 'money');
		  
		  $user =  D ('User')->getById ($order_vo['user_id']);
		  $user['money'] = round($user['money'] * $order_vo['currency_radio'], 3);
		  $user_money = $user['money']; 
		  $this->assign ( 'user', $user);
		}else 
		  $PaymentList = $PaymentMode->where('class_name <> \'Accountpay\'')->field('id,name_'.DEFAULT_LANG_ID.' as name')->findAll ();
			
		  
		//支付方式
		$this->assign ( "user_money", $user_money);  
		$this->assign ( "paymentList", $PaymentList );

		//dump($PaymentList);
		
		//货币
		$Currency = D ( "Currency" );
		$CurrencyList = $Currency->field('id,name_'.DEFAULT_LANG_ID.' as name')->findAll();
		$this->assign ( "currencyList", $CurrencyList );
		
		//dump($CurrencyList);
		
		
		$vo['order_id'] = $order_id;
		$vo['currency_id'] = $order_vo['currency_id'];
		$vo['currency_radio'] = $order_vo['currency_radio'];
		$vo['money'] = $order_vo['order_incharge'];
		$vo['dec_score'] = $order_vo['order_score'];
		
		$this->assign ( 'vo', $vo );
		
		$this->display ( 'uncharge' );
	}
	
   function save_uncharge()
    {
		$model	=	D("OrderUncharge");
        if(false === $vo = $model->create()) {
        	$this->error($model->getError());
        }
        
         if (empty($vo['currency_radio']) || $vo['currency_radio'] == 0){
         	$vo['currency_radio'] = 1;
         }
         $currency_radio = 1 / $vo['currency_radio'];
                 
         //收款金额
        $vo['money'] = $_REQUEST['money'] * $currency_radio;
        $vo['cost_payment_fee'] = $_REQUEST['cost_payment_fee'] * $currency_radio;                
        
        //保存当前数据对象
        $vo['create_time'] = gmtTime();
		
        $id = $model->add($vo);
        
        if($id) { //保存成功
            //减少已收金额
			$this->inc_order_uncharge($id);
			
			$this->assign ('jumpUrl', u('Order/show', array('id'=>intval($vo['order_id']))));
            $this->success(L('ADD_SUCCESS'));
        }else {
            //失败提示
            $this->error(L('ADD_FAIL'));
        }
    }
    	
	//减少已收金额
	function inc_order_uncharge($order_uncharge_id){
		
		$uncharge_vo = D("OrderUncharge")->getById ( $order_uncharge_id );
		
		$model = D("Order");
		$order_vo = $model->getById ( $uncharge_vo['order_id'] );
		$order_vo['order_incharge'] = $order_vo['order_incharge'] - $uncharge_vo['money'];

		
		$payment = D ( "Payment" )->getById($uncharge_vo['payment_id']);
		if ($payment['class_name'] == 'Accountpay' && $order_vo['user_id'] > 0){//会员使用预存款支付，减少预存款
			//记录会员预存款变化明细
			$sql_str = 'insert into '.C("DB_PREFIX").'user_money_log(user_id, rec_id, money,create_time,rec_module,memo) values('.
				$order_vo['user_id'].','.
				$order_uncharge_id.','.
				$uncharge_vo['money'].','.
				gmtTime().','.
				'\'OrderUncharge\','.
				'\''.L("ORDER_CHARGE_MEMO_2").'\','.  //预存款退款
				')';
			//dump($sql_str);
			$model->execute($sql_str);	
			//减去会员的预存款金额
			$sql_str = 'update '.C("DB_PREFIX").'user set money = money + '.$uncharge_vo['money'].' where id = '.$order_vo['user_id'];
			$model->execute($sql_str);
		} 
		
		
			//dump($sql_str);
		//会员积明细,扣掉订单所得积分	
		if ($order_vo['user_id'] > 0 && $uncharge_vo['dec_score'] > 0){
				$sql_str = 'insert into '.C("DB_PREFIX").'user_score_log(user_id, create_time, score, memo) values('.
					$order_vo['user_id'].','.
					gmtTime().','.
					$uncharge_vo['dec_score'].','.
					'\''.L("ORDER_SCORE_MEMO_3").'('.$order_vo['sn'].')\''.  //扣掉订单所得积分
					')';
				$model->execute($sql_str);	

			//增加会员积分
			$sql_str = 'update '.C("DB_PREFIX").'user set score = score - '.$uncharge_vo['dec_score'].' where id = '.$order_vo['user_id'];
			$model->execute($sql_str);				
		} 		
		
		//已收金额 > 订单总金额
		//收款状态：0:未收款; 1:部分收款; 2:全部收款; 3:部分退款; 4:全部退款		
		if ($order_vo["order_incharge"] <= 0.01){
			$order_vo["money_status"] = 4;
		}else if($order_vo["order_incharge"] < $order_vo['order_total_price']){
			$order_vo["money_status"] = 3;
		}		
		
		//退款手续费
		$order_vo["cost_payment_fee"] = floatval($order_vo["cost_payment_fee"]) + $uncharge_vo['cost_payment_fee'];	
			
		$model->save($order_vo);
	}

	
	public function profit() {
		$id = intval($_REQUEST['order_id']);
		
		$model = D("Order");
		if ($id == 0){//新增
			$this->error('无效订单ID');	
		}else{//编辑
			$vo = $model->getById ( $id );
			$vo ['create_time'] = timeToLocalStr($vo ['create_time'], 'Y-m-d h:i:s');
			$vo['money_status_name'] = L("ORDER_MONEY_STATUS_".intval($vo['money_status']));
			$vo['goods_status_name'] = L("ORDER_GOODS_STATUS_".intval($vo['goods_status']));
					
			$this->assign ( 'vo', $vo );
			//dump($vo);
			$this->display ( 'profit' );			
		}
	}	
	
	//订单完成
   function save_profit()
    {
		$model	=	D("Order");
        if(false === $vo = $model->create()) {
        	$this->error($model->getError());
        }
        
        //保存当前数据对象
        $vo['update_time'] = gmtTime();
        if ($vo['status'] != 1){//订单状态 0: 处理中1: 完成2: 作废
        	$vo['status'] = 1;
        	//发放优惠卷
        	if ($vo['user_id'] > 0){
        		$sql_str = 'select a.* from '.C("DB_PREFIX").'order_promote a left outer join '.C("DB_PREFIX").'promote b where b.promote_type_id = 5 and order_id = '.intval($vo['id']);
        		$voList = $model->query($sql_str);
        		if ($voList != false){
	        		$puc_model = D ('PromoteUserCard');
			        foreach($voList as $k=>$cart_vo){
			        	$card_id = intval($cart_vo['card_id']);
			        	$num = intval($cart_vo['promote_data_number']);
			        	if ($card_id > 0 && $num > 0)
			        	{
			        		$p_vo = D ('Promote')->getById ($card_id);
			        		$pc_model = D ('PromoteCard');
							for($i=0;$i<$num;$i++){
								//生成新的优惠卡
								$pc_vo = $pc_model->create();
								$pc_vo['id'] = null;
								$pc_vo['promote_id'] = $card_id;
								$pc_vo['card_limit'] = $p_vo['card_limit'];
								$pc_vo['card_used'] = 0;
								$pc_id = $pc_model->add($pc_vo);
								
								$pc_vo['id'] = $pc_id;
								$pc_vo['card_code'] = buildCard($pc_id);
								$pc_model->save($pc_vo);
								
								//将优惠卡赋值给会员
								$puc_vo = $puc_model->create();
								$puc_vo['id'] = null;
								$puc_vo['user_id'] = $vo['user_id'];
								$puc_vo['card_id'] = $pc_id;
								$puc_model->save($puc_vo);
						 }
			        }//if ($card_id > 0 && $num > 0)
			        //统计发放总量	
					$sql_str = 'update '.C("DB_PREFIX").'promote set card_total = (select count(*) from '.C("DB_PREFIX").'promote_card where promote_id = '.$card_id.') where id ='.$card_id;
					$model->execute($sql_str);			    
			   }//foreach($voList as $k=>$cart_vo)     
        	}//if ($voList != false)
        }//if ($vo['user_id'] > 0)
    }//if ($vo['status'] != 1)
				
    $id = $model->save($vo);
    if($id) { //保存成功		
		$this->assign ('jumpUrl', u('Order/show', array('id'=>intval($vo['id']))));
        $this->success(L('EDIT_SUCCESS'));
    }else {
       //失败提示
       $this->error(L('EDIT_FAIL'));
    }
  }	
}
?>