package com.wecloud.im.ws.cache;

import com.wecloud.im.ws.model.redis.ClientConnectionInfo;
import com.wecloud.im.ws.utils.InitIp;
import com.wecloud.im.ws.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author hewei123@163.com
 * @Description 用户与redis绑定
 * @createTime 2020年04月14日 16:21:00
 */
@Service
@Slf4j
public class UserCache {

    /**
     * 在线状态
     */
    public static final Integer ONLINE = 1;
    /**
     * 离线状态
     */
    public static final Integer OFFLINE = 0;
    /**
     * 维护client端的信息
     * ip及平台类型
     */
    private static final String CLIENT_INFO = "cli:";
    /**
     * 维护client的多端数据:
     * 值为set集合,netty的channel的id
     */
    private static final String CLIENTS = "cis:";
    /**
     * 用户在线状态fieldKey
     */
    private static final String ONLINE_STATUS_KEY = "ost";
    /**
     * 设备类型   web,ios,android,ios,other
     */
    private static final String DEVICE_TYPE = "ty";

    /**
     * 用户所连机器ip的fieldKey
     */
    private static final String LAN_IP = "lip";
    /**
     * 用户公网ip，在公网部署集群需要用到
     */
    private static final String PUBLIC_IP = "pip";
    /**
     * 推送token
     */
    private static final String DEVICE_TOKEN = "dt";
    /**
     * 设备ID
     */
    private static final String DEVICE_ID = "di";
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 用户上线绑定机器ip
     *
     * @param longChannelId
     */
    public void online(String appKey, String clientId, String longChannelId) {
        log.info("ws用户上线保存redis连接ip:" + InitIp.lAN_IP, ",uid:" + longChannelId);
        redisUtils.addForSet(CLIENTS, longChannelId);

        redisUtils.hashset(CLIENT_INFO + appKey + clientId, LAN_IP, InitIp.lAN_IP);
        redisUtils.hashset(CLIENT_INFO + appKey + clientId, ONLINE_STATUS_KEY, ONLINE.toString());

    }

    /**
     * 用户下线删除绑定机器ip
     *
     * @param longChannelId
     */
    public void offline(String appKey, String clientId, String longChannelId) {
        log.info("ws用户离线删除redis key,uid:" + longChannelId);

        redisUtils.removeForSet(CLIENTS, longChannelId);

//        redisUtils.hashset(CLIENT_INFO + appKey + clientId, ONLINE_STATUS_KEY, OFFLINE.toString());
        redisUtils.delKey(CLIENT_INFO + appKey + clientId);
    }

    /**
     * 根据用户id获取存在redis中的数据 例如绑定的服务器ip地址
     *
     * @param clientId
     * @return
     */
    public ClientConnectionInfo getById(String clientId) {

        Map<String, String> hgetll = redisUtils.hashgetll(CLIENT_INFO + clientId);
        if (hgetll.isEmpty()) {
            return null;
        }
        ClientConnectionInfo appHashValueModel = new ClientConnectionInfo();
        appHashValueModel.setLanIp(hgetll.get(LAN_IP));
//        appHashValueModel.(Integer.parseInt(hgetll.get(ONLINE_STATUS_KEY)));
        return appHashValueModel;

    }


}
