package com.chushang.common.dict.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.chushang.common.core.web.Result;
import com.chushang.common.dict.feign.RemoteDictDataService;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DictUtils {

    private static final RemoteDictDataService remoteService = SpringUtil.getBean(RemoteDictDataService.class);
    private static final RedissonClient redissonClient = SpringUtil.getBean(RedissonClient.class);
    private static final String DICT_MAP_KEY = "dict_map_key:";
    private static final String DICT_MAP_LABEL = "dict_map_label:";
    /**
     * 远程调用
     */
    private static Map<String, String> getDictDataByType(String dictType) {
        // 获取到的缓存
        Result<Map<String, String>> result = remoteService.getInfo(dictType, "inner");
        if (result.isSuccess()) {
            return result.getData();
        }
        return new HashMap<>();
    }

    private static Map<String, String> getDictMap(String dictType){
        RBucket<Map<String, String>> bucket = redissonClient.getBucket(DICT_MAP_KEY + dictType);
        Map<String, String> dictMap = bucket.get();
        if (CollUtil.isEmpty(dictMap)) {
            dictMap = getDictDataByType(dictType);
            if (CollUtil.isEmpty(dictMap)) {
                return null;
            }
            bucket.set(dictMap);
        }
        return dictMap;
    }

    /**
     * 根据字段值获取字典标签
     *
     * @param dictType 字典类型
     * @param value    字典值
     * @return 字典标签
     */
    public static String getDictLabel(String dictType, String value) {
        Map<String, String> dictMap = getDictMap(dictType);
        assert dictMap != null;
        return dictMap.get(value);
    }

    /**
     * 根据字段值获取字典标签
     *
     * @param value    字典值
     * @return 字典标签
     */
    public static String getDictWrkStatusLabel(String value) {
        return getDictLabel("wrk_status", value);
    }

    /**
     * 根据字典标签获取字段值
     *
     * @param dictType 字典类型
     * @param label    字典标签
     * @return 字典值
     */
    public static String getDictValue(String dictType, String label) {
        Map<String, String> dictMap = getDictMap(dictType);
        assert dictMap != null;
        if (CollUtil.isEmpty(dictMap)){
            return null;
        }
        AtomicReference<String> key = new AtomicReference<>();
        dictMap.forEach((k,v)->{
            if (v.equals(label)){
                key.set(k);
            }
        });
        return key.get();
    }

}
