<?php

/**
 * EOS相关操作
 * User: ben
 * Date: 2018/9/19
 * Time: 下午2:59
 */
class Eos extends EosBase {
    const REDIS_SERV = 'dw_chat';

    const PRE_ROOM_REWARD = 'globals:dw_chat:room_reward:';

    const LIVE_LIMIT = 20;

    static $objRedisMap = [];

    function __construct() {
        // 解锁钱包
        $this->unlockWallet();
    }

    static function pubEvent($event, $data, $cacheKey = self::REDIS_SERV) {
//        dwRedis::cleanInstance();
//        $objRedis = dwRedis::init('dw_box');
        if (!self::$objRedisMap[$cacheKey]) {
            self::$objRedisMap[$cacheKey] = dwRedis::initNewOne($cacheKey);
        }

        if (is_array($data)) {
            $data = json_encode($data);
        }

        return self::$objRedisMap[$cacheKey]->publish($event, $data);
    }

    /**
     * 块信息
     * @param $blockId
     * @return array
     */
    public static function getBlockInfo($blockId) {
        $cmd = "cleos -u https://api.eosnewyork.io get block '{$blockId}'";
        $json = self::execCmd($cmd);
        return json_decode($json, true);
    }

    /**
     * 获取块id
     * @param $block_num
     *
     * @return array
     */
    public static function getBlockId($block_num) {
        $cmd = "cleos -u {$GLOBALS['eosUrl']} get block {$block_num}";
        $json = self::execCmd($cmd);

        $json = str_replace("\n", '', $json);
        $info = json_decode($json, true);

        if ($info && $info['id']) {
            $block_id = $info['id'];
        } else {
            $hex = dechex($block_num);
            $hex = sprintf("%08s", $hex);
            preg_match("/\"({$hex}[0-9a-fA-F]{56})\"/", $json, $matches);
            $block_id = $matches[1];
        }

        return $block_id;
    }

    function _formatDateTime($str) {
        if (strpos($str, 'T') > 0) {
            return date('Y-m-d H:i:s', strtotime($str) + 8 * 3600);
        } else {
            return date('Y-m-d H:i:s', strtotime($str));
        }
    }


    public static function getAccountActions($account_name, $limit = 200) {
//        $cmd = "cleos -u {$GLOBALS['eosUrl']} get actions {$account_name} -1 -{$limit} -j";
        if (ENV == ENV_DEV) {
            $url = $GLOBALS['eosUrl'];
        } else {
            // 正式环境，要查历史数据，只能用 nodes.get-scatter.com
            $url = 'https://nodes.get-scatter.com';
        }

        $cmd = "cleos -u {$url} get actions {$account_name} -1 -{$limit} -j";
        $json = self::execCmd($cmd);

        return json_decode($json, true);
    }

    /**
     * 抢红包
     * @author solu
     * @param $redpackId
     * @param $trxId
     * @param $logId
     * @param $player
     * @param $quantity
     * @return string
     */
    public static function grabRedpack($redpackId, $trxId, $logId, $player, $quantity) {
        $cmd = "cleos -u {$GLOBALS['eosUrl']} push action {$GLOBALS['codeMee']} grabredpack '[ {$redpackId}, \"{$trxId}\", {$logId}, \"{$player}\", \"{$quantity}\" ]'  -j -p {$GLOBALS['codeMee']}";
        $json = self::execCmd($cmd);

        $log = [
            'player_transaction_id' => $trxId,
            'transaction_type' => 'grabredpack',
            'from' => $GLOBALS['codeMee'],
            'to' => $player,
            'cmd' => $cmd,
            'json' => $json,
        ];
        // 记录交易，失败重试
        self::logTrans($log);

        return $json;
    }

    public static function toDisplayFormat($amount, $unit = 'EOS') {
        return sprintf("%.4f {$unit}", round($amount / 10000, 4));
    }

    public static function toDisplayFormat2($amount, $unit = 'EOS', $keep = 4) {
        return sprintf("%.{$keep}f {$unit}", round($amount / 10000, 4));
    }

    public static function toNumber($amount) {
        $arr = explode(' ', $amount);
        return intval(floatval($arr[0]) * 10000);
    }

}