package com.njzscloud.dispose.config;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njzscloud.common.core.ienum.DictItem;
import com.njzscloud.common.core.ienum.DictManager;
import com.njzscloud.dispose.sys.dict.pojo.entity.DictItemEntity;
import com.njzscloud.dispose.sys.dict.service.DictItemService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class DictConfiguration {

    @Bean
    public DictManager dictManager(DictItemService dictItemService) {
        return new DictManager() {
            @Override
            public List<DictItem> load(String key) {
                try {
                    return dictItemService.list(Wrappers.<DictItemEntity>lambdaQuery().eq(DictItemEntity::getDictKey, key)
                            .orderByAsc(DictItemEntity::getSort, DictItemEntity::getVal, DictItemEntity::getId)
                        )
                        .stream().map(it -> new DictItem().setKey(key).setVal(it.getVal()).setTxt(it.getTxt()))
                        .collect(Collectors.toList());
                } catch (Exception e) {
                    return null;
                }
            }
        };
    }
}
