package com.huashe.park.core.service.impl;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huashe.common.constant.CacheConstants;
import com.huashe.common.utils.StringUtils;
import com.huashe.park.core.mapper.SysCustConfigMapper;
import com.huashe.park.core.redis.RedisProxy;
import com.huashe.park.core.service.ISysCustConfigService;
import com.huashe.park.domain.entity.CustSysConfig;

/**
 * 字典 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysCustConfigServiceImpl implements ISysCustConfigService {
    @Autowired
    private SysCustConfigMapper sysCustConfigMapper;

    @Autowired
    private RedisProxy redisProxy;

    @Override
    public int updateConfig(CustSysConfig config) {
        CustSysConfig temp = sysCustConfigMapper.selectConfigById(config.getConfigId());
        if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
            redisProxy.deleteObject(getCacheKey(temp));
        }

        int row = sysCustConfigMapper.updateConfig(config);
        if (row > 0) {
            redisProxy.setCacheObject(getCacheKey(config), config.getConfigValue());
        }
        return row;
    }

    @Override
    public CustSysConfig selectConfigObjByKey(String configKey) {
        CustSysConfig config = new CustSysConfig();
        config.setConfigKey(configKey);
        return sysCustConfigMapper.selectTenantConfig(config);
    }

    @Override
    public CustSysConfig selectConfigById(Long configId) {
        return sysCustConfigMapper.selectConfigById(configId);
    }

    @Override
    public boolean checkConfigKeyUnique(CustSysConfig config) {
        Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();
        CustSysConfig info = sysCustConfigMapper.checkConfigKeyUnique(config);
        return !StringUtils.isNotNull(info) || info.getConfigId().equals(configId);
    }

    private String getCacheKey(String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }

    private String getCacheKey(CustSysConfig configKey) {
        if (!ObjectUtils.isEmpty(configKey.getTenantId())) {
            return CacheConstants.SYS_CONFIG_KEY + configKey.getConfigKey() + ":" + configKey.getTenantId();
        }
        return CacheConstants.SYS_CONFIG_KEY + configKey.getConfigKey();
    }
}
