package com.yonge.toolset.payment.core.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.toolset.base.util.StringUtil;
import com.yonge.toolset.payment.base.enums.PaymentClientEnum;
import com.yonge.toolset.payment.core.dao.SysConfigPaymentDao;
import com.yonge.toolset.payment.core.entity.SysConfigPayment;
import com.yonge.toolset.payment.base.enums.OpenEnum;
import com.yonge.toolset.payment.core.service.SysConfigPaymentService;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
public class SysConfigPaymentServiceImpl extends ServiceImpl<SysConfigPaymentDao, SysConfigPayment> implements SysConfigPaymentService {

    private final static Logger log = LoggerFactory.getLogger(SysConfigPaymentServiceImpl.class);

    @Autowired
    private RedissonClient redissonClient;

    private static final String REDIS_KEY = "CONFIG_PAYMENT";

    @PostConstruct
    private void init() {
        List<SysConfigPayment> sysConfigPayments = baseMapper.selectList(Wrappers.emptyWrapper());
        for (SysConfigPayment configPayment : sysConfigPayments) {
            redissonClient.getBucket(REDIS_KEY + ":" + configPayment.getOpenType() + ":" + configPayment.getParamName()).set(configPayment, 30, TimeUnit.MINUTES);
        }
    }

    @Override
    public SysConfigPayment getPaymentConfig(OpenEnum openType, PaymentClientEnum client, String paramName) {
        return getPaymentConfig(openType, client.getCode(), paramName);
    }

    @Override
    public SysConfigPayment getPaymentConfig(OpenEnum openType, String paramName) {
        return getPaymentConfig(openType, "ALL", paramName);
    }

    private SysConfigPayment getPaymentConfig(OpenEnum openType, String platform, String paramName) {
        if (null == openType || StringUtil.isEmpty(paramName)) {
            return new SysConfigPayment();
        }
        SysConfigPayment configPayment = (SysConfigPayment) redissonClient.getBucket(REDIS_KEY + ":" + openType.getCode() + ":" + platform + ":" + paramName).get();
        if (null == configPayment) {
            configPayment = baseMapper.selectOne(Wrappers.<SysConfigPayment>lambdaQuery()
                    .eq(SysConfigPayment::getOpenType, openType.getCode())
                    .eq(SysConfigPayment::getClient, platform)
                    .eq(SysConfigPayment::getParamName, paramName)
            );
            redissonClient.getBucket(REDIS_KEY + ":" + openType.getCode() + ":" + platform + ":" + paramName).set(configPayment, 30, TimeUnit.MINUTES);
        }
        return configPayment;
    }
}