package com.qmth.exam.reserve.cache.impl;

import com.qmth.exam.reserve.bean.org.OrgInfo;
import com.qmth.exam.reserve.cache.CacheConstants;
import com.qmth.exam.reserve.cache.RedisClient;
import com.qmth.exam.reserve.service.OrgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class OrgCacheService implements CacheConstants {

    private static final Logger log = LoggerFactory.getLogger(OrgCacheService.class);

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private OrgService orgService;

    /**
     * 获取某个学校缓存
     */
    public OrgInfo getOrgById(Long orgId) {
        String cacheKey = String.format(CACHE_ORG, orgId);
        OrgInfo value = redisClient.get(cacheKey, OrgInfo.class);
        if (value != null) {
            return value;
        }

        value = orgService.findInfoById(orgId);
        if (value == null) {
            return null;
        }

        redisClient.set(cacheKey, value, 10, TimeUnit.MINUTES);
        log.info("SET cacheKey:{}", cacheKey);

        return value;
    }

    public void clearOrgByIdCache(Long orgId) {
        String cacheKey = String.format(CACHE_ORG, orgId);
        redisClient.delete(cacheKey);
        log.warn("DELETE cacheKey:{}", cacheKey);
    }

    /**
     * 获取当前默认的学校缓存
     */
    public OrgInfo currentOrg() {
        OrgInfo value = redisClient.get(CACHE_CURRENT_ORG, OrgInfo.class);
        if (value != null) {
            return value;
        }

        value = orgService.currentOrg();
        if (value == null) {
            return null;
        }

        redisClient.set(CACHE_CURRENT_ORG, value, 6, TimeUnit.HOURS);
        log.info("SET cacheKey:{} curOrgId:{}", CACHE_CURRENT_ORG, value.getOrgId());

        return value;
    }

    public void clearCurrentOrgCache() {
        redisClient.delete(CACHE_CURRENT_ORG);
        log.warn("DELETE cacheKey:{}", CACHE_CURRENT_ORG);
    }

}
