package com.liquidnet.service.goblin.util;

import com.alibaba.fastjson.JSON;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.service.adam.constant.AdamRedisConst;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
import com.liquidnet.service.adam.dto.vo.AdamUserMemberVo;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.feign.adam.api.FeignAdamBaseClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class AdamRedisUtils {
    @Autowired
    public RedisUtil redisUtil;
    @Autowired
    @Lazy
    private FeignAdamBaseClient feignAdamBaseClient;

    public AdamUserInfoVo getUserInfoVoByUid(String uid) {
        String rk = AdamRedisConst.INFO_USER.concat(uid);
        long s = System.currentTimeMillis();
        AdamUserInfoVo vo = (AdamUserInfoVo) redisUtil.get(rk);
        // TODO 如果不存在则从数据库查询
        if (null == vo) {
            log.info("not find value in redis cache, key: {}", rk);
            try {
                ResponseDto<AdamUserInfoVo> responseDto = feignAdamBaseClient.getAdamUserInfoByUid(uid);
                log.info("feign client response: {}", JSON.toJSONString(responseDto));
                if (null != responseDto && responseDto.isSuccess() && null != responseDto.getData()) {
                    log.info("feign client response success");
                    vo = responseDto.getData();
                }
            }catch (Exception e) {
                log.error("error", e);
            }
        }
        log.debug("#RDM耗时:{}ms", System.currentTimeMillis() - s);
        return vo;
    }

    public AdamUserMemberVo getUserMemberVoByUid(String uid) {
        String rk = AdamRedisConst.INFO_USER_MEMBER.concat(uid);
        long s = System.currentTimeMillis();
        AdamUserMemberVo vo = (AdamUserMemberVo) redisUtil.get(rk);
        if (null != vo) {
            vo.setState(vo.getState() == 1 ? (vo.getExpiryAt().isAfter(LocalDateTime.now()) ? 1 : 2) : vo.getState());
        }
        log.debug("#RDM耗时:{}ms", System.currentTimeMillis() - s);
        return vo;
    }
}
