<?php
/**
 * 后台基础控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <570035208@qq.cn>
 */

namespace Home\Controller;
class PayController extends BaseController{
	public function _initialize(){
		parent::_initialize();
    }
    public function index() {
		$id = I('id');
        $map['id']=$id;
        $map['is_paid']=array('neq',1);
		$order_info=M("PayLog")->where($map)->field(true)->find();
        if($order_info && $order_info['payment_id']){
            $p_map['id']=$order_info['payment_id'];
            $payment_info=M("Payment")->where($p_map)->field(true)->find();
            $this->assign('payment_info',$payment_info);
        }else{
            $this->error("支付信息错误");
        }

		$this->assign('pay_title','立即支付');
		$this->assign($order_info);
        $this->display();
    }
	public function go_buy(){
		$id=I('id');//if(empty($id))$id=cookie('logmobpay');
        if(empty($id)){
            $requrl=$_SERVER['PATH_INFO']?$_SERVER['PATH_INFO']:$_SERVER['REQUEST_URI'];
            $reqarr=explode('/',str_replace('.html','',$requrl));
            $id=intval($reqarr[(count($reqarr)-1)]);
        }
		//print_r($_SERVER);exit;
        if(empty($id))$this->error('参数错误');
		$where['id']=$id;
        $where['is_paid']=array('neq',1);
		$pay_info = M('PayLog')->where($where)->field(true)->find();
		$title_name=I('get.title');if(empty($title_name))$title_name="支付";
		$pay_code = $pay_info['pay_code'];
        $p_map['status']=1;
        $p_map['code']=$pay_code;
		$payconfig=M('Payment')->where($p_map)->field(true)->find();
		if(empty($pay_code))$this->error('请选择支付方式');
		$pay = new \Common\Vendor\Pay($pay_code,$payconfig);
		$vo = new \Common\Vendor\Pay\PayVo();
        $user_id=get_openid();

		$vo->setBody($title_name)
				->setFee($pay_info['need_pay'])
				->setTitle($title_name)
				->setOrderNo($pay_info['order_sn'])
				->setParam($pay_info)
				->setProduct_id($id)
				->setUserOpenid($user_id);
		$RequestForm=$pay->buildRequestForm($vo);
        $display=false;
		if(str_exists($pay_code,'Hanchao')){
			$this->assign('before_title','在线支付');
			$display=true;
		}
		if(in_array($pay_code,array('weixincode'))){
			$this->assign('before_title','微信扫码支付');
            $display=true;
		}
        if($display){
            $payarr['order']=$id;
            $payarr['pay_code']=$pay_code;
			$payarr['payment']=idtoname($pay_code,'Payment','name','code');
			$payarr['content']=$RequestForm;
			$this->assign('pay',$payarr);
			$tpl=is_mobile()?'Mobile@Member:mobile':'';
			$this->display($tpl);exit;
        }
		echo $RequestForm;
	}
	/*支付结果返回*/
    public function notify() {
        $apitype = I('get.apitype');
        $config=idtoname($apitype,'Payment','*','code');
        // file_put_contents('uploads/PAY-cc'.I('get.method').date("YmdHis").'.txt',var_export($config,true));
        $pay = new \Common\Vendor\Pay($apitype,$config);
        if(in_array(strtolower($apitype),array('weixinpay','weixincode','weixinsmall','weixinapppay'))){
            $notify = file_get_contents("php://input");
        }elseif(in_array(strtolower($apitype),array('alipayapi','mmscan','chinaums'))){
            $notify = $_POST;
        }elseif (IS_POST && !empty($_POST)) {
            $notify = I('post.');
        } elseif (IS_GET && !empty($_GET)) {
            $notify = I('get.');
            unset($notify['method']);
            unset($notify['apitype']);
        } else {
            $this->error("支付失败！(参数错误)");exit;
        }
        //file_put_contents('uploads/PAY-pm'.I('get.method').date("YmdHis").'.txt',var_export($notify,true));
		//手机支付宝的跳转
		if (I('get.method') == "return" && strtolower($apitype)=='alipayapi' && I('param.result')=='success'){
			if(is_mobile()){
				$this->success("支付成功！",U("Mobile/Member/index"));exit;
			}
		}elseif(I('get.method') == "return" && strtolower($apitype)=='alipayapi' && I('param.result')!='success'){
			if(is_mobile()){
				$this->error("支付失败！",U("Mobile/Member/index"));exit;
			}
		}
        //验证
        if ($pay->verifyNotify($notify)) {
            //获取订单信息
            $info = $pay->getInfo();
            if ($info['status']) {
				D('Common/OrderInfo')->endorder($info);
                if (I('get.method') == "return") {
                    $map=array();
                    $map['order_sn']=$info['out_trade_no'];
                    $type=M('OrderInfo')->where($map)->getField('type');
                    if(is_mobile() && $type==11){
                        $this->success("支付成功！",U("Mobile/OrderInfo/service_order"));
                    }elseif(is_mobile() && $type==10){
                        $this->success("支付成功！",U("Mobile/PurOrderInfo/index"));
                    }elseif(!is_mobile() && $type==5){
                        $this->success("充值成功！",U("Shop/account/accountlog"));
                    }elseif(!is_mobile() && $type==10){
                        $this->success("支付成功！",U("Shop/PurOrder/PurIndex"));
                    }else{
                        $this->success("支付成功！",U("Mobile/OrderInfo/index"));
                    }
                } else {
                    $pay->notifySuccess();
                }
            } else {
                $this->error("支付失败！");
            }
        } else {
            $this->error("支付失败！(验签错误)");
        }
    }
    //退款回调
    public function refund_notify(){
        
        if (IS_POST && !empty($_POST)) {
            $notify = I('post.');
        } elseif (IS_GET && !empty($_GET)) {
            $notify = I('get.');
        } else {
            $notify = file_get_contents("php://input");
        }
        if(empty($notify)){
            $this->error("退款失败！");exit;
        }
        // file_put_contents('uploads/PAY-n'.date("YmdHis").'info.txt',var_export($notify,true));
        $status =0;

        if($notify['success_num'] > 0){
            $refund_sn = $notify['batch_no'];
            $status = 1;
            $payment_refund = idtoname($refund_sn,'PaymentRefund','*','refund_sn');
            D('Common/OrderInfo')->payment_refund($refund_sn,$status,$notify['notify_time']);

            $payconfig = idtoname($payment_refund['payment_code'],'Payment','*','code');
            $pay = new \Common\Vendor\Pay($payment_refund['payment_code'],$payconfig);
            if ($pay->verifyNotifys($notify)) {
                $info['status'] = true;
                $info['money'] = $payment_refund['money'];
                $info['out_trade_no'] = $payment_refund['order_id'];
                $info['pay_sn'] = $payment_refund['trade_no'];
                D('Common/OrderInfo')->refund_order($info);
            }
        }else{
            $this->error("退款失败！");exit;
        }

      
      
        
    }
}