package com.yuchen.saas.manage.dict.api.cache;

import com.yuchen.saas.manage.dict.api.entity.DictBiz;
import com.yuchen.saas.manage.dict.api.enums.DictBizEnum;
import com.yuchen.saas.manage.dict.api.feign.IDictBizClient;
import org.nest.springwrap.core.cache.utils.CacheUtil;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.SpringUtil;
import org.nest.springwrap.core.tool.utils.StringPool;

import java.util.List;

import static org.nest.springwrap.core.cache.constant.CacheConstant.DICT_CACHE;


public class DictBizCache {

    private static final String DICT_ID = "dictBiz:id";
    private static final String DICT_VALUE = "dictBiz:value";
    private static final String DICT_LIST = "dictBiz:list";

    private static IDictBizClient dictClient;

    private static IDictBizClient getDictClient() {
        if (dictClient == null) {
            dictClient = SpringUtil.getBean(IDictBizClient.class);
        }
        return dictClient;
    }


    public static DictBiz getById(Long id) {
        String keyPrefix = DICT_ID.concat(StringPool.DASH).concat(AuthUtil.getTenantId()).concat(StringPool.COLON);
        return CacheUtil.get(DICT_CACHE, keyPrefix, id, () -> {
            R<DictBiz> result = getDictClient().getById(id);
            return result.getData();
        });
    }


    public static String getValue(DictBizEnum code, Integer dictKey) {
        return getValue(code.getName(), dictKey);
    }


    public static String getValue(String code, Integer dictKey) {
        String keyPrefix = DICT_VALUE.concat(StringPool.DASH).concat(AuthUtil.getTenantId()).concat(StringPool.COLON);
        return CacheUtil.get(DICT_CACHE, keyPrefix + code + StringPool.COLON, String.valueOf(dictKey), () -> {
            R<String> result = getDictClient().getValue(code, String.valueOf(dictKey));
            return result.getData();
        });
    }


    public static String getValue(DictBizEnum code, String dictKey) {
        return getValue(code.getName(), dictKey);
    }


    public static String getValue(String code, String dictKey) {
        String keyPrefix = DICT_VALUE.concat(StringPool.DASH).concat(AuthUtil.getTenantId()).concat(StringPool.COLON);
        return CacheUtil.get(DICT_CACHE, keyPrefix + code + StringPool.COLON, dictKey, () -> {
            R<String> result = getDictClient().getValue(code, dictKey);
            return result.getData();
        });
    }


    public static List<DictBiz> getList(String code) {
        String keyPrefix = DICT_LIST.concat(StringPool.DASH).concat(AuthUtil.getTenantId()).concat(StringPool.COLON);
        return CacheUtil.get(DICT_CACHE, keyPrefix, code, () -> {
            R<List<DictBiz>> result = getDictClient().getList(code);
            return result.getData();
        });
    }

}
