package com.wecloud.im.thousandchat.cache;

import com.wecloud.im.core.util.GetIpUtils;
import com.wecloud.im.service.ImConversationMembersService;
import com.wecloud.im.server.cache.UserStateListener;
import com.wecloud.im.server.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 万人群的缓存（本地缓存待实现）
 * @author lixiaozhong
 * @date 2022年01月4日 17:00:00
 */
@Service
@Slf4j
public class ThousandChatCacheManager extends UserStateListener {

    /**
     * redis的群键 key
     */
    public static final String GROUP_KEY = "gp:";
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ImConversationMembersService imConversationMembersService;

    @Override
    public void onLineEvent(Long clientId, Integer platform, String longChannelId) {
        List<Long> thousandGroupIds = imConversationMembersService.findThousandGroupsByClientId(clientId);
        for(Long thousandGroupId : thousandGroupIds) {
            redisUtils.hashset(GROUP_KEY + thousandGroupId, clientId + RedisUtils.SPLIT + platform, GetIpUtils.getlanIp(),
                150, TimeUnit.DAYS);
        }

    }

    @Override
    public void offlineEvent(Long clientId, Integer platform, String longChannelId) {
        List<Long> thousandGroupIds = imConversationMembersService.findThousandGroupsByClientId(clientId);
        for(Long thousandGroupId : thousandGroupIds) {
            redisUtils.hashdel(GROUP_KEY + thousandGroupId, clientId + RedisUtils.SPLIT + platform);
        }
    }

    /**
     * 根据群ID 获取 万人群的 在线成员的key-val
     * @param conversionId
     * @return 在线成员的key-val，其中key是 client的主键id:platform, val是 ip
     */
    public Map<String, String> findOnlineClientsByThousandGroupId(Long conversionId) {
        return redisUtils.hashgetll(GROUP_KEY + conversionId);
    }

    /**
     * 根据群ID 获取 万人群的 在线成员的ip以及对应的成员信息，key-vaul
     * @param conversionId
     * @return 在线成员的key-val，其中key是 ip地址, val是 client的主键id:platform
     */
    public Map<String, List<String>> findOnlineHostsByThousandGroupId(Long conversionId) {
        Map<String /** client的主键ID:platform **/, String /** ip **/> onlineClientIpMap = findOnlineClientsByThousandGroupId(conversionId);
        Map<String /** ip **/, List<String /** client的主键ID:platform **/>> onlineIpClientMap = new HashMap<>();
        onlineClientIpMap.forEach((clientIdAndPlatforms, ip) -> {
            onlineIpClientMap.putIfAbsent(ip, new ArrayList<>());
            onlineIpClientMap.get(ip).add(clientIdAndPlatforms);
        });
        return onlineIpClientMap;
    }



}
