package org.jeecg.modules.regular.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.regular.entity.RegularDetail;
import org.jeecg.modules.regular.entity.RegularInput;
import org.jeecg.modules.regular.mapper.RegularDetailMapper;
import org.jeecg.modules.regular.mapper.RegularInputMapper;
import org.jeecg.modules.regular.service.IRegularInputService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 检修测量数据
 * @Author: jeecg-boot
 * @Date:   2025-01-17
 * @Version: V1.0
 */
@Service
@RequiredArgsConstructor
public class RegularInputServiceImpl extends ServiceImpl<RegularInputMapper, RegularInput> implements IRegularInputService {

    private final RegularDetailMapper regularDetailMapper;

    @Override
    public List<RegularInput> listRegularInput(RegularInput regularInput) {
        List<RegularInput> regularInputs = this.list(new LambdaQueryWrapper<RegularInput>()
                .eq(StringUtils.isNotBlank(regularInput.getDetailId()), RegularInput::getDetailId, regularInput.getDetailId())
                .like(StringUtils.isNotBlank(regularInput.getDataPot()), RegularInput::getDataPot, regularInput.getDataPot()));
        return regularInputs.stream()
            .filter(ri -> StringUtils.isBlank(ri.getPid()))
            .peek(ri -> {
                // 设置子节点
                List<RegularInput> children = regularInputs.stream()
                        .filter(child -> ri.getId().equals(child.getPid()))
                        .collect(Collectors.toList());

                if (!children.isEmpty()) {
                    ri.setPoints(children);
                }
            }).collect(Collectors.toList());
    }

    /**
     * 兼容对传入数据进行插入和更新操作
     * @param regularInput
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertRegularInput(RegularInput regularInput) {
        List<RegularInput> points = regularInput.getPoints();

        if (StringUtils.isBlank(regularInput.getId())) {//新增检修测量项
            if (this.save(regularInput)) {
                points.forEach(point -> {
                    point.setDetailId(regularInput.getDetailId());
                    point.setPid(regularInput.getId());
                });
                this.saveBatch(points);
            }
            return;
        }else {
            this.updateById(regularInput);
        }
        // 更新检修测量项项点
        // 根据测量项点是否有id，判断是否是新数据
        List<RegularInput> updates = points.stream().filter(point -> StringUtils.isNotBlank(point.getId())).collect(Collectors.toList());
        List<RegularInput> inserts = points.stream().filter(point -> StringUtils.isBlank(point.getId())).collect(Collectors.toList());

        if (!inserts.isEmpty()) {
            inserts.forEach(point -> {
                point.setDetailId(regularInput.getDetailId());
                point.setPid(regularInput.getId());
            });
            this.saveBatch(inserts);
        }

        if (!updates.isEmpty()) {
            this.updateBatchById(updates);
        }
    }

    /**
     * 通过修程ID查询该修程下所有测量项
     * @param regularId
     * @return
     */
    @Override
    public List<RegularInput> listInputByRegular(String regularId) {
        // 查询所有有测量需求的检修项
        List<RegularDetail> regularDetailList = regularDetailMapper
                .selectList(new LambdaQueryWrapper<RegularDetail>()
                .eq(RegularDetail::getRegularId,regularId).eq(RegularDetail::getMeasure,"1"));

        Set<String> detailIds = regularDetailList.stream()
                .map(RegularDetail::getId)
                .collect(Collectors.toSet());
        if (detailIds.isEmpty()) {
            return Collections.emptyList();
        }

        // 查询此规程下所有涉及到的测量项
        List<RegularInput> regularInputList = baseMapper.selectList(new LambdaQueryWrapper<RegularInput>()
                .in(RegularInput::getDetailId,detailIds));
        // 优化 HashMap 初始容量，减少扩容开销
        Map<String, RegularInput> typeMap = new HashMap<>(regularInputList.size());
        // 使用 forEach 填充 Map，代码更简洁
        regularInputList.forEach(type -> typeMap.put(type.getId(), type));

        List<RegularInput> rootList = new ArrayList<>();
        for (RegularInput input : regularInputList) {
            String pid = input.getPid();
            if (pid == null || pid.trim().isEmpty()) {
                rootList.add(input);
            } else {
                RegularInput parent = typeMap.get(pid);
                if (parent != null) {
                    // 使用 computeIfAbsent 简化子列表初始化
                    parent.setPoints(Optional.ofNullable(parent.getPoints()).orElseGet(ArrayList::new));
                    parent.getPoints().add(input);
                }
            }
        }

        return rootList;
    }

}
