<?php
function setBaseMoney($money,$currency_id)
{
	$currency_radio = D("Currency")->where("id=".$currency_id)->getField("radio");
	if(!$currency_radio) $currency_radio = 1;
	return $money / $currency_radio;
}

function getBaseMoney($money,$currency_id)
{
	$currency_radio = D("Currency")->where("id=".$currency_id)->getField("radio");
	if(!$currency_radio) $currency_radio = 1;
	return str_replace(",","", number_format(round($money * $currency_radio,2),2));
}

	//用于加载读取相应语言包中的语言变量，前台语言
	function load_lang($key,$lang_id)
	{
		$lang_set = D("LangConf")->where("id=".$lang_id)->getField("lang_name");
		//加载当前语言的语言包
		L(include './app/Lang/'.$lang_set.'/common.php');		
		return L($key);
	}
	//记录会员预存款变化明细
	//$memo 格式为 #LANG_KEY#memos  ##之间所包含的是语言包的变量
	function user_money_log($user_id, $rec_id, $rec_module, $money, $memo, $onlylog = false){
		$user_id = intval($user_id);
		$money = floatval($money);
		$langs = D("LangConf")->findAll();
		
		$log_data = array();
		$log_data['user_id'] = $user_id;
		$log_data['money'] = $money;
		$log_data['rec_id'] = $rec_id;
		$log_data['rec_module'] = $rec_module;
		$log_data['create_time'] = gmtTime();
		foreach($langs as $lang)
		{
			$lang_memo = $memo;
			preg_match_all("/#([^#]*)#/",$memo,$keys);
			foreach($keys[1] as $key)
			{				
				
				$lang_memo = preg_replace("/#[^#]*#/",load_lang($key,$lang['id']),$lang_memo);
			}
			$log_data['memo_'.$lang['id']]= $lang_memo;
		}		
		//记录会员预存款变化明细
		M("UserMoneyLog")->add($log_data);
		if ($onlylog == false){
			//增加会员的预存款金额
			$sql_str = 'update '.C("DB_PREFIX").'user set money = money + '.floatval($money).' where id = '.$user_id;
			D()->execute($sql_str);	
		}
		return true;
	}

	//记录会员预存款变化明细
	//$memo 格式为 #LANG_KEY#memos#LANG_KEY#  ##之间所包含的是语言包的变量
	function user_score_log($user_id, $rec_id, $rec_module, $score, $memo, $onlylog = false){
		$user_id = intval($user_id);
		$langs = D("LangConf")->findAll();
		
		$log_data = array();
		$log_data['user_id'] = $user_id;
		$log_data['score'] = $score;
		$log_data['rec_id'] = $rec_id;
		$log_data['rec_module'] = $rec_module;
		$log_data['create_time'] = gmtTime();
		foreach($langs as $lang)
		{
			$lang_memo = $memo;
			preg_match_all("/#([^#]*)#/",$memo,$keys);
			foreach($keys[1] as $key)
			{				
				
				$lang_memo = preg_replace("/#[^#]*#/",load_lang($key,$lang['id']),$lang_memo);
			}
			$log_data['memo_'.$lang['id']]= $lang_memo;
		}		
		//记录会员预存款变化明细
		M("UserScoreLog")->add($log_data);
		if ($onlylog == false){
			$sql_str = 'update '.C("DB_PREFIX").'user set score = score + '.intval($score).' where id = '.$user_id;
			D()->execute($sql_str);	
		}
		
		return true;
	}
	function order_paid($payment_log_id, $money, $payment_id, $currency_id){
        $result  =  array();
	    $PaymentLog = M("PaymentLog");
    	$payment_log_vo = $PaymentLog->getById ($payment_log_id);
    	if ($payment_log_vo == false){
    		return L('INVALID_PAY_LOG_ID').$payment_log_id;
    	}

    	if ($payment_log_vo['rec_module'] == 'Order'){
    		$status = order_paid_in($payment_log_id, $money, $payment_id, $currency_id);
    	}elseif ($payment_log_vo['rec_module'] == 'UserIncharge'){//在线冲值
    	    
    		$model = M("UserIncharge");
    		$vo = $model->getById($payment_log_vo['rec_id']);
        	if ($vo == false){
    			$status = L('INVALID_USER_INCHAREG_ID');
    		} 

    		$currency = M( "Currency" )->getById(intval($currency_id));
		
			//$vo['money'] = $money * $currency['radio'];
			$vo['update_time'] = gmtTime();
			$vo['status'] = 1;
			$model->save($vo);
			    		
			$status = user_money_log($vo['user_id'], $vo['id'], 'UserIncharge', $vo['money'] * -1, L("ORDER_CHARGE_MEMO_3"));
    	}
		
		if ($status == true){
			$result['status']  =  true;
        	$result['info'] = L('PAY_LOG_ID').':'.$payment_log_id.L('PAY_MONEY').':'. $money .L('PAY_SUCCESS');
        	$result['data'] = L('PAY_LOG_ID').':'.$payment_log_id.L('PAY_MONEY').':'. $money .L('PAY_SUCCESS');
		}else{
			$result['status'] = false;
        	$result['info'] = $status;
        	$result['data'] = $status;			
		}
		
		return $result;
	}
	
	//处理成功返回true，处理失败返回，错误消息
    function order_paid_in($payment_log_id, $money, $payment_id, $currency_id){
    	$PaymentLog = M("PaymentLog");
    	$payment_log_vo = $PaymentLog->getById ($payment_log_id);
    	if ($payment_log_vo == false){
    		return L('INVALID_PAY_LOG_ID').$payment_log_id;
    	}
        if ($payment_log_vo['is_paid'] == 1){
    		return L('PAY_LOG_ID').$payment_log_id.L('PAY_LOG_ID_INVALID');
    	}   
    	        
		/* 修改此次支付操作的状态为已付款 */
        $payment_log_vo['is_paid'] = 1;
        $PaymentLog->save($payment_log_vo);
                	
    	$model = M("Order");
    	$order_vo = $model->getById($payment_log_vo['rec_id']);
        if ($order_vo == false){
    		return L('INVALID_ORDER_ID');
    	}
    	
		$payment = M( "Payment" )->getById(intval($payment_id));
        if ($payment == false){
    		return L('INVALID_PAYMENT_ID');
    	}		
    	
		$user_id = intval($order_vo['user_id']);
    	if ($payment['class_name'] == 'Accountpay'){//会员使用预存款支付
    	  if ($user_id > 0){
    	     $user = M('User')->getById ($user_id);
		  	 if (($user['money'] < 0) || ($order_vo['money'] - $user['money'] > 0.01 )){
            	return L('USER_MONEY_DEFICIT');
		  	 }
    	  }else{
    	  	return L('INVALID_USER_ID');
    	  }
		}

		if (intval($currency_id) == 0){
			$currency_id = $order_vo['currency_id'];
		}
		$currency = M( "Currency" )->getById(intval($currency_id));
		
		$cost_payment_fee = 0;
		if ($payment['cost_fee_type'] == 1){
			$cost_payment_fee = $payment['cost_fee'] * $currency['radio'];
		}else{
			$cost_payment_fee = $money * $payment['cost_fee'] / 100 / $currency['radio'];
		}
		
		//添加一收款单
        $OrderIncharge = M("OrderIncharge"); 
		$vo = $OrderIncharge->create();
		$vo['id'] = null;
		$vo['order_id'] = $order_vo['id'];
		$vo['cost_payment_fee'] = $cost_payment_fee;
		$vo['currency_id'] = $currency_id;
		$vo['currency_radio'] = $currency['radio'];
		$vo['money'] = $money * $currency['radio'];
		$vo['create_time'] = gmtTime();
		$vo['memo'] = L('ORDER_ONLINE_PAY').':'.$money;
		$vo['payment_id'] = $payment_id;
			   
	    $id = $OrderIncharge->add($vo);		
		
	    inc_order_incharge($id);
	    
	    return true;
    }
    
	//增加已收金额
	function inc_order_incharge($order_incharge_id){
		
		$incharge_vo = M("OrderIncharge")->getById ( $order_incharge_id );
		
		$model = M("Order");
		$order_vo = $model->getById ( $incharge_vo['order_id'] );
		$order_vo['order_incharge'] = $order_vo['order_incharge'] + $incharge_vo['money'];

		
		$payment = M( "Payment" )->getById($incharge_vo['payment_id']);
		if ($payment['class_name'] == 'Accountpay' && $order_vo['user_id'] > 0){//会员使用预存款支付，减少预存款
			//记录会员预存款变化明细
			user_money_log($order_vo['user_id'], $order_incharge_id, 'OrderIncharge', $incharge_vo['money'] * -1, L("ORDER_CHARGE_MEMO_1"));
		} 
		
		
		//会员积明细, 第一次收款时，计算积分 注：收款以后 $order_vo["money_status"] 的值都会大小0
		if ($order_vo['user_id'] > 0 && $order_vo['order_score'] > 0 && $order_vo["money_status"] == 0){
				if ($order_vo['order_score'] > 0){
					$Remark = L("ORDER_SCORE_MEMO_1").'('.$order_vo['sn'].')';//订单获得积分
				}else if($order_vo['order_score'] < 0){
					$Remark = L("ORDER_SCORE_MEMO_2").'('.$order_vo['sn'].')';//订单消费积分
				}		
						
				$sql_str = 'insert into '.C("DB_PREFIX").'user_score_log(user_id, create_time, score, memo) values('.
					$order_vo['user_id'].','.
					gmtTime().','.
					$order_vo['order_score'].','.
					'\''.$Remark.'\''.  
					')';
				$model->execute($sql_str);	

			//增加会员积分
			$sql_str = 'update '.C("DB_PREFIX").'user set score = score + '.$order_vo['order_score'].' where id = '.$order_vo['user_id'];
			$model->execute($sql_str);				
		} 		
		
		//已收金额 > 订单总金额
		//收款状态：0:未收款; 1:部分收款; 2:全部收款; 3:部分退款; 4:全部退款
		if ($order_vo["order_incharge"] <= 0){
			$order_vo["money_status"] = 0;
		}else if(abs($order_vo["order_incharge"] - $order_vo['order_total_price']) < 0.01){
			$order_vo["money_status"] = 2;			
		}else if($order_vo["order_incharge"] < $order_vo['order_total_price']){
			$order_vo["money_status"] = 1;
		}else if($order_vo["order_incharge"] >= $order_vo['order_total_price']){
			$order_vo["money_status"] = 2;
		}
		//取款手续费
		$order_vo["cost_payment_fee"] = floatval($order_vo["cost_payment_fee"]) + $incharge_vo['cost_payment_fee'];
		
		$model->save($order_vo);
	}  
	
	
		
	//已发货数量 统计
	function order_send_num($order_id) {	
		$sql_str = 'UPDATE  '.C("DB_PREFIX").'ORDER_GOODS AS A'.
					'   SET A.SEND_NUMBER = IFNULL((SELECT SUM(B.NUMBER)'.
					'                       FROM  '.C("DB_PREFIX").'ORDER_CONSIGNMENT_GOODS AS B'.
					'                      WHERE B.ORDER_GOODS_ID = A.ID),0) -'.
					'                    IFNULL((SELECT SUM(B.NUMBER)'.
					'                       FROM  '.C("DB_PREFIX").'ORDER_RE_CONSIGNMENT_GOODS AS B'.
					'                      WHERE B.ORDER_GOODS_ID = A.ID),0)'.
					' WHERE A.ORDER_ID = '.$order_id;
		//dump($sql_str);
		$Model = new Model();
		$Model->execute($sql_str);							 
	}

	//减库存
	function order_dec_stock($order_consignment_id) {	

		$sql_str =	'UPDATE '.C("DB_PREFIX").'GOODS_SPEC_ITEM G'.
					'   SET G.STOCK = G.STOCK - IFNULL('.
					'                        (SELECT SUM(A.NUMBER)'.
					'                           FROM '.C("DB_PREFIX").'ORDER_CONSIGNMENT_GOODS A'.
					'                           LEFT OUTER JOIN '.C("DB_PREFIX").'ORDER_GOODS B ON B.ID = A.ORDER_GOODS_ID'.
					'                          WHERE G.ID = B.rec_id'.
					'                            AND A.ORDER_CONSIGNMENT_ID = '.$order_consignment_id.'), 0)'.
					' WHERE G.ID IN'.
					'       (SELECT B.rec_id'.
					'          FROM '.C("DB_PREFIX").'ORDER_CONSIGNMENT_GOODS A'.
					'          LEFT OUTER JOIN '.C("DB_PREFIX").'ORDER_GOODS B ON B.ID = A.ORDER_GOODS_ID'.
					'         WHERE A.ORDER_CONSIGNMENT_ID = '.$order_consignment_id.')';
		$Model = new Model();
		$Model->execute($sql_str);		
	}		

	//增加库存
	function order_inc_stock($order_re_consignment_id) {	
		$sql_str =	'UPDATE '.C("DB_PREFIX").'GOODS_SPEC_ITEM G'.
					'   SET G.STOCK = G.STOCK + IFNULL('.
					'                        (SELECT SUM(A.NUMBER)'.
					'                           FROM '.C("DB_PREFIX").'ORDER_RE_CONSIGNMENT_GOODS A'.
					'                           LEFT OUTER JOIN '.C("DB_PREFIX").'ORDER_GOODS B ON B.ID = A.ORDER_GOODS_ID'.
					'                          WHERE G.ID = B.rec_id'.
					'                            AND A.ORDER_RE_CONSIGNMENT_ID = '.$order_re_consignment_id.'), 0)'.
					' WHERE G.ID IN'.
					'       (SELECT B.rec_id'.
					'          FROM '.C("DB_PREFIX").'ORDER_RE_CONSIGNMENT_GOODS A'.
					'          LEFT OUTER JOIN '.C("DB_PREFIX").'ORDER_GOODS B ON B.ID = A.ORDER_GOODS_ID'.
					'         WHERE A.ORDER_RE_CONSIGNMENT_ID = '.$order_re_consignment_id.')';
		//dump($sql_str);
		$Model = new Model();
		$Model->execute($sql_str);		
	}
	
	
	/**
	 * 生成优惠卡号
	 *
	 * @param integer $id sunnyi_promote_card.id
	 * @return string
	 */	
	function buildCard($id){
		$tmp = String::keyGen();
		$tmp = substr($tmp, 0, 16 - strlen($id)).$id;
		return $tmp;
	}

	function formatMoney($money,$currency_id)
	{
		$currency = D("Currency")->where("id=".$currency_id)->find();
		if(!$currency) 
			$currency_radio = 1;
		else
			$currency_radio = $currency['radio'];
		$money = number_format($money * $currency_radio,2);
		return $currency['unit']." ".$money;
	}
?>