package com.quantgroup.asset.distribution.service.newrule.service;

import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.quantgroup.asset.distribution.service.jpa.entity.ProductRuleEntity;
import com.quantgroup.asset.distribution.service.jpa.repository.IProductRuleRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author shihuajun
 * @date 2021/8/28 10:53
 * @ describing 读写锁全量缓存
 */
@Slf4j
@Service
public class ProductRuleServiceImpl implements IProductRuleService{

    @Resource
    private IProductRuleRepository productRuleRepository;

    private static List<ProductRuleEntity> CACHE = Lists.newArrayList();
    private static final ReentrantReadWriteLock RW = new ReentrantReadWriteLock();
    private static final Lock R = RW.readLock();

    @PostConstruct
    public void loadProductRule(){
        CACHE = productRuleRepository.findAll();
        log.info("产品规则加载完毕，数量是 {}",CACHE.size());
    }


    @Override
    public ProductRuleEntity getProductRuleEntityByRuleMame(String ruleMame) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        if (StringUtils.isBlank(ruleMame)){
            throw new RuntimeException("获取产品配置参数错误");
        }
        ProductRuleEntity productRuleEntity = null;
        R.lock();
        try {
            productRuleEntity = CACHE.stream().filter(p -> p.getRuleName().equals(ruleMame)).findFirst().get();
        }catch (Exception e){
            log.error("产品配置执行有点问题", e);
        }finally {
            R.unlock();
        }
        log.info("获取产品配置耗时 {}，返回值为空？{}",stopwatch.elapsed(TimeUnit.MILLISECONDS), productRuleEntity == null);
        return productRuleEntity;
    }

    @Override
    public ProductRuleEntity getProductRuleEntityById(Long id) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        if (id == null){
            throw new RuntimeException("获取产品配置参数错误");
        }
        ProductRuleEntity productRuleEntity = null;
        R.lock();
        try {
            productRuleEntity = CACHE.stream().filter(p -> p.getId() == (id)).findFirst().get();
        }catch (Exception e){
            log.error("产品配置执行有点问题", e);
        }finally {
            R.unlock();
        }
        log.info("获取产品配置耗时 {}，返回值为空？{}",stopwatch.elapsed(TimeUnit.MILLISECONDS), productRuleEntity == null);
        return productRuleEntity;
    }

    @Override
    public List<ProductRuleEntity> getAll() {
        return CACHE;
    }
}
