<?php
/**
 * 修复红包领取状态
 * * 每分钟执行一次
 * User: solu
 * Date: 2019/1/28
 * Time: 2:40 PM
 */

ini_set("display_errors", "On");
set_time_limit(0);
error_reporting(E_ALL & ~E_NOTICE);
require_once realpath(dirname(__FILE__)) . '/../common.php';

if (!singleProcess(getCurrentCommand(), ROOT_PATH . "/bin/run/fixRedpackLog.pid")) {
    exit("Sorry, this script file has already been running ...\n");
}

$st = microtime(true);

define('MAX_REQ', 5);
define('PROCESS_TIME', 30); // 修复超过30秒的记录

$objLog = new TableHelper('redpack_log', 'dw_chat');
$objRedpack = new Redpack();

$t = date('Y-m-d H:i:s', time() - PROCESS_TIME);
$sql = 'select * from redpack_log where status=0 and req_times<' . MAX_REQ . " and create_time<='{$t}'";
$logs = $objLog->getDb()->getAll($sql);
$c = count($logs);
$sc = 0;

$trxIds = array_column($logs, 'redpack_trx_id');
$redpacks = $objRedpack->objTable->getAll(['transfer_trx_id' => $trxIds], ['_field' => 'id, transfer_trx_id']);
$redpacks = arrayFormatKey($redpacks, 'transfer_trx_id', 'id');

foreach ($logs as $log) {
    $trxId = $log['redpack_trx_id'];
    $redpackId = $redpacks[$trxId] ?: 0;
    if (!$redpackId) {
        Eos::log("logId:{$log['id']} miss redpack id");
        continue;
    }

    $i = 0;
    do {
        sleep($i * 0.1);
        $json = Eos::grabRedpack($redpackId, $trxId, $log['id'], $log['player'], $log['quantity']);
        $ret = json_decode($json, true);
        $i += 1;
    } while ($i < 3 && !$ret['transaction_id']);

    if ($ret['transaction_id']) {
        $sc += 1;
        Eos::log("logId:{$log['id']} fix success");
    } else {
        Eos::log("logId:{$log['id']} fix error");
    }
    $req = $log['req_times'] + 1;
    $objLog->updateObject(['req_times' => $req], ['id' => $log['id']]);
}
$ct = microtime(true) - $st;
Eos::log("处理{$c}记录，成功{$sc}，耗时{$ct}");
