/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.paln.task.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.api.UserClent;
import com.tofly.api.UserTaskClient;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.*;
import com.tofly.gpsboot.mapper.plan.PlanFactoryMapper;
import com.tofly.gpsboot.service.car.CarBaseinfoService;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.gpsboot.service.mq.IMessageRecipientService;
import com.tofly.gpsboot.service.paln.*;
import com.tofly.gpsboot.service.paln.task.PlanFactoryService;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.paln.task.PlanchildService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.car.CarBaseinfo;
import com.tofly.pojo.message.Messagepush;
import com.tofly.pojo.message.Usertask;
import com.tofly.pojo.plan.*;
import com.tofly.pojo.plan.dto.PlanDeviceDTO;
import com.tofly.pojo.statement.dto.InspectionStatementDto;
import com.tofly.pojo.statement.vo.MaintenancePlanVo;
import groovy.transform.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * 计划下发厂站设备关联
 *
 * @author admin
 * @date Thu Mar 25 00:00:00 CST 2021
 */
@Service("planFactoryService")
@Slf4j
public class PlanFactoryServiceImpl extends ServiceImpl<PlanFactoryMapper, PlanFactory> implements PlanFactoryService {
    @Autowired
    private PlanchildService planchildService;
    @Autowired
    private PlantypeService plantypeService;
    @Autowired
    private PlanchildtypeService planchildtypeService;
    @Autowired
    private UserTaskClient userTaskClient;
    @Autowired
    private UserClent userClent;
    @Autowired
    private PlanService planService;
    @Autowired
    private IFileInfoService iFileInfoService;
    @Value("${xrty.ftp.planFactory}")
    private String planFactoryPath;
    @Value("${xrty.ftp.workingCondition}")
    private String workingConditionPath;
    @Autowired
    private TfYwpnPlanCartouserService planCartouserService;
    @Autowired
    private CarBaseinfoService carBaseinfoService;
    @Autowired
    private TfYwpnWorkingConditionService workingConditionService;
    @Autowired
    private TfYwpnStationReportService stationReportService;
    @Value("${gps.plan.app.planRecord}")
    private String planRecord;
    @Autowired
    private IMessageRecipientService messageRecipientService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Synchronized
    public Boolean senPlanFactory(List<PlanFactory> planFactoryList, Long userId) {
        // 相关巡检完成率计算
        // 获取当前用户Id
        Long userid = SecurityUtils.getUserId() == null ? userId : SecurityUtils.getUserId();
        // 根据传入参数 点id 获取对应点列表 且为没到位
        List<PlanFactory> pointTempList = this.list(new QueryWrapper<PlanFactory>().lambda()
                .in(PlanFactory::getId, planFactoryList.stream().map(PlanFactory::getId).collect(Collectors.toList()))
                .eq(PlanFactory::getIsOver, IsPlaceEnum.IS_PLACE_YES.getCode()));
        // 赋值点到为状态为1 更新当前时间
        pointTempList.forEach(f -> {
            f.setIsOver(IsPlaceEnum.IS_PLACE_NO.getCode());
            f.setOverDate(new Date());
            f.setOverUser(userid);
        });
        // 传入参数 按照计划ID分组
        Map<Long, List<PlanFactory>> collect = planFactoryList.stream().collect(Collectors.groupingBy(PlanFactory::getPlanId, Collectors.toList()));
        log.info("collect:{}", JSON.toJSONString(collect));
        // 子计划数据源 按照计划id分组(由于根据用户查询,计划中的子计划只能有一个)
        Map<Long, Planchild> planChildMap = planchildService.list(new QueryWrapper<Planchild>().lambda()
                .eq(Planchild::getRespUser, userid)
                .in(Planchild::getPlanId, collect.keySet()))
                .stream().collect(Collectors.toMap(Planchild::getPlanId, a -> a, (k1, k2) -> k2));
        log.info("planChildMap:{}", JSON.toJSONString(planChildMap));

        // 获取对应计划id/巡查类型 计划类型列表
        List<Plantype> planTypeList = plantypeService.list(new QueryWrapper<Plantype>().lambda()
                .in(Plantype::getPlanId, collect.keySet())
                .in(Plantype::getTypeId, planFactoryList.stream().map(PlanFactory::getInspectTypeId).collect(Collectors.toSet())));
        // 按照计划id/巡查类型分组
        Map<Long, Map<Long, List<Plantype>>> map = planTypeList.stream().collect(Collectors.groupingBy(Plantype::getPlanId, Collectors.groupingBy(Plantype::getTypeId)));

        // 获取对应id/用户/巡查类型 子计划类型列表
        List<Planchildtype> planChildTypeList = planchildtypeService.list(new QueryWrapper<Planchildtype>().lambda()
                .in(Planchildtype::getPlanId, collect.keySet())
                .eq(Planchildtype::getUserId, userid)
                .in(Planchildtype::getTypeId, planFactoryList.stream().map(PlanFactory::getInspectTypeId).collect(Collectors.toSet())));
        // 按照计划id/用户/巡查类型分组
        Map<Long, Map<Long, Map<Long, List<Planchildtype>>>> mapChild = planChildTypeList.stream().collect(Collectors.groupingBy(Planchildtype::getPlanId, Collectors.groupingBy(Planchildtype::getUserId, Collectors.groupingBy(Planchildtype::getTypeId))));
        List<Plantype> updatePlanTypeList = new ArrayList<>();
        List<Planchildtype> updateSavePlanChildList = new ArrayList<>();
        // 更新计划类型完成
        collect.forEach((k, v) -> {
            // 子计划
            Planchild planchild = planChildMap.get(k);
            // 按照巡查类型分组
            Map<Long, List<PlanFactory>> mapMap = v.stream().filter(e -> e.getInspectTypeId() != null).collect(Collectors.groupingBy(PlanFactory::getInspectTypeId));
            mapMap.forEach((f, g) -> {
                List<Plantype> plantypeLists = map.get(k).get(f);
                if (null != plantypeLists && plantypeLists.size() > 0) {
                    Plantype one = plantypeLists.get(0);
                    Float completionRate = one.getCompletionRate();
                    BigDecimal overCount = one.getOverCount();
                    BigDecimal totalCount = one.getTotalCount();
                    BigDecimal overNum = (overCount == null ? BigDecimal.ZERO : overCount).add(BigDecimal.valueOf(g.size()));
                    BigDecimal multiply = overNum.divide(totalCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    // 漏损率
                    BigDecimal leakageRate = BigDecimal.ZERO;
                    if (null != completionRate && completionRate > 0) {
                        leakageRate = totalCount.multiply(overCount).divide(BigDecimal.valueOf(completionRate), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    }
                    one.setLeakageRate(leakageRate.floatValue());
                    one.setOverCount(overNum);
                    one.setPercentRate(multiply.floatValue());
                    updatePlanTypeList.add(one);

                    // 个人完成率
                    List<Planchildtype> list = null;
                    if (mapChild != null && mapChild.size() != 0) {
                        list = mapChild.get(k).get(userid).get(f);
                    }
                    Planchildtype planchildtype = new Planchildtype();
                    if (null != list && list.size() > 0) {
                        Planchildtype child = list.get(0);
                        planchildtype.setId(child.getId());
                        planchildtype.setOverCount(child.getOverCount().add(BigDecimal.valueOf(g.size())));
                        planchildtype.setPercentRate(planchildtype.getOverCount().divide(totalCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).floatValue());
                    } else {
                        planchildtype.setOverCount(overNum);
                        planchildtype.setPercentRate(multiply.floatValue());
                    }
                    planchildtype.setTypeId(f);
                    planchildtype.setPlanId(k);
                    planchildtype.setPlanChildId(planchild.getId());
                    planchildtype.setUserId(planchild.getRespUser());
                    planchildtype.setTotalCount(totalCount);
                    planchildtype.setCompletionRate(one.getCompletionRate());
                    planchildtype.setTypeId(one.getTypeId());
                    updateSavePlanChildList.add(planchildtype);
                }
            });
        });

        // 更新完成率
        plantypeService.saveOrUpdateBatch(updatePlanTypeList);
        planchildtypeService.saveOrUpdateBatch(updateSavePlanChildList);

//        // 存入完成计划id
//        Set<Long> overPlanList = new HashSet<>();
//        // 判断当前计划对应的类型计划是否达到对应的计划完成率
//        collect.keySet().forEach(k -> {
//            List<Plantype> plantypes = plantypeService.list(new QueryWrapper<Plantype>().lambda().eq(Plantype::getPlanId, k));
//            if (null != plantypes && plantypes.size() > 0) {
//                int size = plantypes.size();
//                AtomicInteger overNum = new AtomicInteger();
//                plantypes.forEach(planType -> {
//                    float completionRate = planType.getCompletionRate()==null?0:planType.getCompletionRate();
//                    float percent = planType.getPercentRate()==null?0:planType.getPercentRate();
//                    if (completionRate <= percent) {
//                        overNum.set(overNum.get() + 1);
//                    }
//                });
//                if (size == overNum.get()) {
//                    overPlanList.add(k);
//                    // 待办事项处理
//                    Usertask usertask = new Usertask();
//                    usertask.setTableName(MessageTopicEnum.TASK_PLAN_SEND.getTableName());
//                    usertask.setTableId(k);
//                    List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
//                    if (null != result && result.size() > 0) {
//                        result.forEach(task -> {
//                            task.setHandleTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
//                            task.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_COMPLETED.getCode());
//                            userTaskClient.updateById(task);
//                        });
//
//                    }
//                }
//            }
//
//
//        });
//
//        if (overPlanList.size() > 0) {
//            // 更新计划及子计划
//            planService.update(new UpdateWrapper<Plan>().lambda().in(Plan::getId, overPlanList)
//                    .set(Plan::getPlanState, PlanStateEnum.PLAN_STATE_PLAN_COMPLETE.getCode()));
//            // 主计划完成 批量修改主计划下对应子计划状态
//            planchildService.update(new UpdateWrapper<Planchild>().lambda().in(Planchild::getPlanId, overPlanList)
//                    .set(Planchild::getPlanState, IsPlanChildStateEnum.PLAN_STATE_PLAN_COMPLETE.getCode()));
//        }

        return this.updateBatchById(pointTempList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePlanFactory(List<MultipartFile> fileList,
                                     List<MultipartFile> looksPhoto,
                                     List<MultipartFile> pretreatmentPhoto,
                                     List<MultipartFile> twoTankPhoto,
                                     List<MultipartFile> outWaterOpenChannel,
                                     List<MultipartFile> flowmeter,
                                     List<MultipartFile> sample,
                                     List<MultipartFile> aerationTankPhoto,
                                     PlanFactory planFactory,
                                     Long userId,
                                     TfYwpnWorkingCondition workingCondition,
                                     TfYwpnStationReport stationReport) {
        // 厂站巡检异常设备上报
        if (planFactory.getId() == null) {
            List<PlanFactory> query = this.list(new QueryWrapper<PlanFactory>().lambda()
                    .eq(PlanFactory::getPlanId, planFactory.getPlanId())
                    .eq(PlanFactory::getBelongStationId, planFactory.getBelongStationId())
                    .isNull(PlanFactory::getDeviceId)
                    .eq(PlanFactory::getIsOver, "0"));
            List<PlanFactory> queryNoError = this.list(new QueryWrapper<PlanFactory>().lambda()
                    .eq(PlanFactory::getPlanId, planFactory.getPlanId())
                    .eq(PlanFactory::getBelongStationId, planFactory.getBelongStationId())
                    .isNull(PlanFactory::getDeviceId)
                    .eq(PlanFactory::getIsDeviceError, "0"));
            // 1.厂站未到位，第一次走异常设备上报时厂站巡检数据是否到位状态和是否异常状态需更改为1并走到位逻辑
            // 2.厂站已到位并且无异常设备上报，走异常设备上报时更改厂站是否异常状态更改为1
            if (CollUtil.isNotEmpty(query)) {
                List<PlanFactory> planFactoryList = new ArrayList<>();
                planFactoryList.add(query.get(0));
                PlanFactory planFactoryUp = query.get(0);
                planFactoryUp.setIsDeviceError("1");
                planFactoryUp.setId(query.get(0).getId());
                this.updateById(planFactoryUp);
                this.senPlanFactory(planFactoryList, userId);
            } else if(CollUtil.isNotEmpty(queryNoError)) {
                PlanFactory planFactoryUp = queryNoError.get(0);
                planFactoryUp.setIsDeviceError("1");
                planFactoryUp.setId(queryNoError.get(0).getId());
                this.updateById(planFactoryUp);
            }
            StringBuilder files = iFileInfoService.saveFileList(fileList, planFactoryPath, "tf_ywpn_plan_factory");
            planFactory.setFileIds(StringUtils.isBlank(files)? null : files.toString());
            return this.save(planFactory);
        }
        List<PlanFactory> query = this.list(new QueryWrapper<PlanFactory>().lambda()
                .eq(PlanFactory::getPlanId, planFactory.getPlanId())
                .eq(PlanFactory::getBelongStationId, planFactory.getBelongStationId())
                .isNull(PlanFactory::getDeviceId)
                .eq(PlanFactory::getIsOver, "1"));
        StringBuilder files = iFileInfoService.saveFileList(fileList, planFactoryPath, "tf_ywpn_plan_factory");
        if (StringUtils.isNotBlank(files)) {
            if (StringUtils.isNotBlank(planFactory.getFileIds())) {
                planFactory.setFileIds(planFactory.getFileIds() + "," + files);
            } else {
                planFactory.setFileIds(files.toString());
            }
        }
        baseMapper.updateById(planFactory);
        if (workingCondition != null) {
            TfYwpnWorkingCondition workingConditionQuery = workingConditionService.getOne(new QueryWrapper<TfYwpnWorkingCondition>().lambda()
                    .eq(TfYwpnWorkingCondition::getPlanFactoryId, planFactory.getId()));
            workingCondition.setPlanFactoryId(planFactory.getId());
            StringBuilder looksPhotoIds = iFileInfoService.saveFileList(looksPhoto, workingConditionPath, "tf_ywpn_working_condition");
            workingCondition.setLooksPhoto(StringUtils.isBlank(looksPhotoIds)? null : looksPhotoIds.toString());
            StringBuilder pretreatmentPhotoIds = iFileInfoService.saveFileList(pretreatmentPhoto, workingConditionPath, "tf_ywpn_working_condition");
            workingCondition.setPretreatmentPhoto(StringUtils.isBlank(pretreatmentPhotoIds)? null : pretreatmentPhotoIds.toString());
            StringBuilder twoTankPhotoIds = iFileInfoService.saveFileList(twoTankPhoto, workingConditionPath, "tf_ywpn_working_condition");
            workingCondition.setTwoTankPhoto(StringUtils.isBlank(twoTankPhotoIds)? null : twoTankPhotoIds.toString());
            StringBuilder outWaterOpenChannelIds = iFileInfoService.saveFileList(outWaterOpenChannel, workingConditionPath, "tf_ywpn_working_condition");
            workingCondition.setOutWaterOpenChannel(StringUtils.isBlank(outWaterOpenChannelIds)? null : outWaterOpenChannelIds.toString());
            StringBuilder flowmeterIds = iFileInfoService.saveFileList(flowmeter, workingConditionPath, "tf_ywpn_working_condition");
            workingCondition.setFlowmeter(StringUtils.isBlank(flowmeterIds)? null : flowmeterIds.toString());
            StringBuilder sampleIds = iFileInfoService.saveFileList(sample, workingConditionPath, "tf_ywpn_working_condition");
            workingCondition.setSample(StringUtils.isBlank(sampleIds)? null : sampleIds.toString());
            StringBuilder aerationTankPhotoIds = iFileInfoService.saveFileList(aerationTankPhoto, workingConditionPath, "tf_ywpn_working_condition");
            workingCondition.setAerationTankPhoto(StringUtils.isBlank(aerationTankPhotoIds)? null : aerationTankPhotoIds.toString());
            if (workingConditionQuery != null) {
                workingConditionService.update(workingCondition,
                        new QueryWrapper<TfYwpnWorkingCondition>().lambda().eq(TfYwpnWorkingCondition::getPlanFactoryId, planFactory.getId()));
            } else {
                workingConditionService.save(workingCondition);
            }
        }
        if (stationReport != null) {
            // 推送系统消息给指定人
            if (stationReport.getIsReport().equals("1") && StringUtils.isNotBlank(stationReport.getReportUserIds())) {
                Messagepush messagepush = new Messagepush();
                messagepush.setTopic(MessageTopicEnum.RESULT_PLAN_FACTORY.getTopic());
                messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_INSPECTION.getCode());
                messagepush.setTableName(MessageTopicEnum.RESULT_PLAN_FACTORY.getTableName());
                messagepush.setTableId(planFactory.getId());
                String sewageName = this.baseMapper.getSewageName(planFactory.getBelongStationId());
                messagepush.setMessage("巡检人: " + SecurityUtils.getUserName() + ",巡检厂站: " + sewageName + ",巡检结果: " + "巡检完毕！");

                // 跳转到巡检计划历史查询界面
                messagepush.setRouteIpApp(planRecord);
                List<Long> messageUserIds = Arrays.stream(stationReport.getReportUserIds().split(Constant.CSV)).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                // 消息与接收人信息处理
                messageUserIds.forEach(messageUserId -> messageRecipientService.setMessageRecipient(messagepush, messageUserId));

                stationReport.setReportContent(messagepush.getMessage());
            }
            TfYwpnStationReport stationReportQuery = stationReportService.getOne(new QueryWrapper<TfYwpnStationReport>().lambda()
                    .eq(TfYwpnStationReport::getPlanFactoryId, planFactory.getId()));
            stationReport.setPlanFactoryId(planFactory.getId());
            if (stationReportQuery != null) {
                stationReportService.update(stationReport,
                        new QueryWrapper<TfYwpnStationReport>().lambda().eq(TfYwpnStationReport::getPlanFactoryId, planFactory.getId()));
            } else {
                stationReportService.save(stationReport);
            }
        }
        if (CollUtil.isNotEmpty(query)) {
            return true;
        }
        List<PlanFactory> planFactoryList = new ArrayList<>();
        planFactoryList.add(planFactory);
        return this.senPlanFactory(planFactoryList, userId);
    }

    @Override
    public Boolean updatePlanOver(Long planId) {
        // 判断当前计划对应的类型计划是否达到对应的计划完成率
        List<Plantype> plantypes = plantypeService.list(new QueryWrapper<Plantype>().lambda().eq(Plantype::getPlanId, planId));
        if (null != plantypes && plantypes.size() > 0) {
            int size = plantypes.size();
            AtomicInteger overNum = new AtomicInteger();
            // 计算完成个数
            plantypes.forEach(planType -> {
                float completionRate = planType.getCompletionRate()==null?0:planType.getCompletionRate();
                float percent = planType.getPercentRate()==null?0:planType.getPercentRate();
                if (completionRate <= percent) {
                    overNum.set(overNum.get() + 1);
                }
            });
            // 完成率达标
            if (size == overNum.get()) {
                // 待办事项处理
                Usertask usertask = new Usertask();
                usertask.setTableName(MessageTopicEnum.TASK_PLAN_SEND.getTableName());
                usertask.setTableId(planId);
                List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
                // 待办置为已完成
                if (null != result && result.size() > 0) {
                    result.forEach(task -> {
                        task.setHandleTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
                        task.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_COMPLETED.getCode());
                        userTaskClient.updateById(task);
                    });
                }
                // 更新计划及子计划
                planService.update(new UpdateWrapper<Plan>().lambda().eq(Plan::getId, planId)
                        .set(Plan::getPlanState, PlanStateEnum.PLAN_STATE_PLAN_COMPLETE.getCode()));
                // 主计划完成 批量修改主计划下对应子计划状态
                planchildService.update(new UpdateWrapper<Planchild>().lambda().eq(Planchild::getPlanId, planId)
                        .set(Planchild::getPlanState, IsPlanChildStateEnum.PLAN_STATE_PLAN_COMPLETE.getCode()));
                List<TfYwpnPlanCartouser> planCartouserList = planCartouserService.list(new QueryWrapper<TfYwpnPlanCartouser>().lambda()
                        .eq(TfYwpnPlanCartouser::getPlanId,planId));
                if(planCartouserList == null) {
                    return true;
                }
                List<TfYwpnPlanCartouser> updateList = new ArrayList<>();
                List<CarBaseinfo> updateCarIdList = new ArrayList<>();
                String endDate;
                for (TfYwpnPlanCartouser planCartouser : planCartouserList) {
                    endDate = planCartouser.getEndDate();
                    String nowDate = DateUtil.getDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
                    if (StringUtils.isNotBlank(endDate)) {
                        planCartouser.setEndDate(endDate + "," + nowDate);
                    } else {
                        planCartouser.setEndDate(nowDate);
                    }
                    updateList.add(planCartouser);
                    CarBaseinfo carBaseinfo = new CarBaseinfo();
                    carBaseinfo.setId(planCartouser.getCarId());
                    carBaseinfo.setIsBind("0");
                    updateCarIdList.add(carBaseinfo);
                }
                planCartouserService.updateBatchById(updateList);
                carBaseinfoService.updateBatchById(updateCarIdList);
            } else {
                throw new ToflyDeniedException("完成率不达标，不允许结束该计划");
            }
        }
        return true;
    }

    @Override
    public Page<PlanFactory> getPlanDeviceList(Page page, PlanDeviceDTO dto) {
        if (StringUtils.isBlank(dto.getIsStation())) {
            dto.setIsStation("0");
        }
        Page<PlanFactory> planFactoryPage = null;
        if (dto.getIsStation().equals("1")) {
            if(null!=dto.getPlanId()){
                planFactoryPage = baseMapper.getPlanSewageList(page,dto);
                planFactoryPage.getRecords().forEach(info -> {
                    PlanDeviceDTO querydto = new PlanDeviceDTO();
                    querydto.setBelongStationId(info.getBelongStationId());
                    List<PlanFactory> allDeviceList = baseMapper.getDeviceInfoBy(querydto);
                    if (CollUtil.isEmpty(allDeviceList)) {
                        info.setErrorDeviceNum(0);
                        info.setNormalDeviceNum(0);
                        info.setAllDeviceNum(0);
                        return;
                    }
                    List<PlanFactory> errorDeviceList = this.list(new QueryWrapper<PlanFactory>().lambda()
                            .eq(PlanFactory::getPlanId, dto.getPlanId())
                            .eq(PlanFactory::getBelongStationId, info.getBelongStationId())
                            .isNotNull(PlanFactory::getDeviceId));
                    if (CollUtil.isEmpty(errorDeviceList)) {
                        info.setErrorDeviceNum(0);
                        info.setNormalDeviceNum(allDeviceList.size());
                    } else {
                        Set<Long> errorDeviceIds = errorDeviceList.stream().map(PlanFactory::getDeviceId).collect(Collectors.toSet());
                        allDeviceList.removeIf(item -> errorDeviceIds.contains(item.getDeviceId()));
                        allDeviceList.addAll(errorDeviceList);
                        info.setErrorDeviceNum(errorDeviceList.size());
                        info.setNormalDeviceNum(allDeviceList.size() - errorDeviceList.size());
                    }
                    info.setAllDeviceNum(allDeviceList.size());
                    info.setPlanDeviceList(allDeviceList);
                });
            } else {
                planFactoryPage = baseMapper.getSewageList(page,dto);
            }
        } else if(dto.getIsStation().equals("0")) {
            if(null!=dto.getPlanId()){
                planFactoryPage =  baseMapper.getPlanDeviceList(page,dto);
            } else {
                planFactoryPage =  baseMapper.getDeviceList(page,dto);
            }
        }
        if (planFactoryPage != null && CollUtil.isNotEmpty(planFactoryPage.getRecords())) {
            planFactoryPage.getRecords().forEach(info -> {
                info.setWorkingCondition(workingConditionService.getOne(new QueryWrapper<TfYwpnWorkingCondition>().lambda()
                    .eq(TfYwpnWorkingCondition::getPlanFactoryId, info.getId())));
                info.setStationReport(stationReportService.getOne(new QueryWrapper<TfYwpnStationReport>().lambda()
                        .eq(TfYwpnStationReport::getPlanFactoryId, info.getId())));
            });

        }
        return planFactoryPage;
    }

    @Override
    public Page<MaintenancePlanVo> getMaintenanceStatisticsPlan(Page page, InspectionStatementDto dto) {
        return baseMapper.getMaintenanceStatisticsPlan(page,dto);
    }

}
