package cn.cecep.talroad.service.impl.analysis;

import cn.cecep.talroad.domain.analysis.BCoDischargePlanInfo;
import cn.cecep.talroad.mapper.analysis.BCoDischargePlanInfoMapper;
import cn.cecep.talroad.service.analysis.BCoDischargePlanInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.common.util.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class BCoDischargePlanInfoServiceImpl extends ServiceImpl<BCoDischargePlanInfoMapper, BCoDischargePlanInfo> implements BCoDischargePlanInfoService{

    @Override
    public int batchInsert(List<BCoDischargePlanInfo> list) {
        return baseMapper.batchInsert(list);
    }

    @Override
    public List<BCoDischargePlanInfo> selectAllDeviceService(String factoryId, Integer planId) {
        return  baseMapper.selectAllDevice(factoryId,planId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePlanInfo(List<BCoDischargePlanInfo> infos,Integer planId) {
        List<BCoDischargePlanInfo> collect = infos.stream().filter(info ->
                (info.getPlanEndTime() == null || info.getPlanStartTime() == null)).collect(Collectors.toList());
        if(collect.size()>0) {
            if(collect.stream().anyMatch(info -> info.getId() != null)) {
                baseMapper.deleteBatchIds(collect.stream().map(BCoDischargePlanInfo::getId).filter(Objects::nonNull).collect(Collectors.toList()));
            }
        }
        infos.removeAll(collect);
        if(CollectionUtils.isNotEmpty(infos)) {
            infos.forEach(i->{
                if(i.getId()==null){
                    i.setPlanId(planId);
                }
            });
            return saveOrUpdateBatch(infos);
        }else {
            return true;
        }
    }
}
