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.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.framework.handler.MonthTableNameHandler;
import com.ruoyi.zdsz.domain.ZEngiineeringPhoto;
import com.ruoyi.zdsz.domain.ZEngineeringIndustry;
import com.ruoyi.zdsz.domain.bo.*;
import com.ruoyi.zdsz.domain.vo.ZEngiineeringPhotoVo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringIndustryTypeVo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringIndustryVo;
import com.ruoyi.zdsz.mapper.ZEngineeringCivilMapper;
import com.ruoyi.zdsz.mapper.ZEngineeringIndustryMapper;
import com.ruoyi.zdsz.service.IZEngiineeringPhotoService;
import com.ruoyi.zdsz.service.IZEngineeringIndustryService;
import com.ruoyi.zdsz.service.IZEngineeringNodeService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工业工程|市政工程Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-02
 */
@RequiredArgsConstructor
@Service
public class ZEngineeringIndustryServiceImpl implements IZEngineeringIndustryService {

    @Resource
    private final ZEngineeringIndustryMapper baseMapper;

    @Resource
    private IZEngineeringNodeService izEngineeringNodeService;

    @Resource
    private IZEngineeringNodeService nodeService;

    @Resource
    private IZEngiineeringPhotoService photoService;

    @Autowired
    private ZEngineeringCivilMapper zEngineeringCivilMapper;

    @Override
    public TableDataInfo<Map<String, Object>> getByUserList(String type,String enginName,String enginType,String enginProcedure,String enginStatus,PageQuery pageQuery) {
        Page<T> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        String leftJoin = null;
        String szAndGy = null;
        if ("1".equals(type)){
            leftJoin = "z_engineering_pipe_jacking"; // 顶管
        }
        else if ("2".equals(type)){
            leftJoin = "z_engineering_infrastructure"; // 基建
        }
        else if ("3".equals(type)){
            leftJoin = "z_engineering_dangerous"; // 危险工程
        }
        else if ("4".equals(type)){
            leftJoin = "z_engineering_industry"; // 市政工程
            szAndGy = "gy";
        }
        else if ("5".equals(type)){
            leftJoin = "z_engineering_industry"; // 工业工程
            szAndGy = "sz";
        }
        else if ("6".equals(type)){
            leftJoin = "z_engineering_air_wall"; // 工业工程
        }
        LinkedList<String> list = zEngineeringCivilMapper.getTableNames("z_engineering_info");
        List DateList = new ArrayList();
        list.removeLast();
        list.stream().forEach(item -> {
            DateList.add(item.substring(item.indexOf("2")));
        });
        String username = LoginHelper.getUsername();
        Page<Map<String, Object>> listPage = baseMapper.getByUserList(DateList, username, leftJoin, szAndGy, page);

        if ("1".equals(type)){ // 顶管
            listPage.getRecords().forEach(item -> {

                String date = new SimpleDateFormat("yyyy_MM").format(Date.from(((LocalDateTime)item.get("createTime")).atZone(ZoneId.systemDefault()).toInstant()));
                MonthTableNameHandler.setData(date);

                List<Map<String, String>> mapList = baseMapper.getReviewStatusByNodeId(item.get("id").toString());
                Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
                List<SysDictData> municipalEngineeringNode = sysDictMap.get("pipe_jack");
                mapList.forEach(ite -> {
                    String str = "2".equals(ite.get("reviewStatus"))?"未审核":"1".equals(ite.get("reviewStatus"))?"通过":"未通过";
                    // "municipal_engineering_node";
                    ite.put("type",municipalEngineeringNode.stream().filter(ie-> ie.getDictValue() .equals(ite.get("type"))).collect(Collectors.toList()).get(0).getDictLabel());
                    ite.put("reviewStatus", str);
                });
                municipalEngineeringNode.forEach(ite -> {
                    String dictLabel = ite.getDictLabel();
                    List<Map<String, String>> type1 = mapList.stream().filter(it -> it.get("type").equals(dictLabel)).collect(Collectors.toList());
                    if (type1.size() == 0) {
                        HashMap<String, String> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("reviewStatus","未审核");
                        objectObjectHashMap.put("type",dictLabel);
                        mapList.add(objectObjectHashMap);
                    }
                });
                item.put("status",mapList);
                MonthTableNameHandler.removeData();
            });
        }
        else if ("2".equals(type)){ // 基建
            listPage.getRecords().forEach(item -> {
                String date = new SimpleDateFormat("yyyy_MM").format(Date.from(((LocalDateTime)item.get("createTime")).atZone(ZoneId.systemDefault()).toInstant()));;
                MonthTableNameHandler.setData(date);
                List<Map<String, String>> mapList = baseMapper.getReviewStatusByNodeId(item.get("id").toString());
                Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
                List<SysDictData> municipalEngineeringNode = sysDictMap.get("engineering_infrastructure");
                mapList.forEach(ite -> {
                    String str = "2".equals(ite.get("reviewStatus"))?"未审核":"1".equals(ite.get("reviewStatus"))?"通过":"未通过";
                    // "municipal_engineering_node";
                    ite.put("type",municipalEngineeringNode.stream().filter(ie-> ie.getDictValue() .equals(ite.get("type"))).collect(Collectors.toList()).get(0).getDictLabel());
                    ite.put("reviewStatus", str);
                });
                municipalEngineeringNode.forEach(ite -> {
                    String dictLabel = ite.getDictLabel();
                    List<Map<String, String>> type1 = mapList.stream().filter(it -> it.get("type").equals(dictLabel)).collect(Collectors.toList());
                    if (type1.size() == 0) {
                        HashMap<String, String> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("reviewStatus","未审核");
                        objectObjectHashMap.put("type",dictLabel);
                        mapList.add(objectObjectHashMap);
                    }
                });
                item.put("status",mapList);
                MonthTableNameHandler.removeData();
            });
        }
        else if ("3".equals(type)){ // 危险工程
            listPage.getRecords().forEach(item -> {
                String date = new SimpleDateFormat("yyyy_MM").format(Date.from(((LocalDateTime)item.get("createTime")).atZone(ZoneId.systemDefault()).toInstant()));;
;
                MonthTableNameHandler.setData(date);
                List<Map<String, String>> mapList = baseMapper.getReviewStatusByNodeId(item.get("id").toString());
                mapList.forEach(ite -> {
                    String str = "2".equals(ite.get("reviewStatus"))?"未审核":"1".equals(ite.get("reviewStatus"))?"通过":"未通过";
                    ite.put("reviewStatus", str);
                });
                item.put("status",mapList);
                MonthTableNameHandler.removeData();
            });
        }
        else if ("4".equals(type)){ // 市政工程
            listPage.getRecords().forEach(item -> {
                String date = new SimpleDateFormat("yyyy_MM").format(Date.from(((LocalDateTime)item.get("createTime")).atZone(ZoneId.systemDefault()).toInstant()));;
;
                MonthTableNameHandler.setData(date);
                List<Map<String, String>> mapList = baseMapper.getReviewStatusByNodeId(item.get("id").toString());
                Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
                List<SysDictData> municipalEngineeringNode = sysDictMap.get("municipal_engineering_node");
                mapList.forEach(ite -> {
                    String str = "2".equals(ite.get("reviewStatus"))?"未审核":"1".equals(ite.get("reviewStatus"))?"通过":"未通过";
                    // "municipal_engineering_node";
                    ite.put("type",municipalEngineeringNode.stream().filter(ie-> ie.getDictValue() .equals(ite.get("type"))).collect(Collectors.toList()).get(0).getDictLabel());
                    ite.put("reviewStatus", str);
                });
                municipalEngineeringNode.forEach(ite -> {
                    String dictLabel = ite.getDictLabel();
                    List<Map<String, String>> type1 = mapList.stream().filter(it -> it.get("type").equals(dictLabel)).collect(Collectors.toList());
                    if (type1.size() == 0) {
                        HashMap<String, String> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("reviewStatus","未审核");
                        objectObjectHashMap.put("type",dictLabel);
                        mapList.add(objectObjectHashMap);
                    }
                });
                item.put("status",mapList);
                MonthTableNameHandler.removeData();
            });
        }
        else if ("5".equals(type)){ // 工业工程
            listPage.getRecords().forEach(item -> {
                String date = new SimpleDateFormat("yyyy_MM").format(Date.from(((LocalDateTime)item.get("createTime")).atZone(ZoneId.systemDefault()).toInstant()));;
;
                MonthTableNameHandler.setData(date);
                List<Map<String, String>> mapList = baseMapper.getReviewStatusByNodeId(item.get("id").toString());
                mapList.forEach(ite -> {
                    String str = "2".equals(ite.get("reviewStatus"))?"未审核":"1".equals(ite.get("reviewStatus"))?"通过":"未通过";
                    ite.put("reviewStatus", str);
                });
                item.put("status",mapList);
            });
            MonthTableNameHandler.removeData();
        }
        else if ("6".equals(type)){ // 工业工程
            listPage.getRecords().forEach(item -> {
                String date = new SimpleDateFormat("yyyy_MM").format(Date.from(((LocalDateTime)item.get("createTime")).atZone(ZoneId.systemDefault()).toInstant()));;
;
                MonthTableNameHandler.setData(date);
                List<Map<String, String>> mapList = baseMapper.getReviewStatusByNodeId(item.get("id").toString());
                mapList.forEach(ite -> {
                    String str = "2".equals(ite.get("reviewStatus"))?"未审核":"1".equals(ite.get("reviewStatus"))?"通过":"未通过";
                    ite.put("reviewStatus", str);
                });
                item.put("status",mapList);
            });
            MonthTableNameHandler.removeData();
        }
        return TableDataInfo.build(listPage);
    }

    /**
     * 查询工业工程|市政工程
     */
    @Override
    public ZEngineeringIndustryVo queryById(String id) {
        ZEngineeringIndustryVo zEngineeringIndustryVo = baseMapper.selectVoById(id);

        ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
        zEngiineeringPhotoBo.setParentId(zEngineeringIndustryVo.getId());
        zEngiineeringPhotoBo.setCreateTime(zEngineeringIndustryVo.getCreateTime());
        zEngineeringIndustryVo.setPics(photoService.queryList(zEngiineeringPhotoBo));
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCivliId(id);
        zEngineeringNodeBo.setCreateTime(zEngineeringIndustryVo.getCreateTime());
        List<ZEngineeringNodeBo> zEngineeringNodeBos = izEngineeringNodeService.queryListDetails(zEngineeringNodeBo);
        zEngineeringIndustryVo.setZEngineeringNodeBoList(zEngineeringNodeBos);
        return zEngineeringIndustryVo;
    }

    /**
     * 查询工业工程|市政工程列表
     */
    @Override
    public TableDataInfo<ZEngineeringIndustryVo> queryPageList(ZEngineeringIndustryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZEngineeringIndustry> lqw = buildQueryWrapper(bo);
        Page<ZEngineeringIndustryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询工业工程|市政工程列表
     */
    @Override
    public List<ZEngineeringIndustryVo> queryList(ZEngineeringIndustryBo bo) {
        LambdaQueryWrapper<ZEngineeringIndustry> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZEngineeringIndustry> buildQueryWrapper(ZEngineeringIndustryBo bo) {
        LambdaQueryWrapper<ZEngineeringIndustry> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(ZEngineeringIndustry::getCreateTime);
        lqw.eq(StringUtils.isNotBlank(bo.getEnginType()), ZEngineeringIndustry::getEnginType, bo.getEnginType());
        lqw.like(StringUtils.isNotBlank(bo.getEnginName()), ZEngineeringIndustry::getEnginName, bo.getEnginName());
        lqw.like(StringUtils.isNotBlank(bo.getEnginClassification()), ZEngineeringIndustry::getEnginClassification, bo.getEnginClassification());
        lqw.eq(StringUtils.isNotBlank(bo.getConstructUnit()), ZEngineeringIndustry::getConstructUnit, bo.getConstructUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectHead()), ZEngineeringIndustry::getProjectHead, bo.getProjectHead());
        lqw.eq(StringUtils.isNotBlank(bo.getSceneHead()), ZEngineeringIndustry::getSceneHead, bo.getSceneHead());
        lqw.eq(StringUtils.isNotBlank(bo.getDesignUnit()), ZEngineeringIndustry::getDesignUnit, bo.getDesignUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getDesignHead()), ZEngineeringIndustry::getDesignHead, bo.getDesignHead());
        lqw.eq(StringUtils.isNotBlank(bo.getDesignPhone()), ZEngineeringIndustry::getDesignPhone, bo.getDesignPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getSupervisionUnit()), ZEngineeringIndustry::getSupervisionUnit, bo.getSupervisionUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getSupervisionHead()), ZEngineeringIndustry::getSupervisionHead, bo.getSupervisionHead());
        lqw.eq(StringUtils.isNotBlank(bo.getSupervisionPhone()), ZEngineeringIndustry::getSupervisionPhone, bo.getSupervisionPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), ZEngineeringIndustry::getType, bo.getType());
        return lqw;
    }

    /**
     * 新增工业工程|市政工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ZEngineeringIndustryBo bo) {
        ZEngineeringIndustry add = BeanUtil.toBean(bo, ZEngineeringIndustry.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            List<ZEngiineeringPhoto> list = new ArrayList<>();
            bo.getFiles().forEach(o -> {
                ZEngiineeringPhoto pic = new ZEngiineeringPhoto();
                pic.setParentId(bo.getId());
                pic.setPicUrl(o.getUrl());
                pic.setFileName(o.getName());
                pic.setCreateBy(String.valueOf(LoginHelper.getUserId()));
                pic.setCreateTime(new Date());
                list.add(pic);
            });
            if (!list.isEmpty()) {
                photoService.insertBatch(list);
            }
        }
        if (!ObjectUtils.isEmpty(bo.getzEngineeringNodeBo())) {
            bo.getzEngineeringNodeBo().setCivliId(add.getId());
            bo.getzEngineeringNodeBo().setCreateTime(new Date());
            izEngineeringNodeService.insert(bo.getzEngineeringNodeBo());
        }
        return flag;
    }

    /**
     * 修改工业工程|市政工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ZEngineeringIndustryBo bo) {
        ZEngineeringIndustry update = BeanUtil.toBean(bo, ZEngineeringIndustry.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            List<ZEngiineeringPhoto> list = new ArrayList<>();
            // 查询数据库中已存在的文件列表
            ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
            zEngiineeringPhotoBo.setParentId(update.getId());
            zEngiineeringPhotoBo.setCreateTime(bo.getCreateTime());
            List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
            // 插入前端传来的新文件
            if (!ObjectUtils.isEmpty(bo.getFiles())) {
                for (ZFileBo pic : bo.getFiles()) {
                    if (!existingPhotos.contains(pic.getUrl())) {
                        ZEngiineeringPhoto newPhoto = new ZEngiineeringPhoto();
                        newPhoto.setParentId(bo.getId());
                        newPhoto.setPicUrl(pic.getUrl());
                        newPhoto.setFileName(pic.getName());
                        newPhoto.setCreateBy(String.valueOf(LoginHelper.getUserId()));
                        newPhoto.setCreateTime(bo.getCreateTime());
                        newPhoto.setUpdateTime(new Date());
                        list.add(newPhoto);
                    }
                }
                // 删除数据库中多余的文件
                List<String> photosToDelete = existingPhotos.stream().filter(pic -> !bo.getFiles().stream().map(ZFileBo::getUrl).collect(Collectors.toList()).contains(pic)).collect(Collectors.toList());
                if (!photosToDelete.isEmpty()) {
                    photosToDelete.forEach(item -> {
                        ZEngiineeringPhoto zEngiineeringPhoto = new ZEngiineeringPhoto();
                        zEngiineeringPhoto.setPicUrl(item);
                        zEngiineeringPhoto.setCreateTime(bo.getCreateTime());
                        photoService.deleteWithValid(zEngiineeringPhoto);
                    });
                }
                // 批量插入新图片
                if (!list.isEmpty()) {
                    photoService.insertBatch(list);
                }
            }
        }
        bo.getzEngineeringNodeBo().setCivliId(bo.getId());
//        bo.getzEngineeringNodeBo().setType(bo.getType());
        bo.getzEngineeringNodeBo().setCreateTime(bo.getCreateTime());
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCivliId(update.getId());
//        zEngineeringNodeBo.setType(bo.getType());
        zEngineeringNodeBo.setType(bo.getzEngineeringNodeBo().getType()); // zEngineeringNodeBo.setType(bo.getzEngineeringNodeBo().getType());
        zEngineeringNodeBo.setCreateTime(baseMapper.selectVoById(bo.getId()).getCreateTime());
        ZEngineeringNodeBo query = izEngineeringNodeService.query(zEngineeringNodeBo);
        if (!ObjectUtils.isEmpty(query)) {
            bo.getzEngineeringNodeBo().setId(query.getId());
        }
        bo.getzEngineeringNodeBo().setCreateTime(zEngineeringNodeBo.getCreateTime());
        izEngineeringNodeService.insert(bo.getzEngineeringNodeBo());
        System.out.println("izEngineeringNodeService.insert(bo.getzEngineeringNodeBo());");
        return flag;
    }

    private void batchUpdatePic(ZEngineeringIndustryBo bo,  String methodName, String type) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 获取类对象
        Class<?> cls = ZEngineeringInfoBo.class;
        // 获取指定方法
        Method method = cls.getDeclaredMethod(methodName);
//        System.out.println("method.invoke(obj);==="+method.invoke(bo.getzEngineeringNodeBo().getzEngineeringInfoBoList().get(0)));
        // 故事正文开始
        List<ZEngineeringInfoBo> zEngineeringInfoBoList = bo.getzEngineeringNodeBo().getzEngineeringInfoBoList();
        for (int i = 0; i < zEngineeringInfoBoList.size(); i++) {
            ZEngineeringInfoBo zEngineeringInfoBo = zEngineeringInfoBoList.get(i);
            if (!ObjectUtils.isEmpty(method.invoke(zEngineeringInfoBo))) {
                List<ZEngiineeringPhoto> list = new ArrayList<>();
                // 查询数据库中已存在的文件列表
                ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
                zEngiineeringPhotoBo.setCreateTime(zEngineeringInfoBo.getCreateTime());//
                zEngiineeringPhotoBo.setType(type);
                zEngiineeringPhotoBo.setParentId(zEngineeringInfoBo.getId());
                List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
                // 插入前端传来的新文件
                for (String pic : (List<String>)method.invoke(zEngineeringInfoBo)) {
                    if (!existingPhotos.contains(pic)) {
                        ZEngiineeringPhoto newPhoto = new ZEngiineeringPhoto();
                        newPhoto.setParentId(zEngineeringInfoBo.getId());
                        newPhoto.setPicUrl(pic);
                        newPhoto.setFileName(pic);
                        newPhoto.setType(type);
                        newPhoto.setCreateBy(String.valueOf(LoginHelper.getUsername()));
                        newPhoto.setCreateTime(bo.getCreateTime());
                        newPhoto.setUpdateTime(new Date());
                        list.add(newPhoto);
                    }
                }
                // 删除数据库中多余的文件
                List<String> photosToDelete = existingPhotos.stream().filter(pic -> {
                    try {
                        return !((List<String>)(method.invoke(zEngineeringInfoBo))).contains(pic);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    }
                }).collect(Collectors.toList());
                if (!photosToDelete.isEmpty()) {
                    photosToDelete.forEach(item -> {
                        ZEngiineeringPhoto zEngiineeringPhoto = new ZEngiineeringPhoto();
                        zEngiineeringPhoto.setType(type);
                        zEngiineeringPhoto.setPicUrl(item);
                        zEngiineeringPhoto.setCreateTime(bo.getCreateTime());
                        photoService.deleteWithValid(zEngiineeringPhoto);
                    });
                }
                // 批量插入新图片
                if (!list.isEmpty()) {
                    photoService.insertBatch(list);
                }
            }else {
                // 查询数据库中已存在的文件列表
                ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
                zEngiineeringPhotoBo.setCreateTime(zEngineeringInfoBo.getCreateTime());//
                zEngiineeringPhotoBo.setParentId(zEngineeringInfoBo.getId());
                zEngiineeringPhotoBo.setType(type);
                List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
                // 删除数据库中多余的文件
                List<String> photosToDelete = null;
                try {
                    photosToDelete = existingPhotos.stream().filter(pic -> {
                        try {
                            return !((List<String>)(method.invoke(zEngineeringInfoBo))).contains(pic);
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        } catch (InvocationTargetException e) {
                            throw new RuntimeException(e);
                        }
                    }).collect(Collectors.toList());
                }catch (Exception e){

                }
                if (!photosToDelete.isEmpty()) {
                    photosToDelete.forEach(item -> {
                        ZEngiineeringPhoto zEngiineeringPhoto = new ZEngiineeringPhoto();
                        zEngiineeringPhoto.setType(type);
                        zEngiineeringPhoto.setPicUrl(item);
                        zEngiineeringPhoto.setCreateTime(bo.getCreateTime());
                        photoService.deleteWithValid(zEngiineeringPhoto);
                    });
                }
            }
        }
    }

    /**
     * 修改工业工程|市政工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateNodeByBo(ZEngineeringIndustryBo bo) {
        ZEngineeringIndustry update = BeanUtil.toBean(bo, ZEngineeringIndustry.class);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            if (!ObjectUtils.isEmpty(bo.getFiles())) {
                List<ZEngiineeringPhoto> list = new ArrayList<>();
                // 查询数据库中已存在的文件列表
                ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
                zEngiineeringPhotoBo.setCreateTime(update.getCreateTime());
                zEngiineeringPhotoBo.setParentId(update.getId());
                List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
                // 插入前端传来的新文件
                for (ZFileBo pic : bo.getFiles()) {
                    if (!existingPhotos.contains(pic.getUrl())) {
                        ZEngiineeringPhoto newPhoto = new ZEngiineeringPhoto();
                        newPhoto.setParentId(bo.getId());
                        newPhoto.setPicUrl(pic.getUrl());
                        newPhoto.setFileName(pic.getName());
                        newPhoto.setCreateBy(String.valueOf(LoginHelper.getUsername()));
                        newPhoto.setCreateTime(bo.getCreateTime());
                        newPhoto.setUpdateTime(new Date());
                        list.add(newPhoto);
                    }
                }
                // 删除数据库中多余的文件
                List<String> photosToDelete = existingPhotos.stream().filter(pic -> !bo.getFiles().stream().map(ZFileBo::getUrl).collect(Collectors.toList()).contains(pic)).collect(Collectors.toList());
                if (!photosToDelete.isEmpty()) {
                    photosToDelete.forEach(item -> {
                        ZEngiineeringPhoto zEngiineeringPhoto = new ZEngiineeringPhoto();
                        zEngiineeringPhoto.setPicUrl(item);
                        zEngiineeringPhoto.setCreateTime(bo.getCreateTime());
                        photoService.deleteWithValid(zEngiineeringPhoto);
                    });
                }
                // 批量插入新图片
                if (!list.isEmpty()) {
                    photoService.insertBatch(list);
                }
            }

//            // 市政施工-沟上施工 焊接
//            public List<String> welding;
//            // 市政施工-沟上施工 防腐
//            public List<String> aczoiling;
//            // 市政施工-沟下施工 管道下沟
//            public List<String> piping;
//            // 市政施工-沟下施工 警示带铺设
//            public List<String> warning;
//            // 市政施工-沟下施工 回填
//            public List<String> backfilling;
            /**
             * 焊接照片
             * 防腐照片
             *
             */
            try {
                batchUpdatePic(bo,  "getWelding", "welding");
                batchUpdatePic(bo,  "getAczoiling", "aczoiling");
                batchUpdatePic(bo,  "getPiping", "piping");
                batchUpdatePic(bo,  "getWarning", "warning");
                batchUpdatePic(bo,  "getBackfilling", "backfilling");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (!ObjectUtils.isEmpty(bo.getzEngineeringNodeBo())){
            List<ZEngineeringInfoBo> engineeringInfoBoList1 = bo.getzEngineeringNodeBo().getzEngineeringInfoBoList();
            if (engineeringInfoBoList1 != null && !engineeringInfoBoList1.isEmpty()) {
                nodeService.updateMuch(bo.getzEngineeringNodeBo());
            }
        }
        //        bo.getzEngineeringNodeBoList().stream().forEach(item->{
        //            item.setCivliId(bo.getId());
        //            item.setCreateTime(bo.getCreateTime());
        //            item.setType(bo.getType());
        //            izEngineeringNodeService.updateMuch(item);
        //        });
        return flag;
    }


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

    /**
     * 批量删除工业工程|市政工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        ids.forEach(item -> {
            ZEngineeringIndustryVo vo = baseMapper.selectVoById(item);
            // 查询数据库中已存在的文件列表
            ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
            zEngiineeringPhotoBo.setCreateTime(vo.getCreateTime());
            zEngiineeringPhotoBo.setParentId(item);
            // 将查询出的url放入existingPhotos
            List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
            // 若存在 则进行删除
            if (!existingPhotos.isEmpty()) {
                existingPhotos.forEach(i -> {
                    photoService.deleteWithValidByurls(i);
                });
            }
            // 初始化工程节点对象
//            ZEngineeringIndustryVo vo = baseMapper.selectVoById(item);
            ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
            zEngineeringNodeBo.setCreateTime(vo.getCreateTime());
            zEngineeringNodeBo.setCivliId(vo.getId());
            //  查询数据库中已存在的工程节点
            List<ZEngineeringNodeBo> zEngineeringNodeBos = nodeService.queryListDetails(zEngineeringNodeBo);
            // 若存在 则进行删除
            if (!zEngineeringNodeBos.isEmpty()) {
                zEngineeringNodeBos.forEach(ite -> nodeService.delete(ite));
            }
        });
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public ZEngineeringIndustryVo query(String id, String type) {
        ZEngineeringIndustryVo zEngineeringIndustryVo = baseMapper.selectVoById(id);
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCreateTime(zEngineeringIndustryVo.getCreateTime());
        zEngineeringNodeBo.setCivliId(zEngineeringIndustryVo.getId());
        System.out.println("type===" + type);
        zEngineeringNodeBo.setType(type);
//        zEngineeringNodeBo.setType("trench_construction");
        zEngineeringIndustryVo.setZEngineeringNodeBo(izEngineeringNodeService.query(zEngineeringNodeBo));
        return zEngineeringIndustryVo;
    }

    @Override
    public ZEngineeringIndustryVo query(String id) {
        ZEngineeringIndustryVo zEngineeringIndustryVo = baseMapper.selectVoById(id);
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCreateTime(zEngineeringIndustryVo.getCreateTime());
        zEngineeringNodeBo.setCivliId(zEngineeringIndustryVo.getId());
        zEngineeringIndustryVo.setZEngineeringNodeBo(izEngineeringNodeService.query(zEngineeringNodeBo));
        return zEngineeringIndustryVo;
    }

    @Override
    public List<ZEngineeringIndustryTypeVo> queryNameByType(ZEngineeringIndustryBo bo) {
        LambdaQueryWrapper<ZEngineeringIndustry> zEngineeringIndustryBoLambdaQueryWrapper = buildListByType(bo);
        zEngineeringIndustryBoLambdaQueryWrapper.orderByDesc(ZEngineeringIndustry::getCreateTime);
        List<ZEngineeringIndustry> zEngineeringIndustryVos = baseMapper.selectList(zEngineeringIndustryBoLambdaQueryWrapper);
        List<ZEngineeringIndustryTypeVo> zEngineeringIndustryTypeVos = zEngineeringIndustryVos.stream().map(ZEngineeringIndustryTypeVo::new).collect(Collectors.toList());
        return zEngineeringIndustryTypeVos;
    }

    private LambdaQueryWrapper<ZEngineeringIndustry> buildListByType(ZEngineeringIndustryBo bo) {

        LambdaQueryWrapper<ZEngineeringIndustry> queryWrapper = new LambdaQueryWrapper<ZEngineeringIndustry>();
        queryWrapper.orderByDesc(ZEngineeringIndustry::getCreateTime);
        queryWrapper.eq(StringUtils.isNotBlank(bo.getEnginType()), ZEngineeringIndustry::getEnginType, bo.getEnginType());
        queryWrapper.eq(StringUtils.isNotBlank(bo.getType()), ZEngineeringIndustry::getType, bo.getType());
        if (!"null".equals(bo.getEnginClassification())) {
            queryWrapper.like(StringUtils.isNotBlank(bo.getEnginClassification()), ZEngineeringIndustry::getEnginClassification, bo.getEnginClassification());
        }

        return queryWrapper;
    }


}
