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

import cn.cecep.talroad.domain.analysis.BMaintenancePlanInfo;
import cn.cecep.talroad.mapper.analysis.BMaintenancePlanInfoMapper;
import cn.cecep.talroad.service.analysis.BMaintenancePlanInfoService;
import cn.cecep.talroad.vo.query.analysis.BMaintenancePlanQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class BMaintenancePlanInfoServiceImpl extends ServiceImpl<BMaintenancePlanInfoMapper, BMaintenancePlanInfo> implements BMaintenancePlanInfoService{

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePlanInfo(List<BMaintenancePlanInfo> infos,Integer planId) {
        List<BMaintenancePlanInfo> collect = infos.stream().filter(info ->
                (info.getPlanEndTime() == null || info.getPlanStartTime() == null)).collect(Collectors.toList());
        if(collect.size()>0) {
            if(collect.stream().anyMatch(c -> c.getId() != null)) {
                baseMapper.deleteBatchIds(collect.stream().map(BMaintenancePlanInfo::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;
        }
    }

    @Override
    public List<BMaintenancePlanInfo> selectAllDeviceService(String factoryId,Integer planId) {

        return  baseMapper.selectAllDevice(factoryId,planId);
    }

    @Override
    public List<BMaintenancePlanInfo> infoPageList(Page<BMaintenancePlanInfo> page, String factoryId, BMaintenancePlanQuery bMaintenancePlanQuery) {
        List<BMaintenancePlanInfo> list = new ArrayList<>();
        if(page != null){
            list = baseMapper.infoPageList(page,factoryId,bMaintenancePlanQuery.getPlanId(),bMaintenancePlanQuery.getDeviceType(),bMaintenancePlanQuery.getDeviceName());
            page.setRecords(list);
        }
        return list;
    }
}
