package com.storlead.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.framework.common.result.Result;
import com.storlead.system.pojo.dto.SysDictDTO;
import com.storlead.system.pojo.entity.SysDictDetailEntity;
import com.storlead.system.pojo.entity.SysDictEntity;
import com.storlead.system.mapper.SysDictMapper;
import com.storlead.system.service.SysDictDetailService;
import com.storlead.system.service.SysDictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典组 服务实现类
 * </p>
 *
 * @author chenkq
 * @since 2022-09-09
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDictEntity> implements SysDictService {

    @Resource
    private SysDictService sysDictService;
    @Resource
    private SysDictDetailService sysDictDetailService;
    @Override
    public Result lisDetialByCodes(SysDictDTO dto) {
        if (CollectionUtils.isEmpty(dto.getCodels()) && StrUtil.isBlank(dto.getCode())) {
            return Result.error("查询参数错误!");
        }
        LambdaQueryWrapper<SysDictEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SysDictEntity::getIsDelete,Integer.valueOf(0));
        queryWrapper.eq(SysDictEntity::getEnabled,1);
        if (StrUtil.isNotBlank(dto.getCode())) {
            queryWrapper.eq(SysDictEntity::getCode,dto.getCode());
        } else {
            queryWrapper.in(SysDictEntity::getCode,dto.getCodels());
        }
        List<SysDictEntity> vos = sysDictService.list(queryWrapper);
        if (CollectionUtils.isEmpty(vos)) {
            return Result.result(Collections.EMPTY_LIST);
        }
        List<Long> dictIds = vos.stream().map(SysDictEntity::getDictId).collect(Collectors.toList());

        LambdaQueryWrapper<SysDictDetailEntity> detialWq = new LambdaQueryWrapper<SysDictDetailEntity>();
        detialWq.in(SysDictDetailEntity::getDictId,dictIds);
        detialWq.eq(SysDictDetailEntity::getIsDelete,Integer.valueOf(0));
        detialWq.eq(SysDictDetailEntity::getEnabled,1);
        List<SysDictDetailEntity> vos1 = sysDictDetailService.list(detialWq);
        if (CollectionUtils.isEmpty(vos1)) {
            return Result.result(Collections.EMPTY_LIST);
        }
        Map<String,List<SysDictDetailEntity>> dictMap = new HashMap<>();
        vos.stream().forEach(e -> {
            List<SysDictDetailEntity> rs = vos1.stream().filter(s ->s.getDictId().equals(e.getDictId())).collect(Collectors.toList());
            dictMap.put(e.getCode(),rs);
        });
        return Result.result(dictMap);
    }
}
