<?php
/**
 * Copy Right IJH.CC
 * Each engineer has a duty to keep the code elegant
 * $Id$
 */

class Ctl_Trade_Payment extends Ctl
{
    
    public function __construct(&$system)
    {
        parent::__construct($system);
        $uri = $this->request['uri'];
        if(preg_match('/(return|notify)-(\w+)\.html/i', $uri, $match)){
            $system->request['act'] = $match[1].'_verify';
            $system->request['args'] = array($match[2]);
        }
    }

    public function return_verify($code)
    {
        $forward = $this->mklink('member/index');
        if($obj = K::M('trade/payment')->loadPayment($code)){
            if($trade = $obj->return_verify()){
                if(!$log = K::M('payment/log')->log_by_no($trade['trade_no'])){
                    $this->msgbox->add('支付的订单不存在', 211);
                }else if(K::M('payment/log')->set_payed($trade['trade_no'])){
                    if($log['from'] == 'money'){ //余额充值
                        K::M('trade/payment')->payed_money($log, $trade);
                        $this->msgbox->add('充值余额成功');                        
                    }else{ //订单支付
                        K::M('trade/payment')->payed_order($log, $trade);
                        $this->pagedata['order'] = K::M('trade/order')->detail($log['order_id']);
                        $this->msgbox->add('支付订单成功');                      
                        $forward = $this->mklink('mobile/order:detail', array($trade['trade_no']));
                    }
                }else{
                    if($log['from'] == 'money'){
                        $this->msgbox->add('已经充值成功，请不要重复提交', 214);
                    }else{
                        $this->msgbox->add('该订单已经支付过了', 213);
                    }
                }
            }else{
                $this->msgbox->add('支付验证签名失败', 215);
            }
            $this->msgbox->set_data('forward', $forward);
        }
    }

    public function notify_verify($code)
    {
        $success = false;
        if($obj = K::M('trade/payment')->loadPayment($code)){
            if($trade = $obj->notify_verify()){
                if(!$log = K::M('payment/log')->log_by_no($trade['trade_no'])){
                    $this->msgbox->add('支付的订单不存在', 211);
                }else if(K::M('payment/log')->set_payed($trade['trade_no'])){
                    if($log['from'] == 'money'){ //金币充值
                        if(K::M('trade/payment')->payed_money($log, $trade)){
                            $success = true;                           
                        }
                    }else{
                        if(K::M('trade/payment')->payed_order($log, $trade)){
                            $success = true;
                        }
                    }
                }
            }
            $obj->notify_success($success);
        }
    }

    public function order($code=null, $from=null, $order_id=null)
    {
        if(!($order_id = (int)$order_id) && !($order_id = intval($this->GP('order_id')))){
            $this->msgbox->add('错误', 210);
        }else if(empty($code) && !($code = $this->GP('code'))){
            $this->msgbox->add('错误', 210);
        }else if(empty($from) && !($from = $this->GP('from'))){
            $this->msgbox->add('错误', 210);
        }else if($this->check_login()){
            if(!$mdlorder = K::M('trade/order')->loadmodel($from)){
                $this->msgbox->add('订单来源不正确', 211);
            }else if(!$order = $mdlorder->detail($order_id)){
                $this->msgbox->add('您的订单不存在或已经删除', 211);
            }else if($order['order_status'] < 0){
                $this->msgbox->add('订单已经取消不可支付', 218);
            }else if($order['order_status'] == 3){
                $this->msgbox->add('订单已经完成不可支付', 213);
            }else if($order['order_status'] == 0){
                $this->msgbox->add('订单正在审核不可支付', 210);
            }else if($order['pay_status'] == 1){
                $this->msgbox->add('该订单已经支付过了,不需要重复支付', 211);
            }else if(!in_array($order['order_status'], array(1,2))){
                $this->msgbox->add('订单不可支付', 212);
            }else if(floatval($order['amount'])<=0){
                $this->msgbox->add('订单金额无需支付', 000);
            }else{    
                $amount = $order['amount'];          
                if($code == 'money'){                     
                    //使用余额支付

                    if($this->MEMBER['money'] < $order['amount']){
                        $this->msgbox->add('账户余额不足！',555);
                    }else if(K::M('member/member')->update_money($this->uid, -$amount, '支付订单('.$from.':'.$order_id.')')){
                        //if(K::M('member/member')->update_money($this->uid, -$amount)){
                            //$mdlorder->set_payed($order['order_id']);
                        //}
                        
                        $data2 = array(
                            'order_status'=> 2,
                            'pay_status'=>1,
                            'pay_time'=>time(),
                            'code'=>'money'
                        );
                        $up2 = K::M('xiche/order') -> update($order['order_id'],$data2);  
                        
                       //进行记录更新
                        $order_log_data = array(
                            'order_id'=>$order['order_id'],
                            'tips'=>'订单使用余额支付成功，订单完成',
                            'money'=>$oprice
                        );
                        $log = K::M('order/log') -> create($order_log_data);                       
                         //更新模版消息
                        $u = K::M('member/member')->detail($order['uid']);
                        K::M('system/logs')->log('payment',json_encode(array('u'=>$u)));
                        $order_url = K::M('helper/link')->mklink($from.'/order:detail', array($order_id), null, 'www');
                        if ($u['wx_openid']) {
                            //获取模版消息配置                            
                            $wx_config = $this->system->config->get('wx_config');
                            $config = $this->system->config->get('site');
                            $a = array('title'=>'恭喜您！订单支付成功！订单完成！', 'items' => array('OrderSn' => $order['order_id'], 'OrderStatus' => '订单支付成功'), 'remark' =>'恭喜,您的订单于'.date('Y-m-d H:i:s',time()).'支付成功，订单交易完成！');;
                            K::M('weixin/wechat')->wechat_client($config)->sendTempMsg($u['wx_openid'], $wx_config['order_id'], $url, $a);
                            $b = array('title'=>'编号：#'.$order['order_id'].'订单支付成功！余额减少'.$oprice, 'items' => array('keyword1' => '普通会员', 'keyword2' => '订单支付','keyword3' => '余额减少'.$oprice,'keyword4' =>$oprice,'keyword5' => $money), 'remark' =>'恭喜,您的账户于'.date('Y-m-d H:i:s',time()).'支付订单成功！');
                            K::M('weixin/wechat')->wechat_client($config)->sendTempMsg($u['wx_openid'], $wx_config['money_id'], $order_url, $b);
                        }
                        $this->msgbox->add('支付成功');
                        $this->msgbox->set_data('forward', $order_url);
                    }
                }else{
                    if($url = K::M('trade/payment')->order($code, $from, $order)){
						if(!defined('IN_WEIXIN') && strpos($url['url'], 'wxpay')){
							$qrurl = $this->mklink('trade/payment:wxqrcode', array(), array('codeurl'=>$url, 'amount'=>$amount,'order_no'=>$log['trade_no']));
							header("Location:{$qrurl}");
						}else{
							header("Location:{$url}");
						}                       
                    }else{
                        $this->msgbox->add('订单支付请求失败', 233);
                    }                    
                }             
            }
        }
    }

    public function money($code=null,$amount=null)
    {
        $code = $this->GP('code');
        $amount = $this->GP('amount');
        if(!$code){
            $this->msgbox->add('没有选择支付方式',212);            
        }else if(empty($amount)){
            $this->msgbox->add('付款金额不合法', 211);
        }else if($this->check_login()){
            if($url = K::M('trade/payment')->money($this->uid, $code, $amount)){
                if(!defined('IN_WEIXIN') && strpos($url['url'], 'wxpay')){
                    $qrurl = $this->mklink('trade/payment:wxqrcode', array(), array('codeurl'=>$url, 'amount'=>$amount,'order_no'=>$log['trade_no']));
                    header("Location:{$qrurl}");
                }else{
                    $url = $url['url'];
                    header("Location:{$url}");
                }
            }else{
                echo 3333;die; //订单号重复等原因
            }
        }
    }

    public function get_payed($from=null,$order_id=null)
	{
        $from = $this->GP('from');
        $order_id = $this->GP('order_id');
        if(!$from || !$order_id){
            $this->ajaxReturn(array('status'=>'error'));
        }else if($from != 'order' && $from != 'money'){
            $this->ajaxReturn(array('status'=>'error'));
        }
  
        $uid = $this->MEMBER['uid'];
        $r = K::M('payment/log') -> find(array('uid'=>$uid,'payment'=>'wxpay','from'=>$from,'trade_no'=>$order_id),array('log_id'=>'desc'));
        
        if($r){
            if($r['payed'] == 1){
                $this->ajaxReturn(array('status'=>'success','payed'=>1));
            }else{
                $this->ajaxReturn(array('status'=>'error'));
            }
        }else{
            $this->ajaxReturn(array('status'=>'error'));
        }
        
    }
    
    public function wxqrcode()
    {

        if(!$codeurl = $this->GP('codeurl')){
            exit('params error');
        }
        if(!$amount = $this->GP('amount')){
            exit('params error');
        }
		if(!$order_no = $codeurl['trade_no']){
            exit('params error');
        }
        $amount = sprintf("%.2f", $amount);
        $this->pagedata['codeurl'] = $codeurl;
        $this->pagedata['amount'] = $amount;
		$this->pagedata['order_no'] = $order_no;
        $this->tmpl = 'trade/payment/wxqrcode.html';
    }

    public function redirect($trade_no)
    {
        $url = K::M('helper/link')->mklink('mobile/member:index', null, null, 'base');
        if($log = K::M('payment/log')->log_by_no($trade_no)){
            if($log['from'] == 'order'){
                $url = K::M('helper/link')->mklink('mobile/order:detail', array($trade_no), array(), 'base');
            }
        }
        header("Location:{$url}");
        exit;
    }    
    
}