package com.ruoyi.project.business.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.project.business.domain.TpCaseElevator;
import com.ruoyi.project.business.domain.TpParaValidationElevator;
import com.ruoyi.project.business.dto.TpParaValidationDto;
import com.ruoyi.project.business.dto.TpParaValidationElevatorDto;
import com.ruoyi.project.business.mapper.TpParaValidationElevatorMapper;
import com.ruoyi.project.business.service.ITpParaValidationElevatorService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author jubs
 */
@Service
public class TpParaValidationElevatorServiceImpl extends ServiceImpl<TpParaValidationElevatorMapper, TpParaValidationElevator> implements ITpParaValidationElevatorService {


    @Override
    public List<TpParaValidationElevatorDto> initData(Long paraValidationId) {
        return this.getBaseMapper().initData(paraValidationId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchChangeRelation(TpParaValidationDto param) {
        List<Long> elevatorIds = param.getElevatorModelIds();
        if (CollectionUtils.isEmpty(elevatorIds)) {
            throw new ServiceException("梯型不能为空");
        }
        List<Long> caseIds = param.getRelatedCaseIds();
        if (CollectionUtils.isEmpty(caseIds)) {
            throw new ServiceException("校验规则不能为空");
        }

        remove(Wrappers.<TpParaValidationElevator>lambdaQuery()
                .in(TpParaValidationElevator::getParaValidationId, caseIds)
                .in(TpParaValidationElevator::getElevatorModelId, elevatorIds)
        );

        if (param.getIsAppend()){
            List<TpParaValidationElevator> caseElevators = new ArrayList<>();
            caseIds.forEach(caseId -> {
                caseElevators.addAll(elevatorIds.stream().map(elevatorId -> {
                    TpParaValidationElevator item = new TpParaValidationElevator();
                    item.setParaValidationId(caseId);
                    item.setElevatorModelId(elevatorId);
                    return item;
                }).collect(Collectors.toList()));
            });
            saveBatch(caseElevators);
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearAll() {
        baseMapper.clearAll();
    }
}
