<?php
namespace app\models\redis;

use crmeb\utils\Redis;
use think\facade\Log;

/**
 * Class UserHash
 * @package app\models\redis
 */
class UserHash {
    protected static $FIELD_UNREAD = 'unread';
    protected static $FIELD_MINING = 'mining';

    public static function key($uid) {
        return 'user:'.$uid;
    }

    public static function unread_get($uid) {
        return intval(Redis::hGet(self::key($uid), self::$FIELD_UNREAD)??0);
    }

    public static function unread_incr($uid, $by=1) {
        return Redis::hIncrBy(self::key($uid), self::$FIELD_UNREAD, $by);
    }

    /*
     格式:
            {
                "progress": 10,
                "symbol": "etc",
                "icon": "http://x.png",
                "price": 20,
                "ts": 1234,
                "order_id": 12343,
                "total": 20
            }
     */
    public static function mining_get($uid) {
        $sval = Redis::hGet(self::key($uid), self::$FIELD_MINING);
        if ($sval) {
            return json_decode($sval, true);
        }
        return $sval;
    }

    public static function mining_set($uid, $mining) {
        if (!isset($mining['ts']) || !isset($mining['symbol']) ||
            !isset($mining['progress']) || !isset($mining['order_id'])) {
            Log::error('invalid mining value');
            return false;
        }

        return Redis::hSet(self::key($uid), self::$FIELD_MINING, json_encode($mining));
    }
}