package com.quantgroup.asset.distribution.service.funding.impl;

import com.quantgroup.asset.distribution.service.funding.IAidLoanFundConfigService;
import com.quantgroup.asset.distribution.service.jpa.entity.AidLoanFundConfig;
import com.quantgroup.asset.distribution.service.jpa.repository.IAidLoanFundConfigRepository;
import com.quantgroup.asset.distribution.service.redis.IRedisService;
import com.quantgroup.asset.distribution.util.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.quantgroup.asset.distribution.constant.FundingConstants.AID_LOAN_FUND_CONFIG_POOL;
import static com.quantgroup.asset.distribution.constant.RedisKeyConstants.AID_LOAN_POOLKEYS_HMSET_KEY;

/**
 * Created by renfeng on 2019/7/22.
 */
@Service
@Slf4j
public class AidLoanFundConfigServiceImpl implements IAidLoanFundConfigService {

    @Autowired
    private IAidLoanFundConfigRepository iAidLoanFundConfigRepository;
    @Autowired
    private IRedisService<String> redisService;

    /**
     * 查询全部可用助贷资金
     *
     * @return
     */
    @Override
    public List<AidLoanFundConfig> findAll() {
        //助贷资金池key，存在说明有效 不存在说明失效，需要更新内存
        String poolKey = AID_LOAN_FUND_CONFIG_POOL.isEnable()?redisService.hmget(AID_LOAN_POOLKEYS_HMSET_KEY, AID_LOAN_FUND_CONFIG_POOL.getPoolKey()):null;
        if(StringUtils.isEmpty(poolKey)) {
            List<AidLoanFundConfig> aidLoanFundConfigs = iAidLoanFundConfigRepository.findByEnableTrue();
            if (CollectionUtils.isNotEmpty(aidLoanFundConfigs)) {
                String key = UUIDUtil.getUuid();
                AID_LOAN_FUND_CONFIG_POOL.setPoolKey(key);
                AID_LOAN_FUND_CONFIG_POOL.setAidLoanFundConfigList(aidLoanFundConfigs);
                AID_LOAN_FUND_CONFIG_POOL.setEnable(true);
                //每个服务器节点上的助贷资金池poolKey都不一样，放进redis作为刷新标识
                redisService.hmset(AID_LOAN_POOLKEYS_HMSET_KEY,key,key,7, TimeUnit.DAYS);
            }
        }
        //一定要拷贝
        return new ArrayList<>(AID_LOAN_FUND_CONFIG_POOL.getAidLoanFundConfigList()!=null?AID_LOAN_FUND_CONFIG_POOL.getAidLoanFundConfigList():new ArrayList<>());
    }



    /**
     * 根据id查询助贷资金
     *
     * @param id
     * @return
     */
    @Override
    public AidLoanFundConfig findById(Long id) {
        return iAidLoanFundConfigRepository.findOne(id);
    }

    /**
     * 根据编号查询助贷资金
     *
     * @param fundNo
     * @return
     */
    @Override
    public AidLoanFundConfig findByFundNo(String fundNo) {
        return iAidLoanFundConfigRepository.findByFundNo(fundNo);
    }

    @Override
    public void clearCache() {
        redisService.del(AID_LOAN_POOLKEYS_HMSET_KEY);
    }
}
