package com.zhiqiyun.open.core.service.impl;

import com.zhiqiyun.open.config.RedisKeys;
import com.zhiqiyun.open.core.models.user.OauthInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class OauthServiceRedisImpl extends BaseOauthService {

    @Resource
    private RedisTemplate<String, OauthInfo> redisTemplate;

    @Override
    public void setAuth(String accessToken, OauthInfo oauthInfo) {
        try {
            String redisKey = String.format(RedisKeys.OAUTH, accessToken);
            this.redisTemplate.boundValueOps(redisKey).set(oauthInfo, 30, TimeUnit.DAYS);
        } catch (Exception e) {
            log.error("save oauth error", e);
        }

    }

    @Override
    public OauthInfo getAuth(String accessToken) {
        try {
            if (StringUtils.isBlank(accessToken)) {
                return null;
            }
            String redisKey = String.format(RedisKeys.OAUTH, accessToken);

            BoundValueOperations<String, OauthInfo> boundValueOperations = this.redisTemplate.boundValueOps(redisKey);
            boundValueOperations.expire(30, TimeUnit.DAYS);
            OauthInfo oauthInfo = boundValueOperations.get();
            if (oauthInfo != null && accessToken.equals(oauthInfo.getAccessToken())) {
                return oauthInfo;
            }
        } catch (Exception e) {
            log.error("get oauth error", e);
        }
        return null;
    }


    @Override
    public void destroy(String accessToken) {
        //销毁登录信息
        String redisKey = String.format(RedisKeys.OAUTH, accessToken);

        this.redisTemplate.delete(redisKey);
    }
}
