package org.shunt.cache;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.Data;
import lombok.Setter;
import org.shunt.contorller.response.AuthorDTO;
import org.shunt.contorller.response.ShuntQuotaVO;
import org.shunt.service.ShuntService;
import org.springframework.stereotype.Component;

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

@Component
public class ApplyCacheUtils {

    private static final LoadingCache<Key, ShuntQuotaVO> cache =
            CacheBuilder.newBuilder()
                    .maximumSize(100)
                    .expireAfterAccess(1, TimeUnit.HOURS)
                    .concurrencyLevel(10) // 设置并发级别为10
                    .build(
                            new CacheLoader<Key, ShuntQuotaVO>() {
                                @Override
                                public ShuntQuotaVO load(Key key) throws Exception {
                                    AuthorDTO authorDTO = new AuthorDTO();
                                    authorDTO.setCollegeId(key.collegeId);
                                    authorDTO.setYearId(key.yearId);
                                    return shuntService.getMajorQuota(authorDTO);
                                }
                            });


    private static ShuntService shuntService;

    @Data
    private static class Key{
        private String  collegeId;//学院ID
        private Integer yearId;//年份
    }

    @Resource
    public void setShuntService(ShuntService shuntService){
        ApplyCacheUtils.shuntService = shuntService;
    }


    public static ShuntQuotaVO get(AuthorDTO authorDTO){
        Key key = new Key();
        key.collegeId = authorDTO.getCollegeId();
        key.yearId = authorDTO.getYearId();
        return cache.getUnchecked(key);
    }

}
