package com.hz.pm.api.meta.helper.impl;

import com.hz.pm.api.meta.constant.DictTypeEnum;
import com.hz.pm.api.meta.helper.basic.AbstractDictionaryCache;
import com.hz.pm.api.meta.model.dto.DictionaryDTO;
import com.hz.pm.api.meta.service.IMetaDictionaryService;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author liuxinxin
 * @date 2022/7/22 上午10:47
 */
@Component
public class DictionaryCacheImpl extends AbstractDictionaryCache {

    public DictionaryCacheImpl(IMetaDictionaryService metaDictionaryService) {
        super(metaDictionaryService);
    }

    @Override
    public List<DictionaryDTO> listDictByDictType(DictTypeEnum dictionaryType) {
        return dictCache.get(dictionaryType.getKey());
    }

    @Override
    public List<DictionaryDTO> listDictByDictType(String dictType) {
        return dictCache.get(dictType);
    }

    @Override
    public DictionaryDTO getDictionaryByDictionaryType(DictTypeEnum dictionaryType, String code) {
        return Objects.requireNonNull(dictCache.get(dictionaryType.getKey()))
                .stream().filter(w -> w.getDictionaryCode().equals(code))
                .findFirst().orElse(null);
    }

    @Override
    public Optional<DictionaryDTO> getByCode(String dictionaryCode) {
        return Optional.ofNullable(dictionaryMap.get(dictionaryCode));
    }

    @Override
    public Optional<DictionaryDTO> getByDictTypeAndName(String dictType, String name) {
        List<DictionaryDTO> dicts = dictCache.get(dictType);
        if (dicts == null || dicts.isEmpty()) {
            return Optional.empty();
        }
        return dicts.stream()
                .filter(w -> w.getName().equalsIgnoreCase(name))
                .findFirst();
    }

}
