<?php
namespace Sdk\Controller;
use Think\Controller;
use Org\Ipa365SDK\Ipa365;
use Mobile\Controller\SsgController;

// a8eeac3335cef5ee117d357738598f691932513b
class Ipa365Controller extends BaseController{
	const signprice = 10;   // 超级签价格
	public $userinfo; 
	
	public function __construct() {
 		$this->userinfo = $_SESSION['onethink_home']['user_auth'];
		parent::__construct();
	}
	
    public function test(){
    	$user = $this->userinfo;
    	pp($user);
    	die();
    	$ipa365 = new Ipa365Controller();
    	$result = $ipa365->pay_notify(array(
    		'trade_id' => "2222",
    		'order_id' => "SS_20190924170241aEYL"
    	));
    	
    	pp($result);
    	
    	die();
    	$userId = 1;
    	$gameId = 1;
    	
    	$param['price'] = 0.01;
    	
    	$param['spend_ip'] = get_client_ip();
    	$param['sdk_version'] = '2';
    	$param['user_id'] = $userId;
    	$param['game_id'] = $gameId;
    	$param['order_id'] = $orderId;
    	$param['apitype'] = "alipay";
    	$param['config']  = "alipay";
    	$param['signtype']= "MD5";
    	$param['server']  = "alipay.wap.create.direct.pay.by.user";
    	$param['payway']  = 1;
    	$param['title'] = $price;
    	$param['body'] = $price;
    	$param['callback'] = "http://www.baidu.com";
    	$param['notifyurl'] = "https://api.wmtxkj.com/callback.php/Notify/sq_callback";
    	$ret = $this->alipay($param);
    	redirect($ret['url']);
    	die;
    	
		/* $ipa365 = new Ipa365();
		$list = $ipa365->ticketList(array(
			'token' => 'Ido9idMgbZlJHMQxjSgTHWZMB00PFEus',
			'limit' => 1,
		));
		
		pp($list['data']['list'][0]);   */
		// 授予udid下载权限并获取下载地址
		$ret = $ipa365->udidRequest(array(
			'token' => 'Ido9idMgbZlJHMQxjSgTHWZMB00PFEus',
			'udid' => 'a8eeac3335cef5ee117d357738598f691932513b',
		));
		pp($ret); 
		$ret = $ipa365->getinfo(array(
			'token' => 'Ido9idMgbZlJHMQxjSgTHWZMB00PFEus',
			'udid' => 'a8eeac3335cef5ee117d357738598f691932513b',
		));
		pp($ret);
    }
    
    public function pay_notify_test() {
    	die();
    	$this->pay_notify(array(
    		'order_id' => 'SS_20190924102317T2jO',
    		'game_id' => 1,
    	));
    }
    
    /**
     * 订单检查
     */
    public function pay_order_check() {
    	
    	$orderId = I('order_id');
    	$order = M('game_supersign', 'tab_')->where(array(
    		'order_id' => $orderId
    	))->find();
    	if (!$order) {
    		echo "订单不存在!";
    	}
    	if ($order['pay_status'] == 1) {
    		redirect(U("Ipa365/install_show", [
    			'game_id' => $order['game_id'],
    			'order_id' => $order['order_id']
    		]));
    	}
    	echo "订单正在处理中.请稍后再试!";
    	exit();
    }
    /*
     * 发起支付
     */
    public function pay() {
    	$userId = $this->userinfo['user_id'];
    	if (!$userId ) {
    		$this->error("请登入", "/mobile.php/ssg/login");
    	}
    	
    	$gameId = I("game_id", 0);
    	$price = self::signprice;
    	
    	if (!$userId || !$gameId) {
    		$this->error("参数有误!");
    	}
    	
    	$payLog = M('game_supersign', 'tab_')->where(array(
    		'user_id' => $userId,
    		'game_id' => $gameId,
    		'pay_status' => 0
    	))->find();
    	if ($payLog) {
    		$orderId = $payLog['order_id'];                                                               
    	} else {
	    	$orderId = "SS_" . date('Ymd') . date('His') . sp_random_string(4); // 超级签
	    	
	    	$gameInfo = M('game', 'tab_')->field('supersign_token')->where(array(
	    		'id' => $gameId,
	    	))->find();
	    	if (!$gameInfo['supersign_token']) {
	    		$this->error("超级签token未填写!");
	    	}
	    	
	    	$r = M('game_supersign', 'tab_')->add(array(
	    		'udid' => '',
	    		'user_id' => $userId,
	    		'game_id' => $gameId,
	    		'order_id' => $orderId,
	    		'pay_price' => $price,
	    		'pay_status' => 0,
	    		'ticket' => '',  // 调用安装的时候分配
	    		'token' => $gameInfo['supersign_token'],
	    		'create_time' => time()
	    	));
	    	if (!$r) return -1;
    	}
    	
    	$param['price'] = $price;
    	$param['sdk_version'] = '2';
    	$param['user_id'] = $userId;
    	$param['game_id'] = $gameId;
    	$param['order_id'] = $orderId;
    	$param['apitype'] = "alipay";
    	$param['config']  = "alipay";
    	$param['signtype']= "MD5";
    	$param['server']  = "alipay.wap.create.direct.pay.by.user";
    	$param['payway']  = 1;
    	$param['title'] = $price;
    	$param['body'] = $price;
    	$param['callback'] = "https://m.wmtxkj.com/sdk.php/Ipa365/install_show/user_id/{$userId}/game_id/{$gameId}/order_id/{$orderId}";
    	$param['notifyurl'] = "https://m.wmtxkj.com/callback.php/Notify/notify/apitype/alipay";
    	
    	$ret = $this->alipay($param);

    	$this->assign("price", self::signprice);
    	$this->assign("url", $ret['url']);
    	$this->assign("order_id", $orderId);
//     	pp($orderId);
//     	redirect($ret['url']);

    	$this->display();
    }
    
    
	// 微信分享页面
    public function paytip(){
    	$userId = $this->userinfo['user_id'];
    	if (!$userId ) {
    		$this->error("请登入", "/mobile.php/ssg/login");
    	}
    	
    	$orderId = I('order_id');
    	
    	$payLog = M('game_supersign', 'tab_')->where(array(
    		'order_id' => $orderId,
    	))->find();
    	
    	$this->assign('url', U('Ipa365/install', array(
    		'order_id' => $payLog['order_id'],
    		'user_id' => $payLog['user_id'],
    		'game_id' => $payLog['game_id'],
    	)));
    	
    	$price = $payLog['pay_price'];
    	$userId = $payLog['user_id'];
    	$gameId = $payLog['game_id'];
    	
    	$param['price'] = $price;
    	$param['sdk_version'] = '2';
    	$param['user_id'] = $userId;
    	$param['game_id'] = $gameId;
    	$param['order_id'] = $orderId;
    	$param['apitype'] = "alipay";
    	$param['config']  = "alipay";
    	$param['signtype']= "MD5";
    	$param['server']  = "alipay.wap.create.direct.pay.by.user";
    	$param['payway']  = 1;
    	$param['title'] = $price;
    	$param['body'] = $price;
    	$param['callback'] = "https://m.wmtxkj.com/sdk.php/Ipa365/install_show/user_id/{$userId}/game_id/{$gameId}/order_id/{$orderId}";
    	$param['notifyurl'] = "https://m.wmtxkj.com/callback.php/Notify/notify/apitype/alipay";
    	 
    	$ret = $this->alipay($param);
    	
    	$this->assign("url", $ret['url']);
        $this->assign("price",  $price);
        $this->assign("order_id", $payLog['order_id']);
        $this->assign("game_id",  $payLog['game_id']);
        //$this->assign("jump_url",$jump_url);
        $this->display();
    }

    /**
     * 下载页面  判断订单是否支付成功
     */
    public function install_show() {
    	$orderId = I('order_id', 0);
    	$gameId = I('game_id', 0);
    	/* $userId = I('user_id', 0);
    	
    	$user = M('user', 'tab_')->where(array(
    		'id' => $userId
    	))->find(); */
    	$userId = $this->userinfo['user_id'];
    	if (!$userId ) {
    		$this->error("请登入", "/mobile.php/ssg/login");
    	}
    	
//     	$userId = $_SESSION['user_id'];
    	if (!$userId ) {
    		$this->error("请登入", "/mobile.php/ssg/login");
    	}
    	if (!$orderId || !$gameId || !userId) {
    		$this->error("参数校验失败,请重试");
    	}
    	
    	$supersign = M('game_supersign', 'tab_')->where(array('order_id' => $orderId))->find();
    	if (!$supersign) {
    		$this->error("订单不存在");
    	}
    	if ($supersign['pay_status'] != 1) {
    		$this->error("订单未支付");
    	}
    	$game = M('game', 'tab_')->where(array('id' => $gameId))->find();
    	
    	$this->assign('game', $game);
    	$this->assign('url', U('Ipa365/install', array(
    		'order_id' => $orderId,
    		'user_id' => $userId,
    		'game_id' => $gameId
    	))); 
    	$this->display();
    }
    
    /**
     * 获取用户安装历史url
     */
    public function get_install_list() {
    	/* $gameId = I('game_id', 0);
    	$where = array(
    		'pay_status' => 1,
    		'ticket' => array('neq', '')
    	);
    	if ($id) $where['game_id'] = $gameId;
    	
    	$list = M('game_supersign', 'tab_')->where($where)->select();
//     	pp($list);
    	$url = $game['supersign_url']."?code={$code}";
    	pp($url);
    	redirect($url); */
    }
    
    /**
     * 用户点击安装
     */
    public function install() {
    	$userId = $this->userinfo['user_id'];
    	if (!$userId ) {
    		$this->error("请登入", "/mobile.php/ssg/login");
    	}
    	
    	$gameId = I('game_id', 0);
    	$orderId = I('order_id', 0);
    	if (!$userId || !$gameId || !$orderId) {
    		$this->error("参数有误!");
    	}
    	M()->startTrans();
    	// 获取支付记录
    	$gamesign = M('game_supersign', 'tab_')->where(array(
    		'order_id' => $orderId,
    		'user_id' => $userId,
    		'game_id' => $gameId,
    		'pay_status' => 1,
    	))->find();
    	if (!$gamesign) {
//     		pp(M('game_supersign', 'tab_')->_sql());
    		$this->error("支付记录不存在");
    	}
    	if ($gamesign['url']) {
    		redirect($gamesign['url']);
    	}
    	
    	$token = $gamesign['token'];
    	$ipa365 = new Ipa365();
    	
    	$i = 1;
    	while (1) {
    		// 获取授权码
    		$list = $ipa365->ticketList(array(
    			'token' => $token,
    			'limit' => $i,
    		));  // @todo: 并发授权码已分配的情况
    		$code = $list['data']['list'][$i-1]['code'];
	    	$codeExists = M('game_supersign', 'tab_')->field('id')->where(array(
	    		'ticket' => $code,
	    	))->find();
	    	if (!$codeExists) {
	    		break;
	    	}
	    	
	    	$i ++;
    	}
    	
    	$game = M('game', 'tab_')->where(array(
    		'id' => $gameId,
    	))->find();
    	$url = $game['supersign_url']."?code={$code}";
    	$r = M('game_supersign', 'tab_')->where(array(
    		'user_id' => $userId,
    		'game_id' => $gameId,
    		'pay_status' => 1
    	))->save(array(
    		'ticket' => $code,  // 调用安装的时候分配
    		'url' => $url,
    	));
    	if (!$r) {
    		pp(M('game_supersign', 'tab_')->_sql());
    		M()->rollback();
    		return -1;
    	}
    	M()->commit();
    	// 调用第三方连接
//     	pp($url);
    	redirect($url);
    }
    
    /*
     * 打包列表
     */
	public function pay_list() {
		$userId = $this->userinfo['user_id'];
    	if (!$userId ) {
    		$this->error("请登入", "/mobile.php/ssg/login");
    	}
    	
		$list = M('game_supersion', 'tab_')->where(array(
			'user_id' => $userId,
		))->select();
		
		$this->assign("list", $list);
		$this->display();
	} 
	
	// alipay
	public function alipay($param) {
		$pay  = new \Think\Pay($param['apitype'],C($param['config']));
		$vo   = new \Think\Pay\PayVo();
		$vo->setBody("超级签消费")
		->setFee($param['price'])//支付金额
		->setTitle($param['title'])
		->setOrderNo($param['order_id'])
		->setService($param['server'])
		->setSignType($param['signtype'])
		->setPayMethod("wap")
		->setTable("supersign")
		->setPayWay($param['payway'])
		->setCallback($param['callback'])
		->setNotifyUrl($param['notifyurl'])
		->setGameName(get_game_name($param['game_id']))
		->setServerId(0)
		->setUserId($param['user_id'])
 		->setSdkVersion($param['sdk_version']);
		$pay_['url']= $pay->buildRequestForm($vo);
		$pay_['out_trade_no']= $out_trade_no;
		return $pay_;
		
	}
}