package com.ruoyi.zdsz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
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;

    @Resource
    private ZEngineeringCivilMapper zEngineeringCivilMapper;

    @Override
    public TableDataInfo<Map<String, Object>> getByUserList(String type,String enginName,String enginType,String enginProcedure,String enginStatus,PageQuery pageQuery,String nodeType,String createBy,String enginClassification) {
        Page<T> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        String leftJoin = null;
        String szAndGy = null;

        if ("1".equals(type)){
            leftJoin = "z_engineering_pipe_jacking"; // 顶管
            enginType = "";
        }
        else if ("2".equals(type)){
            leftJoin = "z_engineering_infrastructure"; // 基建
            enginType = "";
        }
        else if ("3".equals(type)){
            leftJoin = "z_engineering_dangerous"; // 危险工程
        }
        else if ("4".equals(type)){
            leftJoin = "z_engineering_industry"; // 市政工程
            enginType = "";
        }
        else if ("5".equals(type)){
            leftJoin = "z_engineering_gy"; // 工业工程
            szAndGy = "gy";
        }
        else if ("6".equals(type)){
            leftJoin = "z_engineering_air_wall"; // 带气工程
        }
        else if ("7".equals(type)){
            leftJoin = "z_touch_operation_engineering"; // 碰口工程
            szAndGy = "pk";
        }
        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 = createBy;
        Page<Map<String, Object>> listPage = null;
        if (type.equals("6")) {
            listPage = baseMapper.getByUserList1(DateList, username, leftJoin, szAndGy, page,enginName,enginType);
        } else {
            listPage = baseMapper.getByUserList(DateList, username, leftJoin, szAndGy, page,enginName,enginType,enginClassification);
        }

        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);
                });
                List<Map<String, String>> finalMapList = mapList;
                municipalEngineeringNode.forEach(ite -> {
                    String dictLabel = ite.getDictLabel();
                    List<Map<String, String>> type1 = finalMapList.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);
                        finalMapList.add(objectObjectHashMap);
                    }
                });
                mapList = finalMapList;
                if (!ObjectUtils.isEmpty(enginStatus)){
                    String s = "2".equals(enginStatus)?"未审核":"1".equals(enginStatus)?"通过":"未通过";
                    mapList = mapList.stream().filter(obj->obj.get("reviewStatus").equals(s)).collect(Collectors.toList());
                }
                if (!ObjectUtils.isEmpty(nodeType)){
                    mapList = mapList.stream().filter(obj->obj.get("type").equals(nodeType)).collect(Collectors.toList());
                }
                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);
                });
                List<Map<String, String>> finalMapList = mapList;
                municipalEngineeringNode.forEach(ite -> {
                    String dictLabel = ite.getDictLabel();
                    List<Map<String, String>> type1 = finalMapList.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);
                        finalMapList.add(objectObjectHashMap);
                    }
                });
                mapList = finalMapList;
                if (!ObjectUtils.isEmpty(enginStatus)){
                    String s = "2".equals(enginStatus)?"未审核":"1".equals(enginStatus)?"通过":"未通过";
                    mapList = mapList.stream().filter(obj->obj.get("reviewStatus").equals(s)).collect(Collectors.toList());
                }
                if (!ObjectUtils.isEmpty(nodeType)){
                    mapList = mapList.stream().filter(obj->obj.get("type").equals(nodeType)).collect(Collectors.toList());
                }
                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);
                });
                if (!ObjectUtils.isEmpty(enginStatus)){
                    String s = "2".equals(enginStatus)?"未审核":"1".equals(enginStatus)?"通过":"未通过";
                    mapList = mapList.stream().filter(obj->obj.get("reviewStatus").equals(s)).collect(Collectors.toList());
                }
                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_node_types");
                mapList.forEach(ite -> {
                    String str = "2".equals(ite.get("reviewStatus"))?"未审核":"1".equals(ite.get("reviewStatus"))?"通过":"未通过";
                    try {
                        ite.put("type",municipalEngineeringNode.stream().filter(ie-> ie.getDictValue() .equals(ite.get("type"))).collect(Collectors.toList()).get(0).getDictLabel());
                    } catch (Exception e) {
                        ite.put("type","");
                    }
                    ite.put("reviewStatus", str);
                });
                List<Map<String, String>> finalMapList = mapList;
                municipalEngineeringNode.forEach(ite -> {
                    String dictLabel = ite.getDictLabel();
                    List<Map<String, String>> type1 = finalMapList.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);
                        finalMapList.add(objectObjectHashMap);
                    }
                });
                mapList = finalMapList;
                if (!ObjectUtils.isEmpty(enginStatus)){
                    String s = "2".equals(enginStatus)?"未审核":"1".equals(enginStatus)?"通过":"未通过";
                    mapList = mapList.stream().filter(obj->obj.get("reviewStatus").equals(s)).collect(Collectors.toList());
                }
                if (!ObjectUtils.isEmpty(nodeType)){
                    mapList = mapList.stream().filter(obj->obj.get("type").equals(nodeType)).collect(Collectors.toList());
                }
                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());
                Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
                List<SysDictData> municipalEngineeringNode = new ArrayList<>();
                if (item.get("enginClassification").equals("室内管线")){
                    municipalEngineeringNode.addAll(sysDictMap.get("gy_inner"));
                }
                if (item.get("enginClassification").equals("室外管线")){
                    municipalEngineeringNode.addAll(sysDictMap.get("gy_out"));
                }
                if (item.get("enginClassification").equals("调压柜")){
                    municipalEngineeringNode.addAll(sysDictMap.get("gy_tyg"));
                }
                mapList.forEach(ite -> {
                    String str = "2".equals(ite.get("reviewStatus"))?"未审核":"1".equals(ite.get("reviewStatus"))?"通过":"未通过";
                    try {
                        ite.put("type",municipalEngineeringNode.stream().filter(ie-> ie.getDictValue() .equals(ite.get("type"))).collect(Collectors.toList()).get(0).getDictLabel());
                    } catch (Exception e) {
                        ite.put("type","");
                    }
                    ite.put("reviewStatus", str);
                });
                List<Map<String, String>> finalMapList = mapList;
                municipalEngineeringNode.forEach(ite -> {
                    String dictLabel = ite.getDictLabel();
                    List<Map<String, String>> type1 = finalMapList.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);
                        finalMapList.add(objectObjectHashMap);
                    }
                });
                mapList = finalMapList;
                if (!ObjectUtils.isEmpty(enginStatus)){
                    String s = "2".equals(enginStatus)?"未审核":"1".equals(enginStatus)?"通过":"未通过";
                    mapList = mapList.stream().filter(obj->obj.get("reviewStatus").equals(s)).collect(Collectors.toList());
                }
                if (!ObjectUtils.isEmpty(nodeType)){
                    mapList = mapList.stream().filter(obj->obj.get("type").equals(nodeType)).collect(Collectors.toList());
                }
                item.put("status",mapList);
                MonthTableNameHandler.removeData();
            });
            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()));
                Map<String, List<SysDictData>> sysDictMap = RedisUtils.getCacheMap("sys_dict");
                List<SysDictData> municipalEngineeringNode = sysDictMap.get("air_wall_node");

                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);
                });
                if (!ObjectUtils.isEmpty(enginStatus)){
                    String s = "2".equals(enginStatus)?"未审核":"1".equals(enginStatus)?"通过":"未通过";
                    mapList = mapList.stream().filter(obj->obj.get("reviewStatus").equals(s)).collect(Collectors.toList());
                }
                item.put("status",mapList);
            });
            MonthTableNameHandler.removeData();
        }
        else if ("7".equals(type)){ // 带气封堵

            listPage.getRecords().forEach(item -> {
                String modeOperation = item.get("modeOperation").toString();
                String dists = "";
                if ("地埋扳孔".equals(modeOperation)){
                    dists="bury_the_wrench_hole";
                }else if ("架空扳孔".equals(modeOperation)){
                    dists="aerial_wrench_hole";
                }else if ("停气作业".equals(modeOperation)){
                    dists="shutdown_operation";
                }else if ("PE 封堵".equals(modeOperation)){
                    dists="pe_plugging";
                }else if ("钢管带气封堵".equals(modeOperation)){
                    dists="the_steel_pipe_sealed_with_gas";
                }
                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(dists);
                mapList.forEach(ite -> {
                    String str = "2".equals(ite.get("reviewStatus"))?"未审核":"1".equals(ite.get("reviewStatus"))?"通过":"未通过";
                    try {
                        ite.put("type",municipalEngineeringNode.stream().filter(ie-> ie.getDictValue() .equals(ite.get("type"))).collect(Collectors.toList()).get(0).getDictLabel());
                    } catch (Exception e) {
                        ite.put("type","");
                    }
                    ite.put("reviewStatus", str);
                });
                List<Map<String, String>> finalMapList = mapList;
                municipalEngineeringNode.forEach(ite -> {
                    String dictLabel = ite.getDictLabel();
                    List<Map<String, String>> type1 = finalMapList.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);
                        finalMapList.add(objectObjectHashMap);
                    }
                });
                mapList = finalMapList;
                if (!ObjectUtils.isEmpty(enginStatus)){
                    String s = "2".equals(enginStatus)?"未审核":"1".equals(enginStatus)?"通过":"未通过";
                    mapList = mapList.stream().filter(obj->obj.get("reviewStatus").equals(s)).collect(Collectors.toList());
                }
                if (!ObjectUtils.isEmpty(nodeType)){
                    mapList = mapList.stream().filter(obj->obj.get("type").equals(nodeType)).collect(Collectors.toList());
                }
                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);
        Map<String, Object> ReviewList;
        ReviewList = nodeService.ReViewSZList(result.getRecords());
        result.getRecords().forEach(item -> {
            item.setNodeReViewStateList(ReviewList.get(item.getId()));
        });
        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());
        return lqw;
    }

    /**
     * 新增市政工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ZEngineeringIndustryBo bo) {
        ZEngineeringIndustry add = BeanUtil.toBean(bo, ZEngineeringIndustry.class);
        validEntityBeforeSave(add);
        if (StringUtils.isEmpty(bo.getId())){
            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;
        }
        else if (StringUtils.isNotBlank(bo.getId())){
            ZEngineeringIndustryVo voById = baseMapper.selectVoById(bo.getId());
            List<ZEngineeringNodeBo> zEngineeringNodeBoList = bo.getzEngineeringNodeBoList();
            ZEngineeringNodeBo entity = bo.getzEngineeringNodeBo();
            //pc
            if (!ObjectUtils.isEmpty(zEngineeringNodeBoList)) {
                for (ZEngineeringNodeBo zEngineeringNodeBo : zEngineeringNodeBoList) {
                    zEngineeringNodeBo.setCivliId(voById.getId());
                    zEngineeringNodeBo.setCreateTime(voById.getCreateTime());
                    ZEngineeringNodeBo query = izEngineeringNodeService.query(zEngineeringNodeBo);
                    if (!ObjectUtils.isEmpty(query)) {
                        zEngineeringNodeBo.setId(query.getId());
                    }
                    izEngineeringNodeService.insert(zEngineeringNodeBo);
                }
            }
            //uniapp
            if (!ObjectUtils.isEmpty(entity)) {
                entity.setCivliId(voById.getId());
                entity.setCreateTime(voById.getCreateTime());
                ZEngineeringNodeBo query = izEngineeringNodeService.query(entity);
                if (!ObjectUtils.isEmpty(query)) {
                    entity.setId(query.getId());
                }
                izEngineeringNodeService.insert(entity);
            }
            return true;
        }
        return false;
    }

    /**
     * 修改市政工程
     */
    @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;
        ZEngineeringIndustryVo voById = baseMapper.selectVoById(bo.getId());
        bo.setCreateTime(voById.getCreateTime());
        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);
                }
            }
        }
        //节点表与info表
        if (!ObjectUtils.isEmpty(bo.getzEngineeringNodeBo())) {
            bo.getzEngineeringNodeBo().setCreateTime(voById.getCreateTime());
            izEngineeringNodeService.update(bo.getzEngineeringNodeBo());
        }
        return flag;
    }


    /**
     * 修改市政工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateNodeByBo(ZEngineeringIndustryBo bo) {
        ZEngineeringIndustry update = BeanUtil.toBean(bo, ZEngineeringIndustry.class);
        boolean flag = baseMapper.updateById(update) > 0;
        ZEngineeringIndustryVo voById = baseMapper.selectVoById(bo.getId());
        bo.setCreateTime(voById.getCreateTime());
        if (flag) {
            if (!ObjectUtils.isEmpty(bo.getFiles())) {
                List<ZEngiineeringPhoto> list = new ArrayList<>();
                // 查询数据库中已存在的文件列表
                ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
                zEngiineeringPhotoBo.setCreateTime(bo.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);
                }
            }
        }
        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.setParentId(item);
            zEngiineeringPhotoBo.setCreateTime(vo.getCreateTime());
            // 将查询出的url放入existingPhotos
            List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
            // 若存在 则进行删除
            if (!existingPhotos.isEmpty()) {
                existingPhotos.forEach(i -> {
                    photoService.deleteWithValidByurls(i);
                });
            }
            // 初始化工程节点对象

            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());
        zEngineeringNodeBo.setType(type);
        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);
        List<ZEngineeringIndustry> zEngineeringIndustryVos = baseMapper.selectList(zEngineeringIndustryBoLambdaQueryWrapper);
        return zEngineeringIndustryVos.stream().map(ZEngineeringIndustryTypeVo::new).collect(Collectors.toList());
    }

    @Override
    public List<Map<String,String>> getByUserListAndDicts(String dictType) {
        return baseMapper.getDicts(dictType);
    }

    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());
        return queryWrapper;
    }


}
