package cn.freemud.service.impl;

import cn.freemud.adapter.UserAdapter;
import cn.freemud.constant.RedisKeyConstant;
import cn.freemud.constant.UserInfoKeyConstant;
import cn.freemud.entities.dto.UserLoginInfoDto;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.UserService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author liming.guo
 * @date 2018/05/11
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private static Gson gson = new Gson();
    @Autowired
    private UserAdapter userAdapter;
    @Autowired
    private RedisCache redisCache;

    /**
     * 校验用户是否登录
     */
    public void checkUserLogin(String sessionId) {
        Map<String, Object> userInfoMap = this.getUserInfoMapBySessionId(sessionId);
        if (userInfoMap == null || userInfoMap.size() <= 0 || userInfoMap.get(UserInfoKeyConstant.MEMBER_ID) == null) {
            throw new ServiceException(ResponseResult.NOT_LOGIN);
        }
    }
    /**
     * 校验用户是否登录
     */
    public boolean checkUserLoginFlag(String sessionId) {
        Map<String, Object> userInfoMap = this.getUserInfoMapBySessionId(sessionId);
        log.info("submit userInfoMap:{}", gson.toJson(userInfoMap));
        if (userInfoMap == null || userInfoMap.size() <= 0 || userInfoMap.get(UserInfoKeyConstant.MEMBER_ID) == null) {
            return false;
        }
        return true;
    }

    /**
     * 获取缓存用户信息
     */
    @Override
    public Map<String, Object> getUserInfoMapBySessionId(String sessionId) {
        String redisKey = RedisKeyConstant.SAAS_USER_INFO_SESSIONID_KEY_PREFIX + sessionId;
        Map<String, Object> map;
        try {
            map = redisCache.getValue(redisKey);
        }catch (Exception e){
            map = redisCache.getValue(redisKey);
        }
        return map;
    }

    /**
     * 获取缓存用户信息
     *
     * @param sessionId
     * @return
     */
    @Override
    public UserLoginInfoDto getUserLoginInfoBySessionId(String sessionId) {
        checkUserLogin(sessionId);

        String redisKey = RedisKeyConstant.SAAS_USER_INFO_SESSIONID_KEY_PREFIX + sessionId;
        Map<String, Object> map = redisCache.getValue(redisKey);
        return userAdapter.getUserLoginInfoDto(map);
    }
}
