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.ErpColorKind;
import org.dromara.erp.domain.query.ErpColorKindQuery;
import org.dromara.erp.domain.vo.ErpColorKindVo;
import org.dromara.erp.mapper.ErpColorKindMapper;
import org.dromara.erp.service.IErpColorKindService;
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 ErpColorKindServiceImpl implements IErpColorKindService {

    private final ErpColorKindMapper baseMapper;

    @Override
    public List<ErpColorKindVo> queryList(ErpColorKindQuery query) {
        if (query != null && StrUtil.isNotBlank(query.getParentRowId())) {
            LambdaQueryWrapper<ErpColorKind> lqw = buildQueryWrapper(query);
            return baseMapper.selectVoList(lqw);
        }
        LambdaQueryWrapper<ErpColorKind> lqw = buildFirstLevelWrapper(query);
        List<ErpColorKindVo> all = baseMapper.selectVoList(lqw);
        Set<String> rowIds = all.stream()
            .map(ErpColorKindVo::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<ErpColorKind> buildFirstLevelWrapper(ErpColorKindQuery query) {
        LambdaQueryWrapper<ErpColorKind> lqw = Wrappers.lambdaQuery();
        if (query != null) {
            lqw.like(StrUtil.isNotBlank(query.getNum()), ErpColorKind::getNum, query.getNum());
            lqw.like(StrUtil.isNotBlank(query.getName()), ErpColorKind::getName, query.getName());
        }
        lqw.eq(ErpColorKind::getStopUse, 0);
        lqw.orderByAsc(ErpColorKind::getNum);
        return lqw;
    }

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

}
