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

import com.quantgroup.asset.distribution.constant.RedisKeyConstants;
import com.quantgroup.asset.distribution.service.funding.IAidFundAuditOrderService;
import com.quantgroup.asset.distribution.service.jpa.entity.AidLoanFundAuditOrder;
import com.quantgroup.asset.distribution.service.jpa.repository.IAidLoanFundAuditOrderRepository;
import com.quantgroup.asset.distribution.service.redis.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author : Hyuk
 * @description : AidFundAuditOrderServiceIMpl
 * @date : 2020/3/30 11:14 上午
 */
@Service
public class AidFundAuditOrderServiceImpl implements IAidFundAuditOrderService {

    @Autowired
    private IAidLoanFundAuditOrderRepository aidLoanFundAuditOrderRepository;
    @Autowired
    private IRedisService<AidLoanFundAuditOrder> redisService;

    @Override
    public AidLoanFundAuditOrder saveAidFundAuditOrder(AidLoanFundAuditOrder aidLoanFundAuditOrder) {
        aidLoanFundAuditOrder = aidLoanFundAuditOrderRepository.save(aidLoanFundAuditOrder);
        String key = RedisKeyConstants.AID_FUND_AUDIT_ORDER_KEY + aidLoanFundAuditOrder.getBizNo() + "_" + aidLoanFundAuditOrder.getFundId();
        redisService.setEntityEx(key, aidLoanFundAuditOrder, 30, TimeUnit.MINUTES);
        return aidLoanFundAuditOrder;
    }

    @Override
    public AidLoanFundAuditOrder updateOrderStatus(AidLoanFundAuditOrder aidLoanFundAuditOrder, Integer status) {
        aidLoanFundAuditOrder.setAuditResult(status);
        return saveAidFundAuditOrder(aidLoanFundAuditOrder);
    }

    @Override
    public AidLoanFundAuditOrder findByBizNoAndFundId(String bizNo, String fundId) {
        String key = RedisKeyConstants.AID_FUND_AUDIT_ORDER_KEY + bizNo + "_" + fundId;
        AidLoanFundAuditOrder aidLoanFundAuditOrder = redisService.getEntity(key);
        if (aidLoanFundAuditOrder == null) {
            aidLoanFundAuditOrder = aidLoanFundAuditOrderRepository.findByBizNoAndFundIdAndEnableIsTrue(bizNo, fundId);
            if (aidLoanFundAuditOrder != null) {
                redisService.setEntityEx(key, aidLoanFundAuditOrder, 30, TimeUnit.MINUTES);
            }
        }
        return aidLoanFundAuditOrder;
    }

}
