package com.easyproject.clientbus.service.config.impl;

import com.easyproject.common.constant.CacheConstants;
import com.easyproject.common.core.redis.RedisCache;
import com.easyproject.common.core.text.Convert;
import com.easyproject.common.utils.StringUtils;
import com.easyproject.clientbus.domain.ClientConfig;
import com.easyproject.clientbus.mapper.ClientConfigMapper;
import com.easyproject.clientbus.service.config.IClientConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 参数配置 服务层实现
 *
 * @author java001
 */
@Service
public class ClientConfigServiceImpl implements IClientConfigService {

    @Autowired
    private ClientConfigMapper configMapper;
    @Autowired
    private RedisCache redisCache;

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey)
    {
        return CacheConstants.CLIENT_CONFIG_KEY + configKey;
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey)
    {
        String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue))
        {
            return configValue;
        }
        ClientConfig config = new ClientConfig();
        config.setConfigKey(configKey);
        ClientConfig retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig))
        {
            redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取登录验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaEnabled()
    {
        String captchaEnabled = selectConfigByKey("with.account.login.captchaEnabled");
        if (StringUtils.isEmpty(captchaEnabled))
        {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }

    /**
     * 获取注册验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectRegisterCaptchaEnabled() {
        String captchaEnabled = selectConfigByKey("with.account.regisrer.captchaEnabled");
        if (StringUtils.isEmpty(captchaEnabled))
        {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }
}
