package com.yeejoin.amos.boot.module.jg.biz.edit.typeHandler;

import com.yeejoin.amos.boot.biz.common.typeHandler.DictTypeHandler;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 平台维护的字典处理器
 */
@Slf4j
@Component("platformDictTypeHandler")
@RequiredArgsConstructor
public class PlatformDictTypeHandler implements DictTypeHandler {

    private final Map<String, String> cache = new ConcurrentHashMap<>();

    @Override
    public String handle(String dictType, String dictCode) {
        if (StringUtils.isEmpty(dictCode)){
            return null;
        }
        return cache.computeIfAbsent(dictCode, k -> {
            try {
                List<DictionarieValueModel> result = Systemctl.dictionarieClient.dictValues(dictType).getResult();

                return result.stream()
                        .filter(Objects::nonNull)
                        .filter(dict -> dict.getDictDataKey() != null && dict.getDictDataKey().equals(dictCode))
                        .findFirst()
                        .map(DictionarieValueModel::getDictDataValue)
                        .orElse(null);
            } catch (Exception e) {
                log.error("获取字典数据失败，dictType: {}, error: {}", dictType, e.getMessage(), e);
                return null;
            }
        });
    }


}
