package com.mosty.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.service.SysConfigNewService;
import com.mosty.common.config.Excel.DictUtils;
import com.mosty.common.config.entity.SysConfig;
import com.mosty.common.config.entity.SysDictItem;
import com.mosty.common.config.mapper.SysConfigMapper;
import com.mosty.common.config.mapper.SysDictItemMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class SysConfigNewServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig>
        implements SysConfigNewService {

    private final SysDictItemMapper sysDictItemMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    /**
     * 加载字典缓存数据
     */
    public void loadingDictCache() {
        List<SysDictItem> sysDictItems = this.sysDictItemMapper.selectList(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getXtZxbz, 0));
        if (CollectionUtils.isNotEmpty(sysDictItems)) {
            Map<String, List<SysDictItem>> dictDataMap = sysDictItems.stream().collect(Collectors.groupingBy(SysDictItem::getZdbh));
            for (Map.Entry<String, List<SysDictItem>> entry : dictDataMap.entrySet()) {
                DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictItem::getPx)).collect(Collectors.toList()));
            }
        }
    }

    @Override
    public String getValue(String pzj) {
        if (StringUtils.isBlank(pzj)) {
            return null;
        }
        SysConfig config = this.baseMapper.selectOne(
                new LambdaQueryWrapper<SysConfig>()
                        .eq(SysConfig::getPzj, pzj)
                        .eq(SysConfig::getXtZxbz, "0")
        );
        return config == null ? null : config.getPzz();
    }



}
