<?php
namespace Mobile\Controller;
use Think\Controller;
use Common\Api\GameApi;
use Org\WeixinSDK\Weixin;
use Org\SwiftpassSDK\Swiftpass;
use Org\GoldPig\GoldPig;
use User\Api\SuserApi;


class PayController extends BaseController{

	const ALI_PAY = 1;          //支付宝支付
    const WEIXIN_PAY =2;        //微信支付
	const GOLDPIG_PAY =8;        //金猪支付

	const PLATFORM_COIN = 1;        //平台币
	const BIND_PLATFORM_COIN = 2;   //绑定平台币


    private function pay($table,$prefix,$param){
        $out_trade_no = $prefix.date('Ymd').date('His').sp_random_string(4);
        $user = get_user_entity($param['user_id']);
        switch ($param['apitype']) {
            case 'swiftpass':
                $pay  = new \Think\Pay($param['apitype'],$param['config']);
                break;

            default:
                $pay  = new \Think\Pay($param['apitype'],C($param['config']));
                break;
        }
        $vo   = new \Think\Pay\PayVo();
        $vo ->setFee($param['real_pay_amount'])//支付金额
	        ->setMoney($param['pay_amount'])
            ->setTitle($param['title'])
            ->setBody($param['body'])
            ->setOrderNo($out_trade_no)
            ->setService($param['server'])
            ->setSignType($param['signtype'])
            ->setPayMethod("wap")
            ->setTable($table)
            ->setPayWay($param['payway'])
            ->setGameId($param['game_id'])
            ->setGameName($param['game_name'])
            ->setGameAppid($param['game_appid'])
            ->setServerId(0)
            ->setServerName("")
            ->setUserId($param['user_id'])
            ->setAccount($user['account'])
            ->setUserNickName($user['nickname'])
            ->setPromoteId($param['promote_id'])
            ->setPromoteName(get_promote_name($param['promote_id']))
            ->setExtend($param['extend'])
	        ->setDiscount($param['discount'])
            ->setSdkVersion($param['sdk_version']);
        return $pay->buildRequestForm($vo);
    }

	/**
	 * APP充值
	 * @param $token
	 * @param $pay_amount   金额
	 * @param $good_info    商品信息(json数组:type 1平台币 2绑币 game_id 游戏ID)
	 * @param $pay_way      1 支付宝 2微信
	 * author: xmy 280564871@qq.com
	 */
    public function recharge($pay_amount,$good_info,$pay_way,$promote_id){
	    $good_info = json_decode($good_info,true);
	    $good['user_id'] = $good_info['user_id'];

	    if($pay_amount<0) {
            $this->error("金额不正确");
        }
	    $pay_amount = abs($pay_amount);

    	switch ($good_info['type']){
		    case self::PLATFORM_COIN:
		    	$table = "deposit";
		    	$prefix = "PF_";
			    $good['real_pay_amount'] = $pay_amount;
			    $good['title'] = "平台币";
			    $good['body'] = "平台币充值";
		    	break;
		    case self::BIND_PLATFORM_COIN:
		    	$table = "bind_recharge";
		    	$prefix = "BR_";
		    	$game_id = $good_info['game_id'];
			    $game = M("Game","tab_")->find($game_id);
			    if(empty($game)){
			    	$this->error("游戏不存在");
			    }
			    $discount = empty($game['bind_recharge_discount']) ? 10 : $game['bind_recharge_discount'];
			    $real_pay_amount = round($pay_amount * $discount / 10,2);
			    //构建商品信息
			    $good['title'] = "绑定平台币";
			    $good['body']  = "绑定平台币充值";
			    $good['game_id']    = $game_id;
			    $good['game_name']  = $game['game_name'];
			    $good['game_appid'] = $game['game_appid'];
			    $good['real_pay_amount'] = $real_pay_amount;
			    $good['discount'] = $discount;
			    break;
		    default:
		    	$this->error("商品信息错误");
	    }
	    $good['pay_amount'] = $pay_amount;
    	$good['promote_id'] = $promote_id;
    	switch ($pay_way){
		    case self::ALI_PAY :
			    $result = $this->alipay_pay($good,$table,$prefix);
			    break;
		    case self::WEIXIN_PAY:
		    	$result = $this->weixin_pay($good,$table,$prefix);
		    	break;

		    default:$this->error("暂无该支付选项");
	    }
	    return $result;
    }

		/**
		 * 购买商品并支付
		 * @param $token
		 * @param $pay_amount   金额
		 * @param $good_info    商品信息
		 * @param $pay_way      1 支付宝 2微信
		 * @author 鹿文学
		 */
		public function buy($pay_amount,$good_info,$pay_way,$promote_id) {
			$good = json_decode($good_info,true);

            if($pay_amount<0) {
                $this->error("金额不正确");
            }
            $pay_amount = abs($pay_amount);

			switch($good['type']) {
				case 'small':{
					$table = 'order';
					$good['real_pay_amount'] = $pay_amount;
					$good['title'] = "购买商品";
					$good['body'] = "购买商品支付";
					$prefix = 'SI_';
				};break;
				default:
		    	$this->error("商品信息错误");
			}
			$good['pay_amount'] = $pay_amount;
			switch ($pay_way){
		    case self::ALI_PAY :
			    $result = $this->alipay_pay($good,$table,$prefix,'buy_pay');
			    break;
		    case self::WEIXIN_PAY:
		    	$result = $this->weixin_pay($good,$table,$prefix,'buy_pay');
		    	break;

		    default:$this->error("暂无该支付选项");
	    }

			return $result;
		}

		private function buy_pay($table,$prefix,$param){
				$da = M('Order','tab_')->where(['merchandise_id'=>$param['id'],'buyer_id'=>$param['user_id']])->find();
				if(is_array($da)) {
					M('Order','tab_')->where(['merchandise_id'=>$param['id'],'buyer_id'=>$param['user_id']])->save(['order_time'=>time()]);
					$out_trade_no = $da['order_number'];
				} else {
        $out_trade_no = $prefix.date('Ymd').date('His').sp_random_string(4);
				}
        $user = get_user_entity($param['user_id']);
        switch ($param['apitype']) {
            case 'swiftpass':
                $pay  = new \Think\Pay($param['apitype'],$param['config']);
                break;

            default:
                $pay  = new \Think\Pay($param['apitype'],C($param['config']));
                break;
        }
        $vo   = new \Think\Pay\PayVo();
        $vo ->setFee($param['real_pay_amount'])//支付金额
						->setMoney($param['real'])
            ->setTitle($param['title'])
            ->setBody($param['body'])
            ->setOrderNo($out_trade_no)
            ->setService($param['server'])
            ->setSignType($param['signtype'])
            ->setPayMethod("trade")
            ->setTable($table)
            ->setPayWay($param['payway'])
            ->setBuyerId($param['user_id'])
            ->setBuyerAccount($user['account'])
						->setSellerId($param['seller_id'])
						->setSellerAccount($param['seller_account'])
						->setSmallId($param['small_id'])
						->setSmallAccount($param['small_account'])
						->setParam($param['id'])
						->setGameId($param['game_id'])
						->setPoundage($param['poundage']);

        return $pay->buildRequestForm($vo);
    }


    /**
    *支付宝移动支付
    */
    private function alipay_pay($param,$table,$prefix,$pway=''){
        $param['apitype'] = "alipay";
	    $param['config']  = "alipay";
	    $param['signtype']= "MD5";
	    $param['server']  = "alipay.wap.create.direct.pay.by.user";//mobile.securitypay.pay
	    $param['payway']  = 1;
	    $param['user_id'] = $param['user_id'];
			if($pway=='buy_pay') {
			$data = $this->buy_pay($table,$prefix,$param);
			} else {
	    $data = $this->pay($table,$prefix,$param);
			}

	    $resultData = array('pay_way'=>'alipay',"status"=>1,"url"=>$data);
	    return $resultData;
    }

    /**
    *微信支付
    */
	private function weixin_pay($param, $table, $prefix,$pway='')
	{
		$da = M('Order','tab_')->where(['merchandise_id'=>$param['id'],'buyer_id'=>$param['user_id']])->find();
		if (get_wx_type() == 0) {//官方
			if(is_array($da)) {
				M('Order','tab_')->where(['merchandise_id'=>$param['id'],'buyer_id'=>$param['user_id']])->save(['order_time'=>time()]);
				$param['pay_order_number'] = $da['order_number'];
			} else {
			$param['pay_order_number'] = $prefix . date('Ymd') . date('His') . sp_random_string(4);
			}

			$param['pay_way'] = 3;
			$param['pay_status'] = 0;
			$param['spend_ip'] = get_client_ip();
			$weixn = new Weixin();
			$is_pay = json_decode($weixn->weixin_pay($param['title'], $param['pay_order_number'], $param['real_pay_amount'], 'MWEB'), true);

			if ($is_pay['status'] === 1) {
				switch ($table){
					case 'deposit':
						$this->add_deposit($param);
						break;
					case "bind_recharge":
						$this->add_bind_recharge($param);
						break;
					case 'order':
						$this->add_order($param);
						break;
				}
				if($table == 'order'){
                    $is_pay['mweb_url'] = $is_pay['mweb_url'].'&redirect_url='.(is_ssl()?'https%3A%2F%2F':'http%3A%2F%2F'). $_SERVER ['HTTP_HOST']."%2Fmobile.php%2FTrade%2Fsuccess%2Fout_trade_no%2F".$param['pay_order_number'];
                    if(session('order_scheme')){
                        $is_pay['mweb_url'] .= "/scheme%2F".session('order_scheme');
                    }
                }
				$json_data = array('pay_way'=>'weixin',"status"=>1,"url"=>$is_pay['mweb_url']);
			}else{
				$json_data = array('pay_way'=>'weixin',"status"=>0,"info"=>'失败');
			}
			return $json_data;
		} else {
				$Swiftpass=new Swiftpass(C('weixin_gf.partner'),C('weixin_gf.key'));
				$param['service']="pay.weixin.wappay";
				$param['ip']=  get_client_ip();
				$param['pay_amount']=$param['real_pay_amount'];//;
				if(is_array($da)) {
					$param['out_trade_no'] = $da['order_number'];
				} else {
					$param['out_trade_no']= $prefix . date('Ymd') . date('His') . sp_random_string(4);
				}
				//file_put_contents(dirname(__FILE__). '/wxswiftpass.txt',json_encode($param));
			if('buy_pay'==$pway) {
            $param['body']='购买商品支付';
            $param['callback_url']='http://' . $_SERVER ['HTTP_HOST'] . "/mobile.php/Trade/success/out_trade_no/".$param['out_trade_no'];
            $url=$Swiftpass->submitOrderInfo($param);
            if($url['status']==0){
              $request['pay_way'] = 4;
                $this->add_order($param);
                $json_data = array('pay_way'=>'weixin',"status"=>1,"url"=>$url['pay_info']);
            }else{
                $json_data = array('pay_way'=>'weixin',"status"=>0,"info"=>$url['msg']);
            }
            return $json_data;

			} else {
            $param['body']="游戏充值";
            $param['callback_url']='http://' . $_SERVER ['HTTP_HOST'] . "/mobile.php/User/recharge";
            $url=$Swiftpass->submitOrderInfo($param);
            if($url['status']==0){
              $request['pay_way'] = 4;
                if($request['code']==1){
                    $this->add_spend($param);
                }else{
                    $this->add_deposit($param);
                }
                $json_data = array('pay_way'=>'weixin',"status"=>1,"url"=>$url['pay_info']);
            }else{
                $json_data = array('pay_way'=>'weixin',"status"=>0,"info"=>$url['msg']);
            }
            return $json_data;
			}
		}
	}

    /**
     * 金猪支付
     * @return [type] [description]
     * @author cb <[email address]>
     */
    public function goldpig(){

            if(!$this->islogin()){$this->redirect('Mobile/User/login');}$member = new SuserApi;
            $user_id = get_user_id($_REQUEST['account']);
            if($user_id!=$member->login_info('user_id')){
                $this->error('只能给自己充值');
            }
            if($user_id == 0){$this->error('账号不存在');}

            $pay_amount = $_POST['pay_amount'];
            if($pay_amount<1) {
                $this->error('金额不正确');
            }
            $pay_amount=abs($pay_amount);

            if($_REQUEST['spendType'] == 2){
                $userMap['user_id'] = $user_id;
                $userMap['game_id'] = $_REQUEST['game_id'];
                $empty = M('UserPlay','tab_')->where($userMap)->find();
                if(empty($empty)){
                    $this->error('该用户未玩过此游戏哦~');
                }
            }
            $data['user_id']=$user_id;
            switch ($_POST['spendType']){
                case '1':
                    $data['real_pay_amount'] = $pay_amount;
                    $data['prefix'] = "PF_";
                    break;
                case '2':
                    $data['prefix'] = "BR_";
                    $game_id = $_POST['game_id'];
                    $game = M("Game","tab_")->find($game_id);
                    if(empty($game)){
                        $this->error("游戏不存在");
                    }
                    $discount = empty($game['bind_recharge_discount']) ? 10 : $game['bind_recharge_discount'];
                    $real_pay_amount = round($pay_amount * $discount / 10,2);
                    //构建商品信息
                    $data['game_id']    = $game_id;
                    $data['game_name']  = $game['game_name'];
                    $data['game_appid'] = $game['game_appid'];
                    $data['real_pay_amount'] = $real_pay_amount;
                    break;
                default:
                    $this->error("信息错误");
            }
            $data['pay_amount'] = $pay_amount;

            $this->assign('data',$data);
            $this->display();

    }


    /**
     * 金猪支付
     * @return [type] [description]
     * @author cb <[email address]>
     */

     public function goldpig_pay(){


$member = new SuserApi;

        $user = get_user_entity($member->login_info('user_id'));
        $data['user_id'] = $user['id'];
        $data['promote_id'] = $user['promote_id'];

        $pay_amount = $_POST['amount'];
        $amount = $_POST['amount'];
        if($pay_amount<1 || $amount< 1) {
            $this->error('支付金额错误!');
        }
        $pay_amount = abs($pay_amount);

        switch ($_POST['prefix']){
            case 'PF_':
                $table = "deposit";
                $prefix = "PF_";
                $data['real_pay_amount'] = $pay_amount;
                $data['title'] = "平台币";
                $data['body'] = "平台币充值";
                if($amount!==$pay_amount){//验证订单金额
                    $this->error('支付金额错误!');
                }
                break;
            case 'BR_':
                $game_id = $_POST['game_id'];
                $game = M("Game","tab_")->find($game_id);
                $discount = empty($game['bind_recharge_discount']) ? 10 : $game['bind_recharge_discount'];
                $real_pay_amount = $amount;
                //构建商品信息
                $data['title'] = "绑定平台币";
                $data['body']  = "绑定平台币充值";
                $data['game_id']    = $game_id;
                $data['game_name']  = $game['game_name'];
                $data['game_appid'] = $game['game_appid'];
                $data['real_pay_amount'] = $real_pay_amount;
                $data['discount'] = $discount;
                if(round($pay_amount*$discount,1)/10 != $_POST['amount']){//验证订单金额

                    $this->error('支付金额错误!');
                }
                break;
            default:
                $this->error("信息错误");
        }
            $data['pay_amount'] = $pay_amount;
            $data['pay_order_number'] = $_POST['prefix'] . date('Ymd') . date('His') . sp_random_string(4);
            $data['pay_way'] = 8;
            $data['pay_status'] = 0;
            $data['spend_ip'] = get_client_ip();
            switch ($_POST['prefix']){
                case 'PF_':
                    $this->add_deposit($data);
                    break;
                case "BR_":
                    $this->add_bind_recharge($data);
                    break;
            }

            /* $goldpig=new GoldPig();
            $url = $goldpig->GoldPig($user['account'],$data["real_pay_amount"],$_POST["PayID"],$data["pay_order_number"],$_POST["ka_type"],$_POST["mobile"],$_POST["password"]);


            if($url['status']==1){
                redirect($url['msg']);
            }else{
                $this->error('失败');
            } */

						$baseurl = 'http://api.357p.com/?';

						$url = $baseurl . "UserName={$user['account']}&Price={$data['real_pay_amount']}&shouji={$_POST['shouji']}&PayID={$_POST['PayID']}&userid={$_POST['userid']}&wooolID={$_POST['wooolID']}&jinzhua={$data['pay_order_number']}&jinzhub={$_POST['jinzhub']}&jinzhuc={$_POST['jinzhuc']}&jinzhue={$data['pay_order_number']}";

						redirect($url);exit;




    }




    /**
    *支付验证
    */
    public function pay_validation(){
        #获取SDK上POST方式传过来的数据 然后base64解密 然后将json字符串转化成数组
        $request = json_decode(base64_decode(file_get_contents("php://input")),true);
        $out_trade_no = $request['out_trade_no'];
        $pay_where = substr($out_trade_no,0,2);
        $result = 0;
        $map['pay_order_number'] = $out_trade_no;
        switch ($pay_where) {
            case 'SP':
                $data = M('spend','tab_')->field('pay_status')->where($map)->find();
                $result = $data['pay_status'];
                break;
            case 'PF':
                $data = M('deposit','tab_')->field('pay_status')->where($map)->find();
                $result = $data['pay_status'];
                break;
            case 'AG':
                $data = M('agent','tab_')->field('pay_status')->where($map)->find();
                $result = $data['pay_status'];
                break;
            default:
                exit('accident order data');
                break;
        }
        if($result){
            echo base64_encode(json_encode(array("status"=>1,"return_code"=>"success","return_msg"=>"支付成功")));
            exit();
        }else{
            echo base64_encode(json_encode(array("status"=>0,"return_code"=>"fail","return_msg"=>"支付失败")));
            exit();
        }
    }

    /**
    *sdk客户端显示支付
    */
    public function payShow(){
        $map['type'] = 1;
        $map['status'] = 1;
        $data = M("tool","tab_")->where($map)->select();
        if(empty($data)){
            echo base64_encode(json_encode(array("status"=>0,"return_code"=>"fail","return_msg"=>"暂无数据")));
            exit();
        }
        foreach ($data as $key => $value) {
            $pay_show_data[$key]['mark']  = $value['name'];
            $pay_show_data[$key]['title'] = $value['title'];
        }
        echo base64_encode(json_encode(array("status"=>0,"return_code"=>"fail","return_msg"=>"成功","pay_show_data"=>$pay_show_data)));
        exit();
    }



		public function look() {
			$user = D('User')->getLoginInfo();
			$id = $_POST['id'];
			if(is_array($user)) {
				if(is_numeric($id) && $id>0) {

					$order = M('Order','tab_')->field('order_number')->where(['merchandise_id'=>$id,'buyer_id'=>$user['user_id']])->find();
					file_put_contents(dirname(__FILE__) .'/order.txt',json_encode($order));
					$weixn = new Weixin();

					$result = $weixn->weixin_orderquery($order['order_number']);
					file_put_contents(dirname(__FILE__) .'/order2.txt',json_encode($result));
					if($result == $order['order_number']) {
						$this->ajaxReturn(['status'=>1,'info'=>'','url'=>U('Trade/success',array('out_trade_no'=>$order['order_number']))],'json');
					} else {
						$this->ajaxReturn(['status'=>0,'info'=>$result],'json');
					}
				} else {
					$this->ajaxReturn(['status'=>0,'info'=>'参数错误'],'json');
				}
			} else {
				$this->ajaxReturn(['status'=>0,'info'=>'未登录'],'json');
			}

		}


}