<?php

/**
 * 腾讯登录通知(来自客户端)
 * 用于获取登录和支付token, 以便进行订单的检查和补发(扣除后台游戏币需要token)
 *
 */
include_once __DIR__ . '/../../../main.php';                                    # 导入game utils
include_once __DIR__ . '/../Mo/payResp.php';                                    # 导入通用返回值结构
include_once __DIR__ . '/../Mo/dbOrder.php';                                    # 导入数据库中订单数据结构
// 导入应用宝支付库
require_once __DIR__ . '/ysdks/Api.php';
require_once __DIR__ . '/ysdks/Ysdk.php';
require_once __DIR__ . '/ysdks/Payments.php';

require_once 'config.yyb.php';                                                  # 配置文件, Ps. 里面用到了object

use loyalsoft\CLog;
use loyalsoft\JsonUtil;
use loyalsoft\HttpUtil;

//HttpUtil::PostOnly();                                                         # 要求客户端必须以post方式提交数据
//
// <editor-fold defaultstate="collapsed" desc=" 功能函数 ">

/**
 * 登录校验
 * @param type $sdk
 * @param type $plat
 * @param type $cfg
 * @param type $openid
 * @param type $accessToken
 * @param type $userip
 * @param type $ts
 * @return type
 */
function CheckToken($sdk, $plat, $cfg, $openid, $accessToken, $userip, $ts) {
    # 通用参数
    $params = array(
        'appid' => $cfg->appid,
        'openid' => $openid,
        'userip' => $userip,
        'sig' => md5($cfg->appkey . $ts),
        'timestamp' => $ts,
    );
    if ('qq' == $plat) {
        $params['openkey'] = $accessToken;
        $ret = qq_check_token($sdk, $params);
    } else {
        $params['access_token'] = $accessToken;
        $ret = wx_check_token($sdk, $params);
    }
    loyalsoft\CLog::warn('[应用宝]: 登录验证' . loyalsoft\HttpUtil::makeQueryString($params));
    return $ret;
}

/**
 * 应用宝平台在登录的时候检查有没有未完成订单, 有的话尝试扣款,将扣款成功的订单转为代发货状态.
 * @param type $sdk
 * @param string $plat
 * @param type $openid
 * @param type $openkey
 * @param type $pf
 * @param type $pfkey
 */
function checkOrders($sdk, $plat, $openid, $openkey, $pf, $pfkey) {
    $accout_type = $plat;
    $tableName = 'tpl_order_tab';
    $zoneid = 1;
    $tsnow = loyalsoft\now();
    $baseParam = array(
        'openid' => $openid,
        'openkey' => $openkey,
        'ts' => $tsnow,
        'pf' => $pf,
        'pfkey' => $pfkey,
        'zoneid' => $zoneid,
    );
    $orders = loyalsoft\daoInst()->select()->from($tableName)                   # 查询未完成订单
                    ->where('uid')->eq($openid)
                    ->andWhere('status')->eq(0)->fetchAll();
    if (count($orders) > 0) {                                                   # 遍历订单
        foreach ($orders as $ord) {
            $ord = new \loyalsoft\pay\dbOrder();
            if ($tsnow - $ord->order_ts > 86400) {                              # 一天以前的订单直接关闭
                $n = loyalsoft\daoInst()->update($tableName)
                        ->data(array('status' => 2))
                        ->where('cpOrderId')->eq($ord->cpOrderId)
                        ->exec();
            } else {                                                            # 尝试扣除订单记载的游戏币金额
                $params = $baseParam;
                $ret = get_balance_m($sdk, $params, $accout_type);

                if ($ret->ret == 0) {                                         # 查询余额成功
                    $balance = $ret->balance;                                 # 当前余额
                    if ($ord->amount <= $balance * 10) {                        # 校验余额成功
                        $params = $params = $baseParam;
                        $params['billno'] = $ord->cpOrderId;
                        $params['amt'] = $ord->amount / 10;
                        $ret = pay_m($sdk, $params, $accout_type);              # 扣除游戏币余额
                        if ($ret->ret == 0) {                                   # 扣费成功
                            $n = loyalsoft\daoInst()->update($tableName)->data(array('status' => 1))
                                    ->where('cpOrderId')->eq($ord->cpOrderId)
                                    ->exec();                                   # 更新订单状态,->已付款 ,
                            # Ps.订单状态修改后, 登录游戏的时候自动检查支付完成尚未发货订单进行发货.
                            CLog::pay("[应用宝] [发货] 订单: " . $ord->cpOrderId . ", 金额: " . $ord->amount);
                        } // else 扣费失败不做处理
                    }// else 校验失败不做处理
                }
            }
        }
    }
}

// </editor-fold>
//
/** 客户端需要传的参数
  $params = array(
  'plat' => '',
  'openid' => '',
  'openkey' => '',
  'access_token'=>'',
  'pay_token' => '',
  );
 */
try {
    $str = HttpUtil::getQueryString();
    //    $str = gzinflate($str);
    $params = JsonUtil::decode($str);                                           # 提取参数
    $plat = $params->plat;
    $openid = $params->openId;
    $openkey = $params->openKey;                                                # 支付时(手Q的paytoken,微信的accessToken)
    $pf = $params->pf;
    $pfkey = $params->pfKey;
    $accessToken = $params->access_token;
    $cfg = config_for_yyb::Inst($plat);                                         # 配置

    $sdk = new Api($cfg->appid, $cfg->appkey);                                  // 创建YSDK实例
    $sdk->setPay($cfg->pay_appid, $cfg->pay_appkey);                            // 设置支付信息
    $sdk->setServerName($cfg->server_name);                                     // 设置YSDK调用环境(沙箱地址/现网地址)
    $tableName = 'tpl_order_tab';
    $tag = '[应用宝]';

    $userip = HttpUtil::clientIP();
    $ts = \loyalsoft\now();

    $ret = CheckToken($sdk, $plat, $cfg, $openid, $accessToken, $userip, $ts);  # 验证登录票据

    if ($ret['ret'] == 0) {                                                     # 0 代表登录成功, -1代表失败
        // ps. 票据验证成功的情况下, 执行订单检查逻辑, 对于异常订单进行补扣,补发.
        // 待支付订单: status=0
        // 创建时间大于24小时的, 转为关闭状态, status=>2
        // 24小时以内的 调用扣除游戏币接口-> pay(amount/10, cpOrderId),
        //      := successs , 订单转为支付完成状态, status=>1,
        //      := 其他,failure, 订单转为关闭状态, status=>2, otherinfo=>msg
        checkOrders($sdk, $plat, $openid, $openkey, $pf, $pfkey);
        echo payResp::ok($ret);                                                 # 客户端不关心结果
        CLog::err('[应用宝]: 登录票据验证成功');
    } else {                                                                    # 登录校验失败
        echo payResp::err($ret['msg'], '未登录');
        CLog::err('[应用宝]: 登录票据验证失败');
    }
} catch (Exception $ex) {
    echo payResp::err($ex->getCode(), $ex->getMessage());                       # 返回异常信息
    CLog::err('[应用宝]: 登录票据验证过程发生异常');
}


