package io.renren.common.export;

import cn.afterturn.easypoi.handler.inter.IExcelDictHandler;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Component
public class GlobalExcelDictHandler implements IExcelDictHandler {
	
	private static final Logger LOG = LoggerFactory.getLogger(GlobalExcelDictHandler.class);

	@Override
	public String toName(String dict, Object obj, String name, Object value) {//导出
		return getDictCache(dict).get(value);
	}

	@Override
	public String toValue(String dict, Object obj, String name, Object value) {//导入
		return getDictCache(dict).inverse().get(name);
	}
	
	public BiMap<String,String> getDictCache(String catalog){
		BiMap<String,String> weekNameMap = HashBiMap.create();
		if(catalog.equals("advertiserRole")) {
			weekNameMap.put("ROLE_CHILD_ADVERTISER","广告主");
		}
		return weekNameMap;
	}
	
	
	//定义一个本地缓存临时缓存字典数据
	ListeningExecutorService refreshPools = MoreExecutors
			.listeningDecorator(Executors.newFixedThreadPool(2));
	LoadingCache<String, Map<String, String>> cache = CacheBuilder.newBuilder()
			.refreshAfterWrite(30, TimeUnit.MINUTES).expireAfterAccess(1, TimeUnit.HOURS).maximumSize(50)
			.build(new CacheLoader<String, Map<String, String>>() {
				@Override
				// 当本地缓存命没有中时，调用load方法获取结果并将结果缓存
				public Map<String, String> load(String key) {
					LOG.info("开始从远程读取缓存到本地");
					Map<String, String> data = getDictCache(key);
					return data;
				}
				// 刷新
				@Override
				public ListenableFuture<Map<String, String>> reload(String key, Map<String, String> oldValue)
						throws Exception {
					LOG.info("刷新远程读取缓存到本地");
					return refreshPools.submit(new Callable<Map<String, String>>() {
						@Override
						public Map<String, String> call() throws Exception {
							LOG.info("开始从远程读取缓存到本地");
							Map<String, String> data = getDictCache(key);
							return data;
						}
					});
				}
			});
}