package org.dromara.erp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.erp.domain.ErpColor;
import org.dromara.erp.domain.query.ErpColorQuery;
import org.dromara.erp.domain.vo.ErpColorVo;
import org.dromara.erp.mapper.ErpColorMapper;
import org.dromara.erp.service.IErpColorService;
import org.springframework.stereotype.Service;

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

/**
 * ERP 颜色 Service 业务层处理
 *
 * @Author: Antigravity
 */
@RequiredArgsConstructor
@Service
public class ErpColorServiceImpl implements IErpColorService {

    private final ErpColorMapper baseMapper;

    @Override
    public List<ErpColorVo> queryList(ErpColorQuery query) {
        if (query != null && StrUtil.isNotBlank(query.getParentRowId())) {
            LambdaQueryWrapper<ErpColor> lqw = buildQueryWrapper(query);
            return baseMapper.selectVoList(lqw);
        }
        LambdaQueryWrapper<ErpColor> lqw = buildFirstLevelWrapper(query);
        List<ErpColorVo> all = baseMapper.selectVoList(lqw);
        Set<String> rowIds = all.stream()
            .map(ErpColorVo::getRowId)
            .filter(ObjectUtil::isNotEmpty)
            .collect(Collectors.toSet());
        return all.stream()
            .filter(item -> {
                String pid = item.getParentRowId();
                return ObjectUtil.isEmpty(pid) || !rowIds.contains(pid);
            })
            .collect(Collectors.toList());
    }

    private LambdaQueryWrapper<ErpColor> buildFirstLevelWrapper(ErpColorQuery query) {
        LambdaQueryWrapper<ErpColor> lqw = Wrappers.lambdaQuery();
        if (query != null) {
            lqw.like(StrUtil.isNotBlank(query.getNum()), ErpColor::getNum, query.getNum());
            lqw.like(StrUtil.isNotBlank(query.getName()), ErpColor::getName, query.getName());
            lqw.eq(StrUtil.isNotBlank(query.getColorKind()), ErpColor::getColorKind, query.getColorKind());
        }
        lqw.eq(ErpColor::getStopUse, 0);
        lqw.orderByAsc(ErpColor::getNum);
        return lqw;
    }

    private LambdaQueryWrapper<ErpColor> buildQueryWrapper(ErpColorQuery query) {
        LambdaQueryWrapper<ErpColor> lqw = Wrappers.lambdaQuery();
        lqw.eq(ErpColor::getStopUse, 0);
        lqw.like(StrUtil.isNotBlank(query.getNum()), ErpColor::getNum, query.getNum());
        lqw.like(StrUtil.isNotBlank(query.getName()), ErpColor::getName, query.getName());
        lqw.eq(StrUtil.isNotBlank(query.getColorKind()), ErpColor::getColorKind, query.getColorKind());
        lqw.eq(ErpColor::getParentRowId, query.getParentRowId());
        lqw.orderByAsc(ErpColor::getNum);
        return lqw;
    }

}
