package com.shanghaichengdi.ghjgitem.cache;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import javax.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

/**
 * @author gengaoliu
 */
public class CrudService<T> {

  @Resource
  public RedisTemplate<String, Object> redisTemplate;
  @Resource
  private RedisConfig redisConfig;

  public <R, T> R findObjByCache(String key, T t, Function<T, R> getDataFun) {
    R o = null;
    try {
      o = (R) redisTemplate.opsForValue().get(key);
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (o == null) {
      o = getDataFun.apply(t);
      if (o != null) {
        try {
          redisTemplate.opsForValue().set(key, o, redisConfig.getTimeOut(), TimeUnit.MINUTES);
          CacheManager.putFun(key, t, getDataFun);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return o;
  }

  public <R, T> List<R> findListByCache(String key, T t, Function<T, List<R>> getDataFun) {
    List<R> o = null;
    try {
      // reids
      o = (List<R>) redisTemplate.opsForValue().get(key);
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (o == null) {
      // oracle/mysql
      o = getDataFun.apply(t);
      if (o != null && o.size() > 0) {
        try {
          redisTemplate.opsForValue().set(key, o, redisConfig.getTimeOut(), TimeUnit.MINUTES);
          CacheManager.putFun(key, t, getDataFun);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return o;
  }

  public <R, T> Map<R, R> findMapByCache(String key, T t, Function<T, Map<R, R>> getDataFun) {
    Map<R, R> o = null;
    try {
      // reids
      o = (Map<R, R>) redisTemplate.opsForHash().entries(key);
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (CollectionUtils.isEmpty(o)) {
      // oracle/mysql
      o = getDataFun.apply(t);
      if (o != null && o.size() > 0) {
        try {
          redisTemplate.opsForHash().putAll(key, o);
          redisTemplate.expire(key, redisConfig.getTimeOut(), TimeUnit.MINUTES);
          CacheManager.putFun(key, t, getDataFun);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return o;
  }
}
