package com.ruoyi.zdsz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.DynamicName;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.framework.handler.MonthTableNameHandler;
import com.ruoyi.zdsz.domain.*;
import com.ruoyi.zdsz.domain.bo.*;
import com.ruoyi.zdsz.domain.vo.*;
import com.ruoyi.zdsz.mapper.*;
import com.ruoyi.zdsz.service.IZEngiineeringPhotoService;
import com.ruoyi.zdsz.service.IZEngineeringInfoService;
import com.ruoyi.zdsz.service.IZEngineeringNodeService;
import com.ruoyi.zdsz.service.IZEngineeringReviewService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.util.stereotypes.Lazy;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.hutool.core.date.DateUtil.format;

/**
 * 工程节点Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-27
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ZEngineeringNodeServiceImpl implements IZEngineeringNodeService {

    private final ZEngineeringNodeMapper baseMapper;
    @Autowired
    private IZEngineeringInfoService izEngineeringInfoService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private IZEngineeringReviewService izEngineeringReviewService;
    @Autowired
    private IZEngiineeringPhotoService izEngiineeringPhotoService;
    @Autowired
    private ZEngineeringCivilMapper zEngineeringCivilMapper;
    @Autowired
    private ZEngineeringReviewMapper zEngineeringReviewMapper;
    @Autowired
    private ZComprehensiveMapper zComprehensiveMapper;
    @Autowired
    private ZEngineeringInfoMapper zEngineeringInfoMapper;
    @Autowired
    private ZEngineeringMaterialMapper zEngineeringMaterialMapper;
    @Autowired
    private  ZEnginMaterialQualityMapper zEnginMaterialQualityMapper;


    /**
     * 查询工程节点
     */
    @Override
    public ZEngineeringNodeVo queryById(String id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    //    @Async("threadPoolTaskExecutor")
    public ZEngineeringNodeBo query(ZEngineeringNodeBo bo) {
        LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCivliId()), ZEngineeringNode::getCivliId, bo.getCivliId());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), ZEngineeringNode::getType, bo.getType());
        System.out.println(LoginHelper.getUserType());
        System.out.println(UserType.SYS_USER);
        //        if (!LoginHelper.getUserType().equals(UserType.SYS_USER))
        //            lqw.eq(ZEngineeringNode::getCreateBy, LoginHelper.getLoginUser().getUsername());
        ZEngineeringNode zEngineeringNode = baseMapper.selectOne(lqw);
        //        ZEngineeringNode zEngineeringNodeVo=baseMapper.selectById(bo.getId());
        if (zEngineeringNode == null) {
            return null;
        }
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        //        ZEngineeringNodeBo zEngineeringNodeBo= BeanUtil.toBean(zEngineeringNode, ZEngineeringNodeBo.class);
        BeanUtil.copyProperties(zEngineeringNode, zEngineeringNodeBo, "id");
        zEngineeringNodeBo.setId(zEngineeringNode.getId());
        List<ZEngineeringInfoBo> zEngineeringInfoBo = izEngineeringInfoService.query(zEngineeringNodeBo);
        ZEngineeringReviewBo zEngineeringReview = izEngineeringReviewService.query(zEngineeringNodeBo);
        zEngineeringNodeBo.setReviewStatus(ObjectUtils.isEmpty(zEngineeringReview) ? "0" : zEngineeringReview.getReviewStatus());
        zEngineeringNodeBo.setReviewContent(ObjectUtils.isEmpty(zEngineeringReview) ? "0" : zEngineeringReview.getReviewContent());
        zEngineeringNodeBo.setId(zEngineeringNode.getId());
        zEngineeringNodeBo.setzEngineeringInfoBoList(zEngineeringInfoBo);
        return zEngineeringNodeBo;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    //    @Async("threadPoolTaskExecutor")
    public ZEngineeringNodeBo queryInsert(ZEngineeringNodeBo bo) {
        LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCivliId()), ZEngineeringNode::getCivliId, bo.getCivliId());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), ZEngineeringNode::getType, bo.getType());
        System.out.println(LoginHelper.getUserType());
        System.out.println(UserType.SYS_USER);
        //        if (!LoginHelper.getUserType().equals(UserType.SYS_USER))
        //            lqw.eq(ZEngineeringNode::getCreateBy, LoginHelper.getLoginUser().getUsername());
        ZEngineeringNode zEngineeringNode = baseMapper.selectOne(lqw);
        //        ZEngineeringNode zEngineeringNodeVo=baseMapper.selectById(bo.getId());
        if (zEngineeringNode == null) {
            return null;
        }
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        //        ZEngineeringNodeBo zEngineeringNodeBo= BeanUtil.toBean(zEngineeringNode, ZEngineeringNodeBo.class);
        BeanUtil.copyProperties(zEngineeringNode, zEngineeringNodeBo, "id");
        zEngineeringNodeBo.setId(zEngineeringNode.getId());
        List<ZEngineeringInfoBo> zEngineeringInfoBo = izEngineeringInfoService.queryInsert(zEngineeringNodeBo);
        ZEngineeringReviewBo zEngineeringReview = izEngineeringReviewService.query(zEngineeringNodeBo);
        zEngineeringNodeBo.setReviewStatus(ObjectUtils.isEmpty(zEngineeringReview) ? "0" : zEngineeringReview.getReviewStatus());
        zEngineeringNodeBo.setReviewContent(ObjectUtils.isEmpty(zEngineeringReview) ? "0" : zEngineeringReview.getReviewContent());
        zEngineeringNodeBo.setId(zEngineeringNode.getId());
        zEngineeringNodeBo.setzEngineeringInfoBoList(zEngineeringInfoBo);
        return zEngineeringNodeBo;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    //    @Async("threadPoolTaskExecutor")
    public ZEngineeringNodeBo Userquery(ZEngineeringNodeBo bo, String username) {
        LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCivliId()), ZEngineeringNode::getCivliId, bo.getCivliId());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), ZEngineeringNode::getType, bo.getType());
        //        if (!LoginHelper.isAdmin())
        //            lqw.eq(ZEngineeringNode::getCreateBy, username);
        ZEngineeringNode zEngineeringNode = baseMapper.selectOne(lqw);
        //        ZEngineeringNode zEngineeringNodeVo=baseMapper.selectById(bo.getId());
        if (zEngineeringNode == null) {
            return null;
        }
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        //        ZEngineeringNodeBo zEngineeringNodeBo= BeanUtil.toBean(zEngineeringNode, ZEngineeringNodeBo.class);
        BeanUtil.copyProperties(zEngineeringNode, zEngineeringNodeBo, "id");
        zEngineeringNodeBo.setId(zEngineeringNode.getId());
        List<ZEngineeringInfoBo> zEngineeringInfoBo = izEngineeringInfoService.query(zEngineeringNodeBo);
        zEngineeringNodeBo.setId(zEngineeringNode.getId());
        zEngineeringNodeBo.setzEngineeringInfoBoList(zEngineeringInfoBo);
        return zEngineeringNodeBo;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    public List<ZEngineeringNodeBo> queryListDetails(ZEngineeringNodeBo bo) {
        LambdaQueryWrapper<ZEngineeringNode> lqw = buildQueryWrapper(bo);
        List<ZEngineeringNode> zEngineeringNode = baseMapper.selectList(lqw);
        List<ZEngineeringNodeBo> zEngineeringNodeBoList = new ArrayList<>();
        zEngineeringNode.stream().forEach(item -> {
            ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
            BeanUtil.copyProperties(item, zEngineeringNodeBo, "id");
            zEngineeringNodeBo.setId(item.getId());
            List<ZEngineeringInfoBo> zEngineeringInfoBo = izEngineeringInfoService.query(zEngineeringNodeBo);
            zEngineeringNodeBo.setId(item.getId());
            zEngineeringNodeBo.setzEngineeringInfoBoList(zEngineeringInfoBo);
            zEngineeringNodeBoList.add(zEngineeringNodeBo);
        });
        return zEngineeringNodeBoList;
    }


    /**
     * 查询工程节点列表
     */
    @Override
    public TableDataInfo<ZEngineeringNodeVo> queryPageList(ZEngineeringNodeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZEngineeringNode> lqw = buildQueryWrapper(bo);
        Page<ZEngineeringNodeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询工程节点列表
     */
    @Override
    //    @DynamicName(spel = "#bo.createTime")
    public List<ZEngineeringNodeVo> queryList(ZEngineeringNodeBo bo) {
        LambdaQueryWrapper<ZEngineeringNode> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    public List<ZEngineeringNodeBo> queryNodeList(ZEngineeringCivil bo) {
        LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngineeringNode::getCivliId, bo.getId());
        List<ZEngineeringNode> zEngineeringNodeList = baseMapper.selectList(lqw);
        List<ZEngineeringNodeBo> zEngineeringNodeBoList = new ArrayList<>();
        zEngineeringNodeList.stream().forEach(item -> {
            ZEngineeringNodeBo zEngineeringNodeBo = BeanUtil.copyProperties(item, ZEngineeringNodeBo.class);
            zEngineeringNodeBo.setzEngineeringInfoBoList(izEngineeringInfoService.query(zEngineeringNodeBo));
            ZEngineeringReviewBo zEngineeringReviewBo = izEngineeringReviewService.query(zEngineeringNodeBo);
            if (!ObjectUtils.isEmpty(zEngineeringReviewBo)) {
                zEngineeringNodeBo.setReviewStatus(zEngineeringReviewBo.getReviewStatus());
            } else {
                zEngineeringNodeBo.setReviewStatus("0");
            }
            zEngineeringNodeBoList.add(zEngineeringNodeBo);
        });
        return zEngineeringNodeBoList;
    }

    private LambdaQueryWrapper<ZEngineeringNode> buildQueryWrapper(ZEngineeringNodeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCivliId()), ZEngineeringNode::getCivliId, bo.getCivliId());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), ZEngineeringNode::getType, bo.getType());
        return lqw;
    }

    @Override

    public String ZEngineeringReview(ZEngineeringNodeBo bo) {
        String userId = LoginHelper.getLoginUser().getUsername().toString();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        List<String> dateList = getMonthBetweenDates("2021-12", formatter.format(date));
        dateList.stream().forEach(item -> {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        getZEngineeringNodeList(item, userId, bo);
                        Thread.sleep(30000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
            };
            threadPoolTaskExecutor.execute(runnable);
        });
        return null;
    }

    @Override
    @Async
    public int batchReview(List<ZEngineeringCivil> zEngineeringCivilList, ZEngineeringNodeBo bo, String userId) {
        zEngineeringCivilList.forEach(item -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy_MM");
            LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item.getId()), ZEngineeringNode::getCivliId, item.getId());
            lqw.eq(StringUtils.isNotBlank(bo.getType()), ZEngineeringNode::getType, bo.getType());
            format.format(item.getCreateTime());
            MonthTableNameHandler.setData(format.format(item.getCreateTime()));
            ZEngineeringNode zEngineeringNode = baseMapper.selectOne(lqw);
            List<ZEngineeringReview> zEngineeringReviewList = new ArrayList<>();
            if (null != zEngineeringNode) {
                ZEngineeringReview zEngineeringReview = new ZEngineeringReview();
                zEngineeringReview.setReviewTime(new Date());
                zEngineeringReview.setReviewContent(bo.getReviewContent());
                zEngineeringReview.setReviewStatus(bo.getReviewStatus());
                zEngineeringReview.setReviewUser(userId);
                zEngineeringReview.setCreateTime(item.getCreateTime());
                zEngineeringReview.setEngInfoId(zEngineeringNode.getId());
                zEngineeringReviewList.add(zEngineeringReview);
                izEngineeringReviewService.Bacthinsert(zEngineeringReview);
                ZEngineeringReviewBo zEngineeringReviewBo = BeanUtil.copyProperties(zEngineeringReview, ZEngineeringReviewBo.class);
                izEngineeringReviewService.updateCivilStatus(item);
                //Civilinsert(zEngineeringReviewBo);

            }
            MonthTableNameHandler.removeData();
        });

        return 0;
    }

    @Override
    @Async
    @DynamicName(spel = "#zEngineeringCivilList[0].createTime")
    public int Civilinsert(List<ZEngineeringCivil> zEngineeringCivilList, ZEngineeringNodeBo bo, String UserId) {
        zEngineeringCivilList.forEach(item2 -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy_MM");
            LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringNode::getCivliId, item2.getId());
            lqw.eq(StringUtils.isNotBlank(bo.getType()), ZEngineeringNode::getType, bo.getType());
            format.format(item2.getCreateTime());
            MonthTableNameHandler.setData(format.format(item2.getCreateTime()));
            ZEngineeringNode zEngineeringNode = baseMapper.selectOne(lqw);
            //ZEngineeringNode zEngineeringNode = baseMapper.selectById(zEngineeringReviewBo.getEngInfoId());
            //        ZEngineeringCivil zEngineeringCivil= zEngineeringCivilMapper.selectById(zEngineeringNode.getCivliId());
            ZEngineeringCivilBo zEngineeringCivilBo = BeanUtil.copyProperties(item2, ZEngineeringCivilBo.class);
            ZEngineeringNodeBo zEngineeringNodeBo = BeanUtil.copyProperties(zEngineeringNode, ZEngineeringNodeBo.class);
            MonthTableNameHandler.setData(new SimpleDateFormat("yyyy_MM").format(item2.getCreateTime()));
            zEngineeringCivilBo.setzEngineeringNodeBo(Userquery(zEngineeringNodeBo, UserId));
            MonthTableNameHandler.removeData();
            //        zEngineeringCivilBo.setCreateTime(zEngineeringReviewBo.getCreateTime());
            //        izEngineeringReviewService.Civilinsert(zEngineeringCivil,zEngineeringReviewBo);
            areaMessageVo areaMessageVo = new areaMessageVo();
            if (zEngineeringCivilBo.getEnginClassification().equals("courtyard") || zEngineeringCivilBo.getEnginClassification().equals("overhead ")) {
                if (!"".equals(zEngineeringCivilBo.getBuildingId())) {
                    areaMessageVo = zEngineeringCivilMapper.getAreaMessage(zEngineeringCivilBo.getBuildingId());
                    areaMessageVo.setHouseId("未知");
                    areaMessageVo.setUnitId("未知");
                } else {
                    areaMessageVo = zEngineeringCivilMapper.getAreaName(zEngineeringCivilBo.getAreaId());
                    areaMessageVo.setHouseId("未知");
                    areaMessageVo.setUnitId("未知");
                    areaMessageVo.setBuildingId("未知");
                }

            } else {
                areaMessageVo = zEngineeringCivilMapper.getHouseMessage(zEngineeringCivilBo.getHouseId());
            }
            if (!ObjectUtils.isEmpty(areaMessageVo))
                BeanUtils.copyProperties(areaMessageVo, zEngineeringCivilBo);
            Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
            //            sysDictMap.get(zEngineeringCivilBo.getEnginType()).stream().forEach(item -> {
            //                if (item.getDictValue().equals(zEngineeringCivilBo.getCompletionStatus())) {
            //                    zEngineeringCivilBo.setCompletionStatus(item.getDictLabel());
            //                }
            //            });
            sysDictMap.get(zEngineeringCivilBo.getEnginType()).stream().forEach(item -> {
                if (item.getDictValue().equals(zEngineeringCivilBo.getEnginClassification())) {
                    zEngineeringCivilBo.setEnginClassification(item.getDictLabel());
                }
            });
            sysDictMap.get("engin_cycle").stream().forEach(item -> {
                if (item.getDictValue().equals(zEngineeringCivilBo.getEnginCycle())) {
                    zEngineeringCivilBo.setEnginCycle(item.getDictLabel());
                }
            });
            //        zEngineeringCivilBo.getzEngineeringNodeBo().setType(type);
            //        zEngineeringCivilBo.setEnginClassification(completionStatus);
            if (zEngineeringCivilBo.getEnginType().equals("old_renovation")) {
                zEngineeringCivilBo.setEnginType("旧改");
            } else if (zEngineeringCivilBo.getEnginType().equals("new_built")) {
                zEngineeringCivilBo.setEnginType("新建");
            }

            izEngiineeringPhotoService.write(zEngineeringCivilBo);
        });
        return 0;
    }

    @Override
    @Async
    public Integer batchNode(List<ZHouse> zHouseList, ZEngineeringCivilBo zEngineeringCivilBo, String userId) {
        zHouseList.stream().forEach(item -> {
            LambdaQueryWrapper<ZEngineeringCivil> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item.getAreaId()), ZEngineeringCivil::getAreaId, item.getAreaId());
            lqw.eq(ZEngineeringCivil::getBuildingId, item.getBuildingId());
            //        .isNull(!StringUtils.isNotBlank(item.getBuildingId()),ZEngineeringCivil::getBuildingId);
            lqw.eq(ZEngineeringCivil::getUnitId, item.getUnitId());
            //            .isNull(!StringUtils.isNotBlank(item.getUnitId()),ZEngineeringCivil::getUnitId);
            lqw.eq(ZEngineeringCivil::getHouseId, item.getId());
            //            .isNull(!StringUtils.isNotBlank(item.getId()),ZEngineeringCivil::getHouseId);
            lqw.eq(StringUtils.isNotBlank(zEngineeringCivilBo.getEnginCycle()), ZEngineeringCivil::getEnginCycle, zEngineeringCivilBo.getEnginCycle());
            lqw.eq(StringUtils.isNotBlank(zEngineeringCivilBo.getEnginType()), ZEngineeringCivil::getEnginType, zEngineeringCivilBo.getEnginType());
            lqw.eq(StringUtils.isNotBlank(zEngineeringCivilBo.getEnginClassification()), ZEngineeringCivil::getEnginClassification, zEngineeringCivilBo.getEnginClassification());
            ZEngineeringCivilVo zEngineeringCivilVo = zEngineeringCivilMapper.selectVoOne(lqw);
            if (!ObjectUtils.isEmpty(zEngineeringCivilVo)) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM");
                MonthTableNameHandler.setData(simpleDateFormat.format(zEngineeringCivilVo.getCreateTime()));
                LambdaQueryWrapper<ZEngineeringNode> lqw2 = Wrappers.lambdaQuery();
                lqw2.eq(StringUtils.isNotBlank(zEngineeringCivilVo.getId()), ZEngineeringNode::getCivliId, zEngineeringCivilVo.getId());
                lqw2.eq(StringUtils.isNotBlank(zEngineeringCivilBo.getType()), ZEngineeringNode::getType, zEngineeringCivilBo.getType());
                ZEngineeringNode zEngineeringNode = baseMapper.selectOne(lqw2);
                if (!ObjectUtils.isEmpty(zEngineeringNode)) {
                    ZEngineeringReview zEngineeringReview = new ZEngineeringReview();
                    zEngineeringReview.setReviewTime(new Date());
                    zEngineeringReview.setReviewStatus(zEngineeringCivilBo.getCompletionStatus());
                    zEngineeringReview.setReviewUser(userId);
                    zEngineeringReview.setEngInfoId(zEngineeringNode.getId());
                    zEngineeringReviewMapper.insert(zEngineeringReview);
                } else {
                    ZEngineeringNode zEngineeringNode1 = new ZEngineeringNode();
                    zEngineeringNode1.setCivliId(zEngineeringCivilVo.getId());
                    zEngineeringNode1.setType(zEngineeringCivilBo.getType());
                    baseMapper.insert(zEngineeringNode1);
                    ZEngineeringReview zEngineeringReview = new ZEngineeringReview();
                    zEngineeringReview.setReviewTime(new Date());
                    zEngineeringReview.setReviewStatus(zEngineeringCivilBo.getCompletionStatus());
                    zEngineeringReview.setReviewUser(userId);
                    zEngineeringReview.setEngInfoId(zEngineeringNode1.getId());
                    zEngineeringReviewMapper.insert(zEngineeringReview);
                }
                MonthTableNameHandler.removeData();
            } else {
                ZEngineeringCivil zEngineeringCivil = new ZEngineeringCivil();
                BeanUtils.copyProperties(zEngineeringCivilBo, zEngineeringCivil);
                BeanUtils.copyProperties(item, zEngineeringCivil);
                zEngineeringCivil.setId(null);
                zEngineeringCivil.setCompletionStatus("施工中");
                zEngineeringCivil.setHouseId(item.getId());
                zEngineeringCivilMapper.insert(zEngineeringCivil);
                ZEngineeringNode zEngineeringNode1 = new ZEngineeringNode();
                zEngineeringNode1.setCivliId(zEngineeringCivil.getId());
                zEngineeringNode1.setType(zEngineeringCivilBo.getType());
                baseMapper.insert(zEngineeringNode1);
                ZEngineeringReview zEngineeringReview = new ZEngineeringReview();
                zEngineeringReview.setReviewTime(new Date());
                zEngineeringReview.setReviewStatus(zEngineeringCivilBo.getCompletionStatus());
                zEngineeringReview.setReviewUser(userId);
                zEngineeringReview.setEngInfoId(zEngineeringNode1.getId());
                zEngineeringReviewMapper.insert(zEngineeringReview);
            }

        });
        return 0;
    }

    @Override
    public Integer batchNodes(switchBo bo) {
        LambdaQueryWrapper<ZEngineeringCivil> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getAreaId()), ZEngineeringCivil::getAreaId, bo.getAreaId());
        lqw.eq(ZEngineeringCivil::getBuildingId, bo.getBuildingId());
        //        .isNull(!StringUtils.isNotBlank(item.getBuildingId()),ZEngineeringCivil::getBuildingId);
        lqw.eq(ZEngineeringCivil::getUnitId, bo.getUnitId());
        //            .isNull(!StringUtils.isNotBlank(item.getUnitId()),ZEngineeringCivil::getUnitId);
        lqw.eq(ZEngineeringCivil::getHouseId, bo.getHouseId());
        //            .isNull(!StringUtils.isNotBlank(item.getId()),ZEngineeringCivil::getHouseId);
        lqw.eq(StringUtils.isNotBlank(bo.getEnginCycle()), ZEngineeringCivil::getEnginCycle, bo.getEnginCycle());
        lqw.eq(StringUtils.isNotBlank(bo.getEnginType()), ZEngineeringCivil::getEnginType, bo.getEnginType());
        lqw.eq(StringUtils.isNotBlank(bo.getEnginClassification()), ZEngineeringCivil::getEnginClassification, bo.getEnginClassification());
        ZEngineeringCivilVo zEngineeringCivilVo = zEngineeringCivilMapper.selectVoOne(lqw);
        if (!ObjectUtils.isEmpty(zEngineeringCivilVo)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM");
            MonthTableNameHandler.setData(simpleDateFormat.format(zEngineeringCivilVo.getCreateTime()));
            LambdaQueryWrapper<ZEngineeringNode> lqw2 = Wrappers.lambdaQuery();
            lqw2.eq(StringUtils.isNotBlank(zEngineeringCivilVo.getId()), ZEngineeringNode::getCivliId, zEngineeringCivilVo.getId());
            lqw2.eq(StringUtils.isNotBlank(bo.getActiveNames()), ZEngineeringNode::getType, bo.getActiveNames());
            ZEngineeringNode zEngineeringNode = baseMapper.selectOne(lqw2);
            if (!ObjectUtils.isEmpty(zEngineeringNode)) {
                ZEngineeringReview zEngineeringReview = new ZEngineeringReview();
                zEngineeringReview.setReviewTime(new Date());
                zEngineeringReview.setReviewStatus(bo.getReviewStatus());
                zEngineeringReview.setReviewUser(LoginHelper.getLoginUser().getUserId().toString());
                zEngineeringReview.setEngInfoId(zEngineeringNode.getId());
                zEngineeringReviewMapper.insert(zEngineeringReview);
            } else {
                ZEngineeringNode zEngineeringNode1 = new ZEngineeringNode();
                zEngineeringNode1.setCivliId(zEngineeringCivilVo.getId());
                zEngineeringNode1.setType(bo.getActiveNames());
                baseMapper.insert(zEngineeringNode1);
                ZEngineeringReview zEngineeringReview = new ZEngineeringReview();
                zEngineeringReview.setReviewTime(new Date());
                zEngineeringReview.setReviewStatus(bo.getReviewStatus());
                zEngineeringReview.setReviewUser(LoginHelper.getLoginUser().getUserId().toString());
                zEngineeringReview.setEngInfoId(zEngineeringNode1.getId());
                zEngineeringReviewMapper.insert(zEngineeringReview);
            }
            MonthTableNameHandler.removeData();
        } else {
            ZEngineeringCivil zEngineeringCivil = new ZEngineeringCivil();
            BeanUtils.copyProperties(bo, zEngineeringCivil);
            BeanUtils.copyProperties(bo, zEngineeringCivil);
            zEngineeringCivil.setId(null);
            zEngineeringCivil.setCompletionStatus("施工中");
            zEngineeringCivil.setHouseId(bo.getHouseId());
            zEngineeringCivilMapper.insert(zEngineeringCivil);
            ZEngineeringNode zEngineeringNode1 = new ZEngineeringNode();
            zEngineeringNode1.setCivliId(zEngineeringCivil.getId());
            zEngineeringNode1.setType(bo.getActiveNames());
            baseMapper.insert(zEngineeringNode1);
            ZEngineeringReview zEngineeringReview = new ZEngineeringReview();
            zEngineeringReview.setReviewTime(new Date());
            zEngineeringReview.setReviewStatus(bo.getReviewStatus());
            zEngineeringReview.setReviewUser(LoginHelper.getLoginUser().getUserId().toString());
            zEngineeringReview.setEngInfoId(zEngineeringNode1.getId());
            zEngineeringReviewMapper.insert(zEngineeringReview);
        }

        return null;
    }

    @Override
    public Map<String, Object> ReViewAirList(List<ZEngineeringAirWallVo> list) {
        Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
        List<ZEngineeringReview> nodeTypeList = new ArrayList<>();
        Map<String, Object> statemap = new HashMap<>();
        AtomicReference<List<Map<String, Object>>> ReViewStateMap = new AtomicReference<>(new ArrayList<>());
        list.stream().forEach(item -> {
            String date = new SimpleDateFormat("yyyy_MM").format(item.getCreateTime());
            MonthTableNameHandler.setData(date);
            LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item.getId()), ZEngineeringNode::getCivliId, item.getId());
            // lqw.eq(StringUtils.isNotBlank(type), ZEngineeringNode::getType, type);
            List<ZEngineeringNode> nodeList = baseMapper.selectList(lqw);
            nodeList.stream().forEach(item2 -> {
                LambdaQueryWrapper<ZEngineeringReview> lqw2 = Wrappers.lambdaQuery();
                lqw2.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringReview::getEngInfoId, item2.getId()).orderByDesc(ZEngineeringReview::getReviewTime);
                List<ZEngineeringReview> ReviewList = zEngineeringReviewMapper.selectList(lqw2);
                if (ReviewList.size() > 0) {
                    nodeTypeList.add(ReviewList.get(0));
                }

            });
            System.out.println(nodeList.toString());
            System.out.println(nodeTypeList.toString());
            List stateList = new ArrayList();
            Stream.of("带气封堵施工").forEach(item3 -> {
                Map<String, Object> map = new HashMap<>();
                if (nodeList.size() > 0 && nodeList.stream().anyMatch(x -> x.getType().equals(item3))) {
                    map.put("Type", item3);
                    map.put("state", nodeTypeList.stream().anyMatch(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3)).collect(Collectors.toList()).get(0).getId())) ? nodeTypeList.stream().filter(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3)).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewStatus() : "0");
                    map.put("content", nodeTypeList.stream().anyMatch(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3)).collect(Collectors.toList()).get(0).getId())) ? nodeTypeList.stream().filter(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3)).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewContent() : "暂未审核");
                } else {
                    map.put("Type", item3);
                    map.put("state", "0");
                    map.put("content", "暂未审核");
                }
                stateList.add(map);
                ReViewStateMap.set(stateList);
                ;
            });
            statemap.put(item.getId(), ReViewStateMap.get());

            MonthTableNameHandler.removeData();
        });
        return statemap;
    }


    public List getZEngineeringNodeList(String date, String UserId, ZEngineeringNodeBo bo) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        List<ZEngineeringNodeVo> list = new ArrayList<>();
        try {
            Date startdate = format.parse(date);
            bo.setCreateTime(startdate);

            SimpleDateFormat format2 = new SimpleDateFormat("yyyy_MM");
            MonthTableNameHandler.setData(format2.format(startdate));
            try {
                list = queryList(bo);
            } catch (Exception e) {
                log.info("没有{}该表", format2.format(startdate));

                return null;
            }
            List zEngineeringReviewList = new ArrayList<>();
            list.stream().forEach(item -> {
                ZEngineeringReviewBo zEngineeringReview = new ZEngineeringReviewBo();
                zEngineeringReview.setReviewTime(new Date());
                zEngineeringReview.setReviewContent("批量审核");
                zEngineeringReview.setReviewStatus("1");
                zEngineeringReview.setReviewUser(UserId);
                zEngineeringReview.setEngInfoId(item.getId());
                zEngineeringReviewList.add(zEngineeringReview);

            });
            izEngineeringReviewService.insertBacth(zEngineeringReviewList);
            MonthTableNameHandler.removeData();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        return list;

    }

    /**
     * 新增工程节点
     */
    @Override
    public Boolean insertByBo(ZEngineeringNodeBo bo) {
        ZEngineeringNode add = BeanUtil.toBean(bo, ZEngineeringNode.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 新增工程节点
     *
     * @param bo
     * @return ZEngineeringNode
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @DynamicName(spel = "#bo.createTime")
    public ZEngineeringNode insert(ZEngineeringNodeBo bo) {
        ZEngineeringNode add = BeanUtil.toBean(bo, ZEngineeringNode.class);
        add.setUpdateTime(new Date());
        validEntityBeforeSave(add);
        if (StringUtils.isEmpty(bo.getId())) {
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
            }
        }
        bo.setUpdateTime(new Date());
        bo.getzEngineeringInfoBo().setEngInfoId(add.getId());
        bo.getzEngineeringInfoBo().setCreateTime(bo.getCreateTime());
        bo.getzEngineeringInfoBo().setUpdateTime(new Date());
        izEngineeringReviewService.deleteByInfoId(bo);
        izEngineeringInfoService.insert(bo.getzEngineeringInfoBo());
        izEngineeringReviewService.deleteByNodeBoId(bo);
        return add;
    }


    /**
     * 修改工程节点
     */
    @Override
    public Boolean updateByBo(ZEngineeringNodeBo bo) {
        ZEngineeringNode update = BeanUtil.toBean(bo, ZEngineeringNode.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(ZEngineeringNodeBo bo) {
        ZEngineeringNode update = BeanUtil.toBean(bo, ZEngineeringNode.class);
        validEntityBeforeSave(update);
        if (ObjectUtils.isEmpty(bo.getzEngineeringInfoBo())) {
            for (ZEngineeringInfoBo zEngineeringInfoBo : bo.getzEngineeringInfoBoList()) {
                zEngineeringInfoBo.setCreateTime(bo.getCreateTime());
                izEngineeringInfoService.update(zEngineeringInfoBo);
            }
        } else {
            bo.getzEngineeringInfoBo().setCreateTime(bo.getCreateTime());
            izEngineeringInfoService.update(bo.getzEngineeringInfoBo());
        }
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMuch(ZEngineeringNodeBo bo) {
        ZEngineeringNode update = BeanUtil.toBean(bo, ZEngineeringNode.class);
        bo.getzEngineeringInfoBoList().stream().forEach(item -> {
            item.setCreateTime(bo.getCreateTime());
            item.setState("");
            izEngineeringInfoService.update(item);
        });
        izEngineeringReviewService.deleteByNodeBoId(bo);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(ZEngineeringNodeBo bo) {
        LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngineeringNode::getId, bo.getId());
        ZEngineeringNode zEngineeringNode = baseMapper.selectOne(lqw);
        ZEngineeringNodeBo zEngineeringNodeBo = BeanUtil.toBean(zEngineeringNode, ZEngineeringNodeBo.class);
        if (zEngineeringNodeBo != null) {
            izEngineeringInfoService.delete(zEngineeringNodeBo);
        }
        return baseMapper.deleteById(bo.getId()) > 0;
    }

    @Override
    public List<String> nodeTypeList(List<ZEngineeringCivil> zEngineeringCivilList, String type, String state, ZEngineeringCivilBo bo) {
        List<ZEngineeringNode> nodeTypeList = new ArrayList<>();
        zEngineeringCivilList.forEach(item -> {
            String date = new SimpleDateFormat("yyyy_MM").format(item.getCreateTime());
            MonthTableNameHandler.setData(date);
            LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item.getId()), ZEngineeringNode::getCivliId, item.getId());
            lqw.eq(StringUtils.isNotBlank(type), ZEngineeringNode::getType, type);
            List<ZEngineeringNode> nodeList = baseMapper.selectList(lqw);
            if (StringUtils.isNotBlank(state)) {
                if (nodeList.size() > 0) {
                    nodeList.forEach(item2 -> {
                        LambdaQueryWrapper<ZEngineeringReview> lqw2 = Wrappers.lambdaQuery();
                        lqw2.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringReview::getEngInfoId, item2.getId()).orderByDesc(ZEngineeringReview::getReviewTime);
                        List<ZEngineeringReview> ReviewList = zEngineeringReviewMapper.selectList(lqw2);
                        if (state.equals("2")) {
                            if (ReviewList.size() == 0) {
                                nodeTypeList.add(item2);
                            }
                        } else if (state.equals("1")) {
                            if (ReviewList.size() > 0 && ReviewList.get(0).getReviewStatus().equals("1")) {
                                nodeTypeList.add(item2);
                            }
                        } else if (state.equals("0")) {
                            if (ReviewList.size() > 0 && ReviewList.get(0).getReviewStatus().equals("0")) {
                                nodeTypeList.add(item2);
                            }
                        }
                    });
                }
            } else {
                nodeTypeList.addAll(nodeList);
            }
            MonthTableNameHandler.removeData();
        });
        if ((!"".equals(bo.getBeginTime()) && !ObjectUtils.isEmpty(bo.getBeginTime())) || (!"".equals(bo.getCreateBy()) && !ObjectUtils.isEmpty(bo.getCreateBy()))) {
            Iterator<ZEngineeringNode> iterator = nodeTypeList.iterator();
            while (iterator.hasNext()) {
                ZEngineeringNode item = iterator.next();
                String date = new SimpleDateFormat("yyyy_MM").format(item.getCreateTime());
                MonthTableNameHandler.setData(date);
                LambdaQueryWrapper<ZEngineeringInfo> lqw = Wrappers.lambdaQuery();
                lqw.eq(StringUtils.isNotBlank(item.getId()), ZEngineeringInfo::getEngInfoId, item.getId());
                lqw.like(ZEngineeringInfo::getCreateBy, bo.getCreateBy());
                if (!"".equals(bo.getBeginTime()) && !ObjectUtils.isEmpty(bo.getBeginTime())) {
                    lqw.between(ZEngineeringInfo::getUpdateInfoTime, bo.getBeginTime().get(0), bo.getBeginTime().get(1));
                }
                if (zEngineeringInfoMapper.selectCount(lqw) == 0) {
                    iterator.remove();
                }
            }
        }
        List<String> IDList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(nodeTypeList)) {
            IDList = nodeTypeList.stream().map(ZEngineeringNode::getCivliId).collect(Collectors.toList());
        }
        return IDList;
    }

    @Override
    public Map<String, Object> ReViewInfrastructureList(List<ZEngineeringInfrastructureVo> list) {
        Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
        List<ZEngineeringReview> nodeTypeList = new ArrayList<>();
        Map<String, Object> statemap = new HashMap<>();
        AtomicReference<List<Map<String, Object>>> ReViewStateMap = new AtomicReference<>(new ArrayList<>());
        list.stream().forEach(item -> {
            String date = new SimpleDateFormat("yyyy_MM").format(item.getCreateTime());
            MonthTableNameHandler.setData(date);
            LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item.getId()), ZEngineeringNode::getCivliId, item.getId());
            // lqw.eq(StringUtils.isNotBlank(type), ZEngineeringNode::getType, type);
            List<ZEngineeringNode> nodeList = baseMapper.selectList(lqw);
            nodeList.stream().forEach(item2 -> {
                LambdaQueryWrapper<ZEngineeringReview> lqw2 = Wrappers.lambdaQuery();
                lqw2.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringReview::getEngInfoId, item2.getId()).orderByDesc(ZEngineeringReview::getReviewTime);
                List<ZEngineeringReview> ReviewList = zEngineeringReviewMapper.selectList(lqw2);
                if (ReviewList.size() > 0) {
                    nodeTypeList.add(ReviewList.get(0));
                }

            });
            System.out.println(nodeList.toString());
            System.out.println(nodeTypeList.toString());
            List stateList = new ArrayList();
            sysDictMap.get("engineering_infrastructure").stream().forEach(item3 -> {
                Map<String, Object> map = new HashMap<>();
                if (nodeList.size() > 0 && nodeList.stream().anyMatch(x -> x.getType().equals(item3.getDictValue()))) {
                    map.put("Type", item3.getDictValue());
                    map.put("state", nodeTypeList.stream().anyMatch(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())) ? nodeTypeList.stream().filter(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewStatus() : "0");
                    map.put("content", nodeTypeList.stream().anyMatch(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())) ? nodeTypeList.stream().filter(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewContent() : "暂未审核");
                } else {
                    map.put("Type", item3.getDictValue());
                    map.put("state", "0");
                    map.put("content", "暂未审核");
                }
                stateList.add(map);
                ReViewStateMap.set(stateList);
                ;
            });
            statemap.put(item.getId(), ReViewStateMap.get());

            MonthTableNameHandler.removeData();
        });
        return statemap;
    }

    @Override
    public Map<String, Object> ReViewPipeJackingList(List<ZEngineeringPipeJackingVo> list) {
        Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
        List<ZEngineeringReview> nodeTypeList = new ArrayList<>();
        Map<String, Object> statemap = new HashMap<>();
        AtomicReference<List<Map<String, Object>>> ReViewStateMap = new AtomicReference<>(new ArrayList<>());
        list.stream().forEach(item -> {
            String date = new SimpleDateFormat("yyyy_MM").format(item.getCreateTime());
            MonthTableNameHandler.setData(date);
            LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item.getId()), ZEngineeringNode::getCivliId, item.getId());
            // lqw.eq(StringUtils.isNotBlank(type), ZEngineeringNode::getType, type);
            List<ZEngineeringNode> nodeList = baseMapper.selectList(lqw);
            nodeList.stream().forEach(item2 -> {
                LambdaQueryWrapper<ZEngineeringReview> lqw2 = Wrappers.lambdaQuery();
                lqw2.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringReview::getEngInfoId, item2.getId()).orderByDesc(ZEngineeringReview::getReviewTime);
                List<ZEngineeringReview> ReviewList = zEngineeringReviewMapper.selectList(lqw2);
                if (ReviewList.size() > 0) {
                    nodeTypeList.add(ReviewList.get(0));
                }
                if("回拖".equals(item2.getType())){
                    LambdaQueryWrapper<ZEngineeringInfo> lqw3 = Wrappers.lambdaQuery();
                    lqw3.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringInfo::getEngInfoId, item2.getId());
                    List<ZEngineeringInfo> info= zEngineeringInfoMapper.selectList(lqw3);
                    info.stream().forEach(item3->{
                        LambdaQueryWrapper<ZEngineeringMaterial> lqw4 = Wrappers.lambdaQuery();
                        lqw4.eq(StringUtils.isNotBlank(item3.getId()), ZEngineeringMaterial::getDetailsId, item3.getId());
                        List<ZEngineeringMaterial> material= zEngineeringMaterialMapper.selectList(lqw4);
                        material.stream().forEach(item4->{
                            String type = zEnginMaterialQualityMapper.selectVoById(item4.getMaterialQuality()).getMaterialType();
                            if("0".equals(type)){
                                item.setPesj(new BigDecimal(Double.toString(item.getPesj())).add(new BigDecimal(Double.toString(item4.getNumber()))).doubleValue());
                            }else if("1".equals(type)){
                                item.setGsj(new BigDecimal(Double.toString(item.getGsj())).add(new BigDecimal(Double.toString(item4.getNumber()))).doubleValue());
                            }
                        });
                    });
                }
            });
            System.out.println(nodeList.toString());
            System.out.println(nodeTypeList.toString());
            List stateList = new ArrayList();
            sysDictMap.get("pipe_jack").stream().forEach(item3 -> {
                Map<String, Object> map = new HashMap<>();
                if (nodeList.size() > 0 && nodeList.stream().anyMatch(x -> x.getType().equals(item3.getDictValue()))) {
                    map.put("Type", item3.getDictValue());
                    map.put("state", nodeTypeList.stream().anyMatch(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())) ? nodeTypeList.stream().filter(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewStatus() : "0");
                    map.put("content", nodeTypeList.stream().anyMatch(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())) ? nodeTypeList.stream().filter(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewContent() : "暂未审核");
                } else {
                    map.put("Type", item3.getDictValue());
                    map.put("state", "0");
                    map.put("content", "暂未审核");
                }
                stateList.add(map);
                ReViewStateMap.set(stateList);
                ;
            });
            statemap.put(item.getId(), ReViewStateMap.get());

            MonthTableNameHandler.removeData();
        });
        return statemap;
    }

    @Override
    public Map<String, Object> ReViewSZList(List<ZEngineeringIndustryVo> list) {
        Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
        List<ZEngineeringReview> nodeTypeList = new ArrayList<>();
        Map<String, Object> statemap = new HashMap<>();
        AtomicReference<List<Map<String, Object>>> ReViewStateMap = new AtomicReference<>(new ArrayList<>());
        list.stream().forEach(item -> {
            String date = new SimpleDateFormat("yyyy_MM").format(item.getCreateTime());
            MonthTableNameHandler.setData(date);
            LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item.getId()), ZEngineeringNode::getCivliId, item.getId());
            List<ZEngineeringNode> nodeList = baseMapper.selectList(lqw);
            nodeList.stream().forEach(item2 -> {
                LambdaQueryWrapper<ZEngineeringReview> lqw2 = Wrappers.lambdaQuery();
                lqw2.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringReview::getEngInfoId, item2.getId()).orderByDesc(ZEngineeringReview::getReviewTime);
                List<ZEngineeringReview> ReviewList = zEngineeringReviewMapper.selectList(lqw2);
                if (!ReviewList.isEmpty()) {
                    nodeTypeList.add(ReviewList.get(0));
                }
                if("下管".equals(item2.getType())){
                    LambdaQueryWrapper<ZEngineeringInfo> lqw3 = Wrappers.lambdaQuery();
                    lqw3.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringInfo::getEngInfoId, item2.getId());
                    List<ZEngineeringInfo> info= zEngineeringInfoMapper.selectList(lqw3);
                    info.stream().forEach(item3->{
                        LambdaQueryWrapper<ZEngineeringMaterial> lqw4 = Wrappers.lambdaQuery();
                        lqw4.eq(StringUtils.isNotBlank(item3.getId()), ZEngineeringMaterial::getDetailsId, item3.getId());
                        List<ZEngineeringMaterial> material= zEngineeringMaterialMapper.selectList(lqw4);
                        material.stream().forEach(item4->{
                            String type = zEnginMaterialQualityMapper.selectVoById(item4.getMaterialQuality()).getMaterialType();
                            if("0".equals(type)){
                                item.setPesj(new BigDecimal(Double.toString(item.getPesj())).add(new BigDecimal(Double.toString(item4.getNumber()))).doubleValue());
                            }else if("1".equals(type)){
                                item.setGsj(new BigDecimal(Double.toString(item.getGsj())).add(new BigDecimal(Double.toString(item4.getNumber()))).doubleValue());
                            }
                        });
                    });
                }
            });
            List stateList = new ArrayList();
            sysDictMap.get("municipal_node_types").stream().forEach(item3 -> {
                Map<String, Object> map = new HashMap<>();
                if (nodeList.size() > 0 && nodeList.stream().anyMatch(x -> x.getType().equals(item3.getDictValue()))) {
                    map.put("Type", item3.getDictValue());
                    map.put("state", nodeTypeList.stream().anyMatch(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())) ? nodeTypeList.stream().filter(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewStatus() : "0");
                    map.put("content", nodeTypeList.stream().anyMatch(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())) ? nodeTypeList.stream().filter(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewContent() : "暂未审核");
                } else {
                    map.put("Type", item3.getDictValue());
                    map.put("state", "0");
                    map.put("content", "暂未审核");
                }
                stateList.add(map);
                ReViewStateMap.set(stateList);
            });
            statemap.put(item.getId(),ReViewStateMap.get());

            MonthTableNameHandler.removeData();
        });
        return statemap;
    }
    @Override
    public Map<String,Object> ReViewGYList(List<ZEngineeringGYVo> list){
        Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
        List<ZEngineeringReview> nodeTypeList=new ArrayList<>();
        Map<String,Object> statemap=new HashMap<>();
        AtomicReference<List<Map<String, Object>>> ReViewStateMap= new AtomicReference<>(new ArrayList<>());
        list.stream().forEach(item->{
            String date = new SimpleDateFormat("yyyy_MM").format(item.getCreateTime());
            MonthTableNameHandler.setData(date);
            LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item.getId()), ZEngineeringNode::getCivliId, item.getId());
            List<ZEngineeringNode> nodeList=baseMapper.selectList(lqw);
            nodeList.stream().forEach(item2->{
                LambdaQueryWrapper<ZEngineeringReview> lqw2 = Wrappers.lambdaQuery();
                lqw2.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringReview::getEngInfoId, item2.getId()).orderByDesc(ZEngineeringReview::getReviewTime);
                List<ZEngineeringReview> ReviewList= zEngineeringReviewMapper.selectList(lqw2);
                if (!ReviewList.isEmpty())
                {
                    nodeTypeList.add(ReviewList.get(0));
                }
                if("焊接".equals(item2.getType())&&item.getEnginClassification().equals("室内管线")){
                    LambdaQueryWrapper<ZEngineeringInfo> lqw3 = Wrappers.lambdaQuery();
                    lqw3.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringInfo::getEngInfoId, item2.getId());
                    List<ZEngineeringInfo> info= zEngineeringInfoMapper.selectList(lqw3);
                    info.stream().forEach(item3->{
                        LambdaQueryWrapper<ZEngineeringMaterial> lqw4 = Wrappers.lambdaQuery();
                        lqw4.eq(StringUtils.isNotBlank(item3.getId()), ZEngineeringMaterial::getDetailsId, item3.getId());
                        List<ZEngineeringMaterial> material= zEngineeringMaterialMapper.selectList(lqw4);
                        material.stream().forEach(item4->{
                            String type = zEnginMaterialQualityMapper.selectVoById(item4.getMaterialQuality()).getMaterialType();
                            if("0".equals(type)){
                                item.setPesj(new BigDecimal(Double.toString(item.getPesj())).add(new BigDecimal(Double.toString(item4.getNumber()))).doubleValue());
                            }else if("1".equals(type)){
                                item.setGsj(new BigDecimal(Double.toString(item.getGsj())).add(new BigDecimal(Double.toString(item4.getNumber()))).doubleValue());
                            }
                        });
                    });
                }else if("下管".equals(item2.getType())&&item.getEnginClassification().equals("室外管线")){
                    LambdaQueryWrapper<ZEngineeringInfo> lqw3 = Wrappers.lambdaQuery();
                    lqw3.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringInfo::getEngInfoId, item2.getId());
                    List<ZEngineeringInfo> info= zEngineeringInfoMapper.selectList(lqw3);
                    info.stream().forEach(item3->{
                        LambdaQueryWrapper<ZEngineeringMaterial> lqw4 = Wrappers.lambdaQuery();
                        lqw4.eq(StringUtils.isNotBlank(item3.getId()), ZEngineeringMaterial::getDetailsId, item3.getId());
                        List<ZEngineeringMaterial> material= zEngineeringMaterialMapper.selectList(lqw4);
                        material.stream().forEach(item4->{
                            String type = zEnginMaterialQualityMapper.selectVoById(item4.getMaterialQuality()).getMaterialType();
                            if("0".equals(type)){
                                item.setPesj(new BigDecimal(Double.toString(item.getPesj())).add(new BigDecimal(Double.toString(item4.getNumber()))).doubleValue());
                            }else if("1".equals(type)){
                                item.setGsj(new BigDecimal(Double.toString(item.getGsj())).add(new BigDecimal(Double.toString(item4.getNumber()))).doubleValue());
                            }
                        });
                    });
                }
            });
            String flag = null;
            if (item.getEnginClassification().equals("室内管线")){
                flag = "gy_inner";
            }
            if (item.getEnginClassification().equals("室外管线")){
                flag = "gy_out";
            }
            if (item.getEnginClassification().equals("调压柜")){
                flag = "gy_tyg";
            }
            List stateList=new ArrayList();
            sysDictMap.get(flag).stream().forEach(item3 -> {
                Map<String,Object> map=new HashMap<>();
                if (nodeList.size()>0&&nodeList.stream().anyMatch(x->x.getType().equals(item3.getDictValue()))){
                    map.put("Type",item3.getDictValue());
                    map.put("state",nodeTypeList.stream().anyMatch(y->y.getEngInfoId().equals(nodeList.stream().filter(x->x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId()))?nodeTypeList.stream().filter(y->y.getEngInfoId().equals(nodeList.stream().filter(x->x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewStatus():"0");
                    map.put("content",nodeTypeList.stream().anyMatch(y->y.getEngInfoId().equals(nodeList.stream().filter(x->x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId()))?nodeTypeList.stream().filter(y->y.getEngInfoId().equals(nodeList.stream().filter(x->x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewContent():"暂未审核");
                }else {
                    map.put("Type",item3.getDictValue());
                    map.put("state","0");
                    map.put("content","暂未审核");
                }
                stateList.add(map);
                ReViewStateMap.set(stateList);;
            });
            statemap.put(item.getId(), ReViewStateMap.get());

            MonthTableNameHandler.removeData();
        });
        return statemap;
    }

    @Override
    public Map<Long, Object> ReViewPKList(List<ZTouchOperationEngineeringVo> list) {
        Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
        List<ZEngineeringReview> nodeTypeList = new ArrayList<>();
        Map<Long, Object> statemap = new HashMap<>();
        AtomicReference<List<Map<String, Object>>> ReViewStateMap = new AtomicReference<>(new ArrayList<>());
        list.stream().forEach(item -> {
            List stateList = new ArrayList();
            String dists = "";
            if ("地埋扳孔".equals(item.getModeOperation())){
                dists="bury_the_wrench_hole";
            }else if ("架空扳孔".equals(item.getModeOperation())){
                dists="aerial_wrench_hole";
            }else if ("停气作业".equals(item.getModeOperation())){
                dists="shutdown_operation";
            }else if ("PE 封堵".equals(item.getModeOperation())){
                dists="pe_plugging";
            }else if ("钢管带气封堵".equals(item.getModeOperation())){
                dists="the_steel_pipe_sealed_with_gas";
            }
            sysDictMap.get(dists).stream().forEach(item3 -> {
                Map<String, Object> map = new HashMap<>();
                map.put("Type", item3.getDictValue());
                map.put("state", "0");
                map.put("content", "暂未审核");
                stateList.add(map);

            });
            statemap.put(item.getId(), stateList);
            MonthTableNameHandler.removeData();
        });
        return statemap;
    }

    @Override
    public Map<String, Object> ReViewList(List<ZEngineeringCivilVo> zEngineeringCivilList) {
        Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
        List<ZEngineeringReview> nodeTypeList = new ArrayList<>();
        Map<String, Object> statemap = new HashMap<>();
        List<Map<String, Object>> ReViewMap = new ArrayList<>();
        AtomicReference<List<Map<String, Object>>> ReViewStateMap = new AtomicReference<>(new ArrayList<>());
        zEngineeringCivilList.stream().forEach(item -> {
            String date = new SimpleDateFormat("yyyy_MM").format(item.getCreateTime());
            MonthTableNameHandler.setData(date);
            LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item.getId()), ZEngineeringNode::getCivliId, item.getId());
            // lqw.eq(StringUtils.isNotBlank(type), ZEngineeringNode::getType, type);
            List<ZEngineeringNode> nodeList = baseMapper.selectList(lqw);
            nodeList.stream().forEach(item2 -> {
                LambdaQueryWrapper<ZEngineeringReview> lqw2 = Wrappers.lambdaQuery();
                lqw2.eq(StringUtils.isNotBlank(item2.getId()), ZEngineeringReview::getEngInfoId, item2.getId()).orderByDesc(ZEngineeringReview::getReviewTime);
                List<ZEngineeringReview> ReviewList = zEngineeringReviewMapper.selectList(lqw2);
                if (ReviewList.size() > 0) {
                    nodeTypeList.add(ReviewList.get(0));
                }
            });
            List stateList = new ArrayList();
            List<SysDictData> list = sysDictMap.get(item.getEnginType() + "_" + item.getEnginClassification());
            if (list != null && !list.isEmpty()) {
                list.stream().forEach(item3 -> {
                    Map<String, Object> map = new HashMap<>();
                    if (nodeList.size() > 0 && nodeList.stream().anyMatch(x -> x.getType().equals(item3.getDictValue()))) {
                        map.put("Type", item3.getDictValue());
                        map.put("state", nodeTypeList.stream().anyMatch(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())) ? nodeTypeList.stream().filter(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewStatus() : "0");
                        map.put("content", nodeTypeList.stream().anyMatch(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())) ? nodeTypeList.stream().filter(y -> y.getEngInfoId().equals(nodeList.stream().filter(x -> x.getType().equals(item3.getDictValue())).collect(Collectors.toList()).get(0).getId())).collect(Collectors.toList()).get(0).getReviewContent() : "暂未审核");
                    } else {
                        map.put("Type", item3.getDictValue());
                        map.put("state", "0");
                        map.put("content", "暂未审核");
                    }
                    stateList.add(map);
                    ReViewStateMap.set(stateList);
                    ;
                });
            }
            if (item.getEnginClassification().contains("indoor_engin")) {
                Map<String, Object> map = new HashMap<>();
                map.put("Type", "开栓");
                map.put("state", zComprehensiveMapper.getIsQualifiedString(item.getHouseId()));
                ReViewStateMap.get().add(map);
            }
            statemap.put(item.getId(), ReViewStateMap.get());

            MonthTableNameHandler.removeData();
        });

        return statemap;
    }


    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZEngineeringNode entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除工程节点
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 获取某个时间段内所有月份
     *
     * @param minDate
     * @param maxDate
     * @return
     * @throws ParseException
     */
    public List<String> getMonthBetweenDates(String minDate, String maxDate) {
        ArrayList<String> result = new ArrayList<String>();
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        min.setTime(parse(minDate, "yyyy-MM"));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
        max.setTime(parse(maxDate, "yyyy-MM"));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        Calendar curr = min;
        while (curr.before(max)) {
            result.add(format(curr.getTime(), "yyyy-MM"));
            curr.add(Calendar.MONTH, 1);
        }
        return result;
    }

    public Date parse(String date, String pattern) {
        try {
            return new SimpleDateFormat(pattern).parse(date);
        } catch (Exception e) {
        }
        return null;
    }
}
