package com.cf.imes.framework.organ.core.redis;

import cn.hutool.core.text.CharSequenceUtil;
import com.cf.imes.framework.redis.core.TimeoutRedisCacheManager;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.util.ArrayList;
import java.util.List;

/**
 * 多组织的 {@link RedisCacheManager} 实现类
 *
 * 操作指定 name 的 {@link Cache} 时，自动拼接组织后缀，格式为 name + ":" + organId + 后缀
 *
 * @author airhead
 */
@Slf4j
public class OrganRedisCacheManager extends TimeoutRedisCacheManager {

    // 不需要拼接组织id的redis-key列表
    private static final List<String> ignoreOrganIdKeyList = new ArrayList<>();

    static {
        ignoreOrganIdKeyList.add("tenant_package_menu_ids");
    }

    public OrganRedisCacheManager(RedisCacheWriter cacheWriter,
                                  RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @Override
    public Cache getCache(String name) {
        // key带#代表设置了ttl，只保留#前的部分作为key
        if (name.contains("#")) {
            name = CharSequenceUtil.subBefore(name, "#", false);
        }
        // 如果开启多组织，则 name 拼接组织后缀
        if (!OrganContextHolder.isIgnore()
                && OrganContextHolder.getOrganId() != null
                && !ignoreOrganIdKeyList.contains(name)) {
            name = name + ":" + OrganContextHolder.getOrganId();
        }

        // 继续基于父方法
        return super.getCache(name);
    }

}
