package com.sv.service.api;

import com.sv.service.api.config.SpringProfiles;
import com.ydd.framework.core.common.TimeConstants;
import com.ydd.framework.core.interceptor.AccessTokenInterceptor;
import com.ydd.framework.core.service.CacheService;
import com.ydd.framework.core.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Service - 用户编号缓存
 *
 * @author Demon
 * @since 2017-10-31
 */
@Service
public class MemberIdCacheService extends BaseServiceImpl {

    /**
     * 2小时有效期（秒）
     */
    public static final Long EXPIRE_SECONDS = TimeConstants.WEEK_1;

    @Resource
    private CacheService cacheService;

    @Resource
    private SpringProfiles springProfiles;

    /**
     * 保存访问凭证
     *
     * @param memberId    会员编号
     * @param accessToken 访问凭证
     */
    public void cacheMemberId(Integer memberId, String accessToken) {
        cacheService.set(AccessTokenInterceptor.ACCESS_TOKEN_CACHE_KEY + accessToken, memberId, getExpireSeconds()*1000);
    }

    /**
     * 获取会员编号
     *
     * @param accessToken 访问凭证
     * @return 会员编号
     */
    public Integer getMemberIdByAccessToken(String accessToken) {
        Object ret = cacheService.get(AccessTokenInterceptor.ACCESS_TOKEN_CACHE_KEY + accessToken);

        if (ret == null) {
            return null;
        }

        return (Integer) ret;
    }

    /**
     * 删除访问凭证
     *
     * @param accessToken 访问凭证
     */
    public void remove(String accessToken) {
        cacheService.remove(AccessTokenInterceptor.ACCESS_TOKEN_CACHE_KEY + accessToken);
    }

    /**
     * 获取有效期
     *
     * @return 有效期
     */
    private Long getExpireSeconds() {
        if (springProfiles.isProduction()) {
            return EXPIRE_SECONDS;
        }

        // 非正式环境，有效期为1个月
        return EXPIRE_SECONDS * 12 * 30;
    }
}
