ConfigParamDao.java 2.32 KB
package com.viontech.keliu.dao;

import com.viontech.keliu.entity.SConfigParam;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhuhai
 * Date: 2023-12-23
 * Time: 14:29
 */
@Repository
@Slf4j
public class ConfigParamDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public String getConfigParamByMallIdAndConfigKey(Long mallId, String configKey) {
        List<SConfigParam> mallConfigParams = getMallConfigParams(mallId, Collections.singletonList(configKey));
        if (mallConfigParams.isEmpty()) {
            return null;
        }
        return mallConfigParams.get(0).getConfigValue();
    }

    public List<SConfigParam> getMallConfigParams(Long mallId, List<String> configKeys) {
        Map<String, Object> params = new HashMap<>();
        params.put("mallId", mallId);
        params.put("configKeys", configKeys);
        String sql = "SELECT * FROM s_config_params WHERE config_key IN (:configKeys) " +
                "AND ((account_id IS NULL AND mall_id IS NULL) " +
                "OR (account_id = (SELECT account_id FROM b_mall WHERE id = :mallId) AND mall_id IS NULL) " +
                "OR (mall_id = :mallId));";
        // 门店配置,集团配置,系统配置
        List<SConfigParam> sConfigParams = namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<>(SConfigParam.class));
        return new ArrayList<>(sConfigParams.stream().collect(Collectors.toMap(SConfigParam::getConfigKey, config -> config,
                this::mergeByPriority)).values());
    }

    /**
     * @param config 配置
     * @return 配置的使用优先级。数字越小,优先级越高。门店级最高
     */
    private int getLevel(SConfigParam config) {
        if (config.getMallId() != null) {
            return 1;
        }
        if (config.getAccountId() != null) {
            return 2;
        }
        return 3;
    }

    private SConfigParam mergeByPriority(SConfigParam c1, SConfigParam c2) {
        return getLevel(c1) <= getLevel(c2) ? c1 : c2;
    }

}