<?php
/**
 * 退回已超时的红包
 * * 每10分钟执行一次
 * User: solu
 */

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/returnRedpack.pid")) {
    exit("Sorry, this script file has already been running ...\n");
}

$st = microtime(true);

$objRedpack = new Redpack();

$t = date('Y-m-d H:i:s', strtotime('-1 days'));
$sql = "select id, sender, transfer_trx_id, status, num_left, create_time from redpack where status=0 and create_time<'{$t}'";
$redpacks = $objRedpack->objDb->getAll($sql);
$c = count($redpacks);
$sc = 0;

foreach ($redpacks as $redpack) {
    $trxId = $redpack['transfer_trx_id'];
    $redpackId = $redpack['id'];

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

    if ($ret['transaction_id']) {
        $sc += 1;
        Eos::log("redpack:{$log['id']} return success");
    } else {
        Eos::log("redpack:{$log['id']} return error");
    }
}
$ct = microtime(true) - $st;
Eos::log("处理{$c}记录，成功{$sc}，耗时{$ct}");
