<?php
namespace app\pay\controller;
use think\Db;

class Notify extends \think\Controller{
	
	public function index(){
	    $flag=false;
	    if (empty($_POST)) $_POST = $_GET;//如果为GET方式访问
		$sign = $this->ASCII($_POST);
		$verifyResult = $this->md5Verify($sign,$_POST['sign'],config('yuanbaopay.appkey'));
		//处理业务
		if($verifyResult){
			$pay_id = $_POST['pay_id']; //需要充值的ID 或订单号 或用户名
			$pay_no = $_POST['pay_no']; //交易流水号
			$pay_money = (float)$_POST['pay_money']; //实际付款金额	
			$pay_time = date("Y-m-d H:i:s",$_POST['pay_time']); //订单支付时间
			Db::startTrans();
			try{
			    //处理订单
			    $orderInfo = \think\Db::name("gamebuy_log")->field(true)->where("orderId", $pay_id)->find();
                if($orderInfo){
                    if($orderInfo["status"] == 0){                     
                        \think\Db::name("gamebuy_log")->where("orderId", $pay_id)->update(["status" => 1, "payId" => $pay_no, "payTime" => $pay_time]);
                        \think\Db::name("user")->where("account", $orderInfo["account"])->setInc("recharge", \intval($pay_money));
						$this->agentPoint($orderInfo["agent"], $orderInfo["account"], \intval($pay_money), $pay_id, $pay_no);
                        Db::commit();
                        $flag=true;                     
                    }else{
                        exit('订单已处理过，请勿重复操作'); 
                    }
                }else{
                    exit('订单不存在'); 
                }
				
			} catch (\Exception $e) {
			    Db::rollback();
			    $flag=false;
				exit('充值异常，Error：'.$e);
			}
			//发送物品
			if($flag){
                $this->sendItem($orderInfo);
				exit('success'); //返回成功，业务处理完成，下面不再执行了
			}
		}else{
			exit('fail');//返回失败 继续补单
		}
	}
	
	private function sendItem($orderInfo){
	    $productInfo = \think\Db::name("payconfig")->field(true)->where("id", $orderInfo["productId"])->find();
	    
	    $goods = $productInfo["goods"];
	    if($productInfo["firstAdd"] != ""){
	        $count = \think\Db::name("gamebuy_log")->where(["account" => $orderInfo["account"], "server" => $orderInfo["server"], "productId" => $orderInfo["productId"], "status" => 1])->count();
	        if ($count <= 1) {
	            $goods = $goods.";".$productInfo["firstAdd"];
	        }
	    }
	    
	    $gameInfo = \think\Db::name("gameconfig")->field(true)->where("server", $orderInfo["server"])->find();
	    
	    $this->realSendItems($orderInfo, $gameInfo, $goods);
	}
	
	private function realSendItems($orderInfo, $gameInfo, $goods){
	    $url = "http://127.0.0.1:8877/gm";	    
	    $serverid = $orderInfo["server"];
	    $guid = $orderInfo["guid"];		
		$getdata["server"] = $serverid;
		$getdata["guid"] = $guid;
		$getdata["cmd"] = "itemManage";
		$getdata["subcmd"] = "giveItem";
		$getdata["ip"] = $gameInfo["ip"];
		$getdata["gmport"] = $gameInfo["gmport"];
		$getdata["md5"] = md5("#aldGame#server*".$serverid."guid*".$guid."cmd*itemManage"."subcmd*giveItem"."#aldGame#");
	    
		$newarr = explode(";", $goods);
		
		$attach_item=[];
		for ($i = 0; $i < count($newarr); $i++) {
			$newarrd = explode(",", $newarr[$i]);
			if (isset($newarrd[0]) && isset($newarrd[1])) {
				$attach_item[] = ["id" => $newarrd[0], "num" => $newarrd[1]];
			}
		}
		
		$getdata["body"] = json_encode([
		    "player_list" => [\strval($guid)],//strval()转为字符串
		    "server_broadcast" => "0",
		    "content" => "购买：".$orderInfo["productName"]."，价格：". $orderInfo["price"],
		    "items" => $attach_item
	        ]);
		$returngm = http_curl($url, "get", $getdata);
		
		if ($returngm) {
		    $returngm = json_decode($returngm, true);
		    if($returngm["code"] == 1000){
		        return true;
		    }
		}
        return false;
	}
	
	private function agentPoint($agent, $account, $money, $sdorderno, $sdpayno){
	    if(trim($agent) != ""){
	        $data = \think\Db::name("agent")->field(true)->where("account", $agent)->find();
    	    if($data){
    	        $branch = $data["branch"];
    	        $rmb = $money * ($branch / 100);   	        
    	        \think\Db::name("agent")->where("account", $agent)->setInc("rmb", $rmb); 	        
    	        $order_id = time().rand(1, 1000000);
    	        $insert["agent"] = $agent;
                $insert["order_id"] = $sdorderno;
                $insert["pay_id"] = $sdpayno;
                $insert["account"] = $account;
        		$insert["money"] = $money;
        		$insert["point"] = $rmb;
        		$insert["time"] = date("Y-m-d H:i:s", time());
        		\think\Db::name("agent_log")->data($insert)->insert();
    	    }
	    }
	}
	/**
     * 验证签名
     * @param $prestr 需要签名的字符串
     * @param $sign 签名结果
     * @param $key 私钥
     * return 签名结果
     */
	function md5Verify($prestr, $sign, $key) {
		$prestr = $prestr . $key;
		$mysgin = md5($prestr);
		if($mysgin == $sign) {
			return true;
		} else {
			return false;
		}
	}
    function ASCII($params = array()){
		//ksort()对数组按照键名进行升序排序
		ksort($params);
		//reset()内部指针指向数组中的第一个元素
		reset($params);
		//$sign = http_build_query($params, '', '&amp');
		$sign = '';//初始化
		foreach ($params AS $key => $val) { //遍历POST参数
			if ($val == ''||$key == 'sign') continue; //跳过这些不签名
			if ($sign) $sign .= '&'; //第一个字符串签名不加& 其他加&连接起来参数
			$sign .= "$key=$val"; //拼接为url参数形式
		}		
		return $sign;
	}
}