<?php

namespace App\Service;

/**
 * websocket关系存储
 *
 * @package App\Service
 */
class RedisService extends RedisInterface
{
    protected $prefix_fn = 'chat_fn';
    protected $prefix_user = 'chat_user';
    protected $prefix_user_info = 'userListInfo';
    protected $prefix_user_friends = 'myFriends';
    const SERVER_RUN_ID = 'prod'; // 替换为实际的值
    /**
     * 绑定fd和用户关系
     * @param string $fid
     * @param int $userId
     * @param $run_id
     * @return void
     * @throws \RedisException
     */
    public function bind(string $fid, int $userId, $run_id = self::SERVER_RUN_ID)
    {
        //站点通道+用户
        $this->redis->hSet($run_id, $this->prefix_fn . $fid, $userId);
        //站点用户+通道
        $this->redis->hSet($run_id, $this->prefix_user . $userId, $fid);
    }

    /**
     * 解绑通道和用户关系
     * @param string $fid
     * @param int $userId
     * @param $run_id
     * @return void
     * @throws \RedisException
     */
    public function unbind(string $fid, int $userId, $run_id = self::SERVER_RUN_ID)
    {
        $this->redis->hDel($run_id, $this->prefix_fn . $fid);

        $this->redis->hDel($run_id, $this->prefix_user . $userId);
    }

    /**
     * 通过FD获取userID
     * @param string $fid
     * @param $run_id
     * @return false|\Redis|string
     * @throws \RedisException
     */
    public function findUser(string $fid, $run_id = self::SERVER_RUN_ID)
    {
        return $this->redis->hGet($run_id, $this->prefix_fn . $fid);
    }

    /**
     * 通过UserID 获取fd
     * @param int $userId
     * @param $run_id
     * @return false|\Redis|string
     * @throws \RedisException
     */
    public function findFd(int $userId, $run_id = self::SERVER_RUN_ID)
    {
        return $this->redis->hGet($run_id, $this->prefix_user . $userId);
    }

    /**
     * 存储用户信息
     * @param int $userId
     * @param array $data
     * @return void
     * @throws \RedisException
     */
    public function setUserInfo(string $userId, array $data)
    {
        $this->redis->hSet($this->prefix_user_info, $userId, json_encode($data));
    }

    /**
     * 获取用户信息
     * @param int $userId
     * @return void
     * @throws \RedisException
     */
    public function getUserInfo(string $userId)
    {
        $this->redis->hGet($this->prefix_user_info, $userId);
    }
    /**
     * 获取用户好友列表
     * @return mixed
     * @throws \RedisException
     */
    public function getUserFriends(string $userId)
    {
        return $this->redis->hGet($this->prefix_user_friends, $userId);
    }
    /**
     * 设置用户好友列表
     * @return void
     * @throws \RedisException
     */
    public function setUserFriends(string $userId, array $friends)
    {
        $this->redis->hSet($this->prefix_user_friends, $userId, json_encode($friends));
    }

}