xingjinshuang
2025-02-20 4ffb61934bd556bb681b96bcc5c690105000ed5e
src/main/java/com/se/simu/controller/SimuController.java
@@ -1,35 +1,43 @@
package com.se.simu.controller;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.io.Resources;
import com.se.simu.config.PropertiesConfig;
import com.se.simu.domain.dto.GeDb;
import com.se.simu.domain.dto.GeLayer;
import com.se.simu.domain.dto.GridDto;
import com.se.simu.domain.po.DataPo;
import com.se.simu.domain.po.SimuPo;
import com.se.simu.domain.vo.CreateSimuVo;
import com.se.simu.domain.vo.R;
import com.se.simu.domain.vo.SimuVo;
import com.se.simu.helper.StringHelper;
import com.se.simu.service.GedbService;
import com.se.simu.service.ResultService;
import com.se.simu.service.SimuService;
import com.se.simu.service.UwService;
import com.se.simu.domain.vo.*;
import com.se.simu.enums.RadioEnums;
import com.se.simu.service.*;
import com.se.simu.utils.*;
import io.swagger.annotations.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
/**
 * 仿真管理
 *
 * @author WWW
 * @date   2024-09-18
 */
@Api(tags = "仿真管理")
@Slf4j
@RestController
@@ -46,6 +54,22 @@
    SimuService simuService;
    @Resource
    SimuFilesService simuFilesService;
    @Resource
    PropertiesConfig config;
    @Value("${simu-app.filePath}")
    private String uploadedFolder;
    @Value("${config.outPath}")
    private String outPath;
    @Value("${config.inPath}")
    private String inPath;
    @Resource
    ResultService resultService;
    private final List<String> FLOOD_TYPE = new ArrayList<>(Arrays.asList("沙袋", "防水板"));
@@ -57,17 +81,14 @@
            if (null == vo.getTotal() || vo.getTotal() < 1 || vo.getTotal() > 1000) {
                return fail("降雨量不能为空,且取值在1~1000之间");
            }
            if (null == vo.getDuration() || vo.getDuration() < 1 || vo.getDuration() > 120) {
                return fail("仿真时长不能为空,且取值在1~120之间");
            if (null == vo.getDuration() || vo.getDuration() < 1 || vo.getDuration() > 10080) {
                return fail("仿真时长不能为空,且取值在1~10080之间");
            }
            if (null == vo.getMinx() || null == vo.getMiny() || null == vo.getMaxx() || null == vo.getMaxy()) {
                return fail("选择范围不能为空", false);
            }
            if (null == vo.getPid() || vo.getPid() < 0) {
                vo.setPid(0);
            }
            if (StringHelper.isEmpty(vo.getName())) {
                vo.setName(StringHelper.YMDHMS2_FORMAT.format(new Date()));
            }
            if (null == vo.getNum() || vo.getNum() < 1) {
                vo.setNum(simuService.getMaxId() + 1);
@@ -152,71 +173,12 @@
        }
    }
    @ApiOperation(value = "当前时间 *")
    @GetMapping("/getTime")
    public Object getTime() {
        return System.currentTimeMillis();
    }
    @ApiOperation(value = "testCallExe *")
    @GetMapping("/testCallExe")
    public R<Object> testCallExe() {
        try {
            DataPo data = new DataPo();
            data.setInPath("20241010095328");
            String str = uwService.callExe(data);
            return success(str);
        } catch (Exception ex) {
            return fail(ex, null);
        }
    }
    @ApiOperation(value = "testResuslt *")
    @GetMapping("/testResuslt")
    public R<Object> testResuslt() {
        try {
            DataPo data = new DataPo();
            data.setEpsg(4548);
            data.setInPath("20241010095328");
            data.setStartTime(StringHelper.YMDHMS_FORMAT.parse("2024-09-30 00:00:00"));
            resultService.process(data);
            return success("ok");
        } catch (Exception ex) {
            return fail(ex, null);
        }
    }
    @ApiOperation(value = "testSww2Tif *")
    @GetMapping("/testSww2Tif")
    public R<Object> testSww2Tif() {
        try {
            DataPo data = new DataPo();
            data.setEpsg(4548);
            data.setInPath("20241010095328");
            data.setStartTime(StringHelper.YMDHMS_FORMAT.parse("2024-09-30 00:00:00"));
            Object rs = uwService.copeDrainFiles(data);
            return success(rs);
        } catch (Exception ex) {
            return fail(ex, null);
        }
    }
    /**
     * 使用空间范围查询 管点,管线,建筑物 3个图层,且每个图层的数量大于0,返回 true。
     */
    @ApiOperation(value = "降水范围校验")
    @GetMapping("/rangeVerif")
    public R<Object> rangeVerif(@RequestParam @ApiParam("最小X")  Double minx,
                                @RequestParam @ApiParam("最小y")  Double miny,
                                @RequestParam @ApiParam("最大X")  Double maxx,
                                @RequestParam @ApiParam("最大y")  Double maxy) {
    @GetMapping("/rangeVerify")
    public R<Object> rangeVerify(@RequestParam @ApiParam("最小X") double minx,
                                 @RequestParam @ApiParam("最小y") double miny,
                                 @RequestParam @ApiParam("最大X") double maxx,
                                 @RequestParam @ApiParam("最大y") double maxy) {
        try {
            DataPo data = new DataPo();
            data.setMinx(minx);
@@ -224,12 +186,772 @@
            data.setMaxx(maxx);
            data.setMaxy(maxy);
            data.setEpsg(4326);
            String token = gedbService.getToken();
            GeDb db = gedbService.connectGedb(token, data);
            List<GeLayer> layers = gedbService.getLayers(token, db);
            return success(gedbService.queryBboxCount(token,db, layers));
            boolean result = gedbService.queryBboxCount(token, db, layers);
            log.info("result = " + result);
            return success(result);
            //  return success(gedbService.queryBboxCount(token, db, layers));
        } catch (Exception ex) {
            return fail(ex, false);
        }
    }
    /**
     * 文件创建模拟
     * <p>
     * "状态:
     * 0-创建仿真任务,
     * 1-连接GEDB库,
     * 2-下载空间数据,
     * 3-下载高程数据,
     * 4-生成降雨文件,
     * 5-生成配置文件,
     * 6-模拟内涝仿真,
     * 7-处理水位文件,
     * 8-处理排水文件,
     * 9-处理仿真结果,
     * 10-完成,-10-出错
     *
     * @param vo VO
     * @return {@link R}<{@link Object}>
     */
    @ApiOperation(value = "文件创建")
    @PostMapping(value = "/file_create", produces = "application/json; charset=UTF-8")
    public R<Object> fileCreate(@RequestBody @ApiParam("创建仿真视图类") CreateFilesSimuVo vo) throws IOException {
        // 获取上传文件路径
        String targetDir = uploadedFolder;
        log.info("上传文件路径:{}", targetDir);
        // 获取各个文件的地址
        String floodFile = vo.getFloodFile();
        log.info("范围文件地址:{}", floodFile);
        try {
            // 判断是否绘制区域
            if (!StringUtils.isEmpty(vo.getMaxx().toString()) && !Objects.isNull(vo.getMaxx())) {
                rangeVerify(vo.getMinx(), vo.getMaxx(), vo.getMiny(), vo.getMaxy());
                log.info("绘制区域范围验证通过!");
            } else
                // 判断地址不为空
                if (StringUtils.isEmpty(floodFile)) {
                    return fail("范围文件地址不能为空", false);
                } else {
                    // todo: 解析范围文件 根据不同的的格式文件进行不同的解析,获取需要计算的范围值
                    //  上传格式:.shp/.tiff/.img/.geojson
                    //  重新给vo赋值
                    // 获取文件的后缀名
                    String fileName = floodFile.substring(floodFile.lastIndexOf("."));
                    // 判断后缀名是否为.shp
                    if (!fileName.equalsIgnoreCase(".shp")) {
                        return fail("范围文件格式不正确", false);
                    } else {
                        // 1 读取shp文件,获取范围值
                        JSONObject jsonObject = ShpToolUtils.readShp(floodFile);
                        // 2 获取jsonObject中的范围值
                        Double minX = jsonObject.getDouble("minY");
                        Double maxX = jsonObject.getDouble("maxY");
                        Double minY = jsonObject.getDouble("minX");
                        Double maxY = jsonObject.getDouble("maxX");
                        // 3 判断范围值是否为空
                        vo.setMinx(jsonObject.getDouble("minY"));
                        vo.setMaxx(jsonObject.getDouble("maxY"));
                        vo.setMiny(jsonObject.getDouble("minX"));
                        vo.setMaxy(jsonObject.getDouble("maxX"));
                        rangeVerify(minX, maxX, minY, maxY);
                    }
                }
        } catch (Exception e) {
            log.error("解析范围文件失败");
            if (null == vo.getMinx() || null == vo.getMiny() || null == vo.getMaxx() || null == vo.getMaxy()) {
                return fail("解析范围文件失败!选择范围不能为空,请重新选择文件!", false);
            }
        }
        String stationFile = vo.getStationFile();
        log.info("站点文件shp地址:{}", stationFile);
        try {
            if (RadioEnums.ACCESS.getCode().equals(vo.getRadio()) && StringUtils.isNotEmpty(stationFile)) {
                // 1 读取shp文件,获取站点坐标值
                ShpToolUtils.readShpGetLocal(stationFile);
            }
        } catch (Exception e) {
            log.error("解析站点文件shp失败");
        }
        // 创建表名 时间戳
        String tableName = "station_rain_" + System.currentTimeMillis();
        try {
            //接入处理
            if (RadioEnums.ACCESS.getCode().equals(vo.getRadio())) {
                String stationRainFile = vo.getStationRainFile();
                log.info("站点雨量CSV文件地址:{}", floodFile);
                // 判断地址不为空
                if (StringUtils.isEmpty(stationRainFile)) {
                    return fail("站点雨量CSV文件地址不能为空", false);
                }
                // 1 读取CSV 文件
                CsvToSQLiteUtils.readCsvSaveLocal(stationRainFile, tableName);
                // 获取仿真时间 duration
                Integer duration = CsvToSQLiteUtils.getDuration(tableName);
                log.info("仿真时间 duration = {}", duration);
                vo.setDuration(duration);
                // 获取降雨总量 total
                Double total = CsvToSQLiteUtils.getTotal(tableName);
                log.info("降雨总量 total = {}", total);
                vo.setTotal(total);
            } else if (RadioEnums.SIMULATE.getCode().equals(vo.getRadio())) {
                if (StringUtils.isEmpty(vo.getStation())) {
                    return fail("模拟计算站点不能为空!", false);
                }
                if (vo.getTotal() == null) {
                    return fail("模拟计算降雨量不能为空!", false);
                }
                if (vo.getDuration() == null || vo.getDuration() <= 0) {
                    return fail("模拟计算计算时长不能为空!", false);
                }
                if (vo.getStationLatitude() == null) {
                    return fail("模拟计算计算坐标!", false);
                }
                if (vo.getStationLongitude() == null) {
                    return fail("模拟计算计算坐标!", false);
                }
                double aveTotal = BigDecimal.valueOf(vo.getTotal()).divide(BigDecimal.valueOf(vo.getDuration()), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
                JSONArray jsonArray = new JSONArray();
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
                for (int i = 0; i < vo.getDuration(); i++) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("stationName", vo.getStation());
                    jsonObject.put("rainfall", aveTotal);
                    jsonObject.put("longitude", vo.getStationLongitude());
                    jsonObject.put("latitude", vo.getStationLatitude());
                    LocalDateTime plusMinutes = now.plusMinutes(i);
                    jsonObject.put("datetime", customFormatter.format(plusMinutes));
                    jsonArray.add(jsonObject);
                }
                CsvToSQLiteUtils.readCsvSaveLocal(jsonArray, tableName);
            } else {
                return fail("无效的模型计算方式", false);
            }
        } catch (Exception e) {
            return fail("雨量处理失败!", false);
        }
        // TODO: 2024/12/24 根据这些文件的地址,获取文件内容,创建仿真视图
        try {
            if (null == vo.getDuration() || vo.getDuration() < 1 || vo.getDuration() > 10080) {
                return fail("仿真时长不能为空,且取值在1~10080之间");
            }
            if (null == vo.getPid() || vo.getPid() < 0) {
                vo.setPid(0);
            }
            if (null == vo.getNum() || vo.getNum() < 1) {
                vo.setNum(simuService.getMaxId() + 1);
            }
            if (null == vo.getStartTime()) {
                vo.setStartTime(new Date());
            }
            // 防汛作业
            if (vo.getPid() > 0) {
                SimuPo pp = simuService.getSimuByPid(vo.getPid());
                if (null == pp) {
                    return fail("pid不存在");
                }
                if (null == vo.getFloodStart() || vo.getFloodStart() < 1 || vo.getFloodStart() > vo.getDuration() * 60) {
                    return fail("防汛开始时间不能为空,且取值在1~" + (vo.getDuration() * 60) + "之间");
                }
                if (null == vo.getFloodEnd() || vo.getFloodEnd() < vo.getFloodStart() || vo.getFloodEnd() > vo.getDuration() * 60) {
                    return fail("防汛结束时间不能为空,且取值在" + vo.getFloodStart() + "~" + (vo.getDuration() * 60) + "之间");
                }
                if (null == vo.getFloodHeight() || vo.getFloodHeight() < 1 || vo.getFloodHeight() > 2000) {
                    return fail("防汛高度不能为空,且取值在1~2000之间");
                }
                if (!FLOOD_TYPE.contains(vo.getFloodType())) {
                    return fail("防汛类型不能为空,且只能是沙袋和防水板");
                }
                if (null == vo.getFloodMinx() || null == vo.getFloodMiny() || null == vo.getFloodMaxx() || null == vo.getFloodMaxy()) {
                    return fail("防汛范围不能为空", false);
                }
            }
            if (StringUtils.isEmpty(vo.getSemUrl())) {
                return fail("sem文件生成路径不能为空!", false);
            }
            List<GridDto> dtos = new ArrayList<>();
            dtos.add(new GridDto(vo.getMiny(), vo.getMinx()));
            dtos.add(new GridDto(vo.getMaxy(), vo.getMinx()));
            dtos.add(new GridDto(vo.getMaxy(), vo.getMaxx()));
            dtos.add(new GridDto(vo.getMiny(), vo.getMaxx()));
            String bbox = "";
            //生成点和线的实体库模型并保存路径
            String name = vo.getSemUrl();
            String token = EntityLibraryUtils.login();
            vo.setPointName(name + "-point");
            vo.setLinkName(name + "-line");
            JSONArray min = ProjectionToGeographicUtil.get4548Point(dtos.get(0).getLon(), dtos.get(0).getLat());
            JSONArray max = ProjectionToGeographicUtil.get4548Point(dtos.get(2).getLon(), dtos.get(2).getLat());
            bbox = bbox + min.getDouble(0) + "," + min.getDouble(1) + "," + max.getDouble(0) + "," + max.getDouble(1);
            JSONObject point = getModule("layerQueryPointParams.json");
            String pointUrl = assemble(vo.getPointName(), point.getString("layerid"), bbox, token);
            vo.setPointName(pointUrl);
            JSONObject link = getModule("layerQueryParams.json");
            String linkUrl = assemble(vo.getLinkName(), link.getString("layerid"), bbox, token);
            vo.setLinkName(linkUrl);
            asyncCall(tableName, dtos, vo, token);
            // 开始模拟计算
            boolean flag = simuFilesService.createByfiles(vo);
            return success(flag, flag ? "成功" : "失败");
        } catch (Exception ex) {
            return fail(ex, null);
        }
    }
    @ApiOperation(value = "获取点路径")
    @GetMapping("/getPointUrl")
    public R<String> getPointUrl(@RequestParam("id") Integer id) throws Exception {
        SimuPo po = simuService.getSimuById(id);
        String token = EntityLibraryUtils.login();
        if (po != null) {
            return success(po.getPointUrl().replace("{token}", token));
        }
        return success(null);
    }
    @ApiOperation(value = "获取线路径")
    @GetMapping("/getLineUrl")
    public R<String> getLineUrl(@RequestParam("id") Integer id) throws Exception {
        SimuPo po = simuService.getSimuById(id);
        String token = EntityLibraryUtils.login();
        if (po != null) {
            return success(po.getLinkUrl().replace("{token}", token));
        }
        return success(null);
    }
    private void asyncCall(String tableName, List<GridDto> dtos, CreateFilesSimuVo vo, String token) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(new Runnable() {
            @Override
            @SneakyThrows
            public void run() {
                createSem(tableName, dtos, vo, token);
            }
        });
        executor.shutdown();
    }
    public void createSem(String tableName, List<GridDto> dtos, CreateFilesSimuVo vo, String token) throws Exception {
        vo.setSemUrl(inPath + "\\" + vo.getSemUrl());
        boolean ends = vo.getSemUrl().endsWith("\\");
        if (!ends) {
            vo.setSemUrl(vo.getSemUrl() + "\\");
        }
        File file = new File(vo.getSemUrl());
        if (!file.exists()) {
            file.mkdirs();
        }
        //降雨文件生成
        saveZarr(tableName, vo.getSemUrl());
        //管点生成
        pointTosem(dtos, token, vo.getSemUrl());
        //管线生成
        lineToSem(dtos, token, vo.getSemUrl());
        //范围生成
        gridToCityJson(dtos, vo.getSemUrl());
        //河流生成
        riverToSem(vo.getSemUrl());
        //土地利用生成
        landuseToSem(vo.getSemUrl());
        //地形生成
        terrainToSem(dtos, vo.getSemUrl());
    }
    public String assemble(String name, String layerid, String bbox, String token) throws Exception {
        JSONObject jsonObject = EntityLibraryUtils.createAssemble(name, token);
        String packageid = jsonObject.getString("packageid");
        EntityLibraryUtils.addAssemble(layerid, token, packageid, bbox);
        JSONObject result = EntityLibraryUtils.submitAssemble(token, packageid);
        Random random = new Random();
        int randomNumber = random.nextInt(90000) + 10000;
        String url = "http://106.120.22.26:8024/geo-service/package/3d/normal/85257774fdb64e5f99f6778696cad02a/" + packageid + "/" + layerid + "//l0/tileset.json?r=" + randomNumber + "&token={token}";
        return url;
    }
    public R<String> saveZarr(String tableName, String semUrl) throws Exception {
        List<String> list = CsvToSQLiteUtils.getNameList(tableName);
        String path = outPath + "\\";
        String rainfall = "rainfall\\";
        String basePath = path + tableName + "\\" + rainfall;
        JSONObject jsonObject = getModule("rainfallmodule.json");
        String startTime = null;
        String endTime = null;
        for (String src : list
        ) {
            File directories = new File(basePath);
            if (!directories.exists()) {
                directories.mkdirs();
                System.out.println("Directories created successfully.");
            } else {
                System.out.println("Directories already exist.");
            }
            List<StationRainVo> stationRainVos = CsvToSQLiteUtils.getList(tableName, src);
            if (startTime == null) {
                startTime = stationRainVos.get(0).getDatetime();
            }
            if (endTime == null) {
                endTime = stationRainVos.get(stationRainVos.size() - 1).getDatetime();
            }
            ZarrUtils.saveZarrRainfall(basePath + src, stationRainVos);
            ZarrUtils.saveZarrTime(basePath + src, stationRainVos);
            ZipUtils.toZarr(basePath + src, basePath + src + ".zip");
            System.out.println(src + "的zarr数据生成=====================");
            //json拼装
            String uuid = "UUID_" + UUID.randomUUID().toString();
            //拼装zarr
            JSONObject dynamizer = new JSONObject();
            dynamizer.put("url", rainfall.replace("\\", "/") + src + ".zarr");
            dynamizer.put("gmlId", uuid);
            jsonObject.getJSONArray("Dynamizers").add(dynamizer);
            //拼装坐标
            JSONArray vertice = new JSONArray();
            vertice.add(stationRainVos.get(0).getLongitude());
            vertice.add(stationRainVos.get(0).getLatitude());
            vertice.add(0.0);
            jsonObject.getJSONArray("vertices").add(vertice);
            //拼装基础信息
            JSONObject cityObject = new JSONObject();
            cityObject.put("type", "+Rainfall");
            JSONObject attribute = new JSONObject();
            attribute.put("name", src);
            cityObject.put("attributes", attribute);
            JSONArray geometry = new JSONArray();
            JSONObject metry = new JSONObject();
            metry.put("type", "MultiPoint");
            metry.put("lod", 0);
            JSONArray boundarie = new JSONArray();
            boundarie.add(jsonObject.getJSONArray("vertices").size() - 1);
            metry.put("boundaries", boundarie);
            geometry.add(metry);
            cityObject.put("geometry", geometry);
            jsonObject.getJSONObject("CityObjects").put(uuid, cityObject);
        }
        File jsonFile = new File(path + tableName + "\\降雨量.json");
        if (jsonFile.exists()) {
            jsonFile.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(path + tableName + "\\降雨量.json");
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        SemUtils.cityJsonToSem(path + tableName + "\\降雨量.json", semUrl + "raingage.sem");
        getConfigJson(startTime, endTime, semUrl);
        return success(semUrl + "raingage.sem");
    }
    public void getConfigJson(String startTime, String endTime, String semUrl) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        Date start = sdf.parse(startTime);
        Date end = sdf.parse(endTime);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        JSONObject jsonObject = getModule("config.json");
        jsonObject.put("start_datetime", simpleDateFormat.format(start));
        jsonObject.put("end_datetime", simpleDateFormat.format(end));
        FileWriter fileWriter = new FileWriter(semUrl + "\\config.json");
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
    }
    public R<String> pointTosem(List<GridDto> dtos, String token, String semUrl) throws Exception {
        String path = outPath + "\\point\\";
        String publicKey = EntityLibraryUtils.getPublicKey();
        JSONArray jsonArrayList = EntityLibraryUtils.getPointInfo(dtos, token);
        JSONObject jsonObject = getModule("pointmodule.json");
        for (int s = 0; s < jsonArrayList.size(); s++) {
            JSONObject pointObject = jsonArrayList.getJSONObject(s);
            //拼装坐标
            JSONArray vertice = new JSONArray();
            vertice.add(Double.valueOf(pointObject.getString("lon")));
            vertice.add(Double.valueOf(pointObject.getString("lat")));
            vertice.add(0.0);
            jsonObject.getJSONArray("vertices").add(vertice);
            //拼装基础信息
            JSONObject cityObject = new JSONObject();
            cityObject.put("type", "+PipePoint");
            JSONObject attribute = new JSONObject();
            attribute.put("维护时间", pointObject.get("operatetime"));
            attribute.put("维护人", pointObject.get("operator"));
            attribute.put("唯一编码", pointObject.get("seid"));
            attribute.put("ID", pointObject.get("id"));
            attribute.put("enti_uuid", pointObject.get("enti_uuid"));
            attribute.put("标识码", pointObject.get("bsm"));
            attribute.put("管线种类", pointObject.get("gxzl"));
            attribute.put("地面高程", pointObject.get("dmgc"));
            attribute.put("特征", pointObject.get("tz"));
            attribute.put("附属物", pointObject.get("fsw"));
            attribute.put("建筑物", pointObject.get("jzw"));
            attribute.put("井底高程", pointObject.get("jdgc"));
            attribute.put("井底埋深", pointObject.get("jdms"));
            attribute.put("井脖埋深", pointObject.get("jbms"));
            attribute.put("井盖形状", pointObject.get("jgxz"));
            attribute.put("井盖尺寸", pointObject.get("jgcc"));
            attribute.put("井盖材质", pointObject.get("jgcz"));
            attribute.put("井盖状态", pointObject.get("jgzt"));
            attribute.put("井脖材质", pointObject.get("jbcz"));
            attribute.put("井脖尺寸", pointObject.get("jbcc"));
            attribute.put("井材质", pointObject.get("jcz"));
            attribute.put("井尺寸", pointObject.get("jcc"));
            attribute.put("使用状况", pointObject.get("syzk"));
            attribute.put("lon", Double.valueOf(pointObject.getString("lon")));
            attribute.put("lat", Double.valueOf(pointObject.getString("lat")));
            attribute.put("atti", pointObject.get("atti"));
            attribute.put("雨水集结点", pointObject.get("ysjjd"));
            cityObject.put("attributes", attribute);
            JSONArray geometry = new JSONArray();
            JSONObject metry = new JSONObject();
            metry.put("type", "MultiPoint");
            metry.put("lod", 0);
            JSONArray boundarie = new JSONArray();
            boundarie.add(jsonObject.getJSONArray("vertices").size() - 1);
            metry.put("boundaries", boundarie);
            geometry.add(metry);
            cityObject.put("geometry", geometry);
            jsonObject.getJSONObject("CityObjects").put("UUID_" + UUID.randomUUID().toString(), cityObject);
        }
        long times = System.currentTimeMillis();
        String pointPath = path + times + "\\管点.json";
        File dirFile = new File(path + times);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        FileWriter fileWriter = new FileWriter(pointPath);
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        SemUtils.cityJsonToSem(pointPath, semUrl + "node.sem");
        return success(semUrl + "node.sem");
    }
    public R<String> pointToCityJson(String shpPath) throws Exception {
        String path = outPath + "\\point\\";
        List<Map<String, Object>> list = ShpReadUtils.readPointShp(shpPath);
        JSONObject jsonObject = getModule("pointmodule.json");
        for (Map<String, Object> map : list
        ) {
            //拼装坐标
            JSONArray vertice = new JSONArray();
            vertice.add(map.get("lon"));
            vertice.add(map.get("lat"));
            vertice.add(0.0);
            jsonObject.getJSONArray("vertices").add(vertice);
            //拼装基础信息
            JSONObject cityObject = new JSONObject();
            cityObject.put("type", "+PipePoint");
            JSONObject attribute = new JSONObject();
            attribute.put("name", map.get("fsw"));
            cityObject.put("attributes", attribute);
            JSONArray geometry = new JSONArray();
            JSONObject metry = new JSONObject();
            metry.put("type", "MultiPoint");
            metry.put("lod", 0);
            JSONArray boundarie = new JSONArray();
            boundarie.add(jsonObject.getJSONArray("vertices").size() - 1);
            metry.put("boundaries", boundarie);
            geometry.add(metry);
            cityObject.put("geometry", geometry);
            jsonObject.getJSONObject("CityObjects").put("UUID_" + UUID.randomUUID().toString(), cityObject);
        }
        long times = System.currentTimeMillis();
        String pointPath = path + times + "\\管点.json";
        File dirFile = new File(path + times);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        FileWriter fileWriter = new FileWriter(pointPath);
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        String filePatn = inPath + "\\tongzhou\\";
        File file = new File(filePatn);
        if (!file.exists()) {
            file.mkdirs();
        }
        SemUtils.cityJsonToSem(pointPath, filePatn + "node.sem");
        return success(filePatn + "node.sem");
    }
    public R<String> lineToSem(List<GridDto> dtos, String token, String semUrl) throws Exception {
        String path = outPath + "\\line\\";
        String publicKey = EntityLibraryUtils.getPublicKey();
        JSONArray jsonArrayList = EntityLibraryUtils.getLineInfo(dtos, token);
        if (jsonArrayList.size() == 0) {
            return fail("该区域不存在管线!");
        }
        StringBuffer stringBuffer = new StringBuffer("id in (");
        for (int i = 0; i < jsonArrayList.size(); i++) {
            jsonArrayList.getJSONObject(i).getInteger("id");
            stringBuffer.append("'" + jsonArrayList.getJSONObject(i).getInteger("id") + "',");
        }
        String sql = stringBuffer.toString();
        sql = sql.substring(0, sql.length() - 1) + ")";
        StringBuffer paramBuffer = new StringBuffer("");
        while (!"".equals(sql)) {
            if (sql.length() > 110) {
                String item = sql.substring(0, 110);
                paramBuffer.append(EntityLibraryUtils.encrypt(item, publicKey) + ",");
                sql = sql.replace(item, "");
            } else {
                paramBuffer.append(EntityLibraryUtils.encrypt(sql, publicKey) + ",");
                sql = "";
            }
        }
        String src = paramBuffer.toString().substring(0, paramBuffer.length() - 1);
        JSONArray arrayDetail = EntityLibraryUtils.getLineDetail(src, token);
        JSONObject jsonObject = getModule("linemodule.json");
        for (int i = 0; i < arrayDetail.size(); i++) {
            JSONObject detailJSONObject = arrayDetail.getJSONObject(i);
            //拼装基础信息
            JSONObject cityObject = new JSONObject();
            cityObject.put("type", "+PipeLine");
            JSONObject attribute = new JSONObject();
            attribute.put("维护时间", detailJSONObject.getJSONObject("properties").getLong("operatetime"));
            attribute.put("维护人", detailJSONObject.getJSONObject("properties").getString("operator"));
            attribute.put("唯一编码", detailJSONObject.getJSONObject("properties").get("seid"));
            attribute.put("ENTI_UUID", detailJSONObject.getJSONObject("properties").get("enti_uuid"));
            attribute.put("ID", detailJSONObject.getJSONObject("properties").get("id"));
            attribute.put("lon", detailJSONObject.getJSONObject("properties").get("lon"));
            attribute.put("lat", detailJSONObject.getJSONObject("properties").get("lat"));
            attribute.put("atti", detailJSONObject.getJSONObject("properties").get("atti"));
            attribute.put("管线种类", detailJSONObject.getJSONObject("properties").get("gxzl"));
            attribute.put("起点标识码", detailJSONObject.getJSONObject("properties").get("qdbsm"));
            attribute.put("止点标识码", detailJSONObject.getJSONObject("properties").get("zdbsm"));
            attribute.put("起点高程", detailJSONObject.getJSONObject("properties").get("qdgc"));
            attribute.put("起高程类型", detailJSONObject.getJSONObject("properties").get("qgclx"));
            attribute.put("起点埋深", detailJSONObject.getJSONObject("properties").get("qdms"));
            attribute.put("止点高程", detailJSONObject.getJSONObject("properties").get("zdgc"));
            attribute.put("止高程类型", detailJSONObject.getJSONObject("properties").get("zgclx"));
            attribute.put("止点埋深", detailJSONObject.getJSONObject("properties").get("zdms"));
            attribute.put("材质", detailJSONObject.getJSONObject("properties").get("cz"));
            attribute.put("埋设方式", detailJSONObject.getJSONObject("properties").get("msfs"));
            attribute.put("管径1", detailJSONObject.getJSONObject("properties").get("gja"));
            attribute.put("管径2", detailJSONObject.getJSONObject("properties").get("gjb"));
            attribute.put("使用状况", detailJSONObject.getJSONObject("properties").get("syzk"));
            attribute.put("管线段长度", detailJSONObject.getJSONObject("properties").get("gxdcd"));
            attribute.put("groupID", detailJSONObject.getJSONObject("properties").get("groupid"));
            attribute.put("Shape_Length", detailJSONObject.getJSONObject("properties").get("shape_length"));
            attribute.put("标识码", detailJSONObject.getJSONObject("properties").get("bsm"));
            JSONArray geometry = new JSONArray();
            JSONObject metry = new JSONObject();
            metry.put("type", "MultiLineString");
            metry.put("lod", 0);
            JSONArray boundarie = new JSONArray();
            JSONArray array = detailJSONObject.getJSONObject("geometry").getJSONArray("coordinates").getJSONArray(0);
            for (int m = 0; m < array.size(); m++) {
                JSONArray object = array.getJSONArray(m);
                jsonObject.getJSONArray("vertices").add(ProjectionToGeographicUtil.getPoint(object.getDouble(0), object.getDouble(1)));
                boundarie.add(jsonObject.getJSONArray("vertices").size() - 1);
            }
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(boundarie);
            metry.put("boundaries", jsonArray);
            JSONArray metryArray = new JSONArray();
            metryArray.add(metry);
            cityObject.put("geometry", metryArray);
            cityObject.put("attributes", attribute);
            cityObject.put("attributes", attribute);
            geometry.add(metry);
            jsonObject.getJSONObject("CityObjects").put("UUID_" + UUID.randomUUID().toString(), cityObject);
        }
        long times = System.currentTimeMillis();
        String pointPath = path + times + "\\管线.json";
        File dirFile = new File(path + times);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        FileWriter fileWriter = new FileWriter(pointPath);
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        SemUtils.cityJsonToSem(pointPath, semUrl + "link.sem");
        return success(semUrl + "link.sem");
    }
    public R<String> lineToCityJson(String shpPath) throws Exception {
        String path = outPath + "\\line\\";
        List<Map<String, Object>> list = ShpReadUtils.readPointShp(shpPath);
        JSONObject jsonObject = getModule("linemodule.json");
        for (Map<String, Object> map : list
        ) {
            //拼装基础信息
            JSONObject cityObject = new JSONObject();
            cityObject.put("type", "+PipeLine");
            JSONObject attribute = new JSONObject();
            attribute.put("name", map.get("msfs"));
            JSONArray geometry = new JSONArray();
            JSONObject metry = new JSONObject();
            metry.put("type", "MultiLineString");
            metry.put("lod", 0);
            JSONArray boundarie = new JSONArray();
            JSONArray array = JSONObject.parseObject(map.get("the_geom").toString()).getJSONArray("coordinates");
            for (int i = 0; i < array.size(); i++) {
                JSONObject object = JSONObject.parseObject(array.get(i).toString());
                jsonObject.getJSONArray("vertices").add(ProjectionToGeographicUtil.getPoint(Double.valueOf(object.get("x").toString()), Double.valueOf(object.get("y").toString())));
                boundarie.add(jsonObject.getJSONArray("vertices").size() - 1);
            }
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(boundarie);
            metry.put("boundaries", jsonArray);
            JSONArray metryArray = new JSONArray();
            metryArray.add(metry);
            cityObject.put("geometry", metryArray);
            cityObject.put("attributes", attribute);
            cityObject.put("attributes", attribute);
            geometry.add(metry);
            jsonObject.getJSONObject("CityObjects").put("UUID_" + UUID.randomUUID().toString(), cityObject);
        }
        long times = System.currentTimeMillis();
        String pointPath = path + times + "\\管线.json";
        File dirFile = new File(path + times);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        FileWriter fileWriter = new FileWriter(pointPath);
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        String filePatn = inPath + "\\tongzhou\\";
        File file = new File(filePatn);
        if (!file.exists()) {
            file.mkdirs();
        }
        SemUtils.cityJsonToSem(pointPath, filePatn + "link.sem");
        return success(filePatn + "link.sem");
    }
    public R<String> terrainToSem(List<GridDto> dtos, String semUrl) throws Exception {
        long times = System.currentTimeMillis();
        String path = outPath + "\\terrain\\" + times + "\\";
        File dirFile = new File(path + "appearance");
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        double minx = 180.0;
        double maxx = 0.0;
        double miny = 180.0;
        double maxy = 0.0;
        for (GridDto dto : dtos
        ) {
            if (dto.getLon() > maxx) {
                maxx = dto.getLon();
            }
            if (dto.getLon() < minx) {
                minx = dto.getLon();
            }
            if (dto.getLat() > maxy) {
                maxy = dto.getLat();
            }
            if (dto.getLat() < miny) {
                miny = dto.getLat();
            }
        }
        JSONArray min = ProjectionToGeographicUtil.get4548Point(minx, miny);
        JSONArray max = ProjectionToGeographicUtil.get4548Point(maxx, maxy);
        String tifPath = path + "terrain.tif";
        TiffClipper.cropTiffByLatLon(config.getTifPath(), tifPath, min.getDouble(0), min.getDouble(1), max.getDouble(0), max.getDouble(1));
        String pngPath = path + "appearance\\terrain.png";
        TiffToRGBUtil.tifToPng(tifPath, pngPath);
        JSONObject jsonObject = getModule("terrainmodule.json");
        jsonObject.put("vertices", TiffCoordinateExtractorUtil.getCoordinate(tifPath));
        FileWriter fileWriter = new FileWriter(path + "terrain.json");
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        SemUtils.cityJsonToSem(path + "terrain.json", semUrl + "terrain.sem");
        return success(semUrl + "terrain.sem");
    }
    public R<String> terrainToCityJson(String tifPath) throws Exception {
        long times = System.currentTimeMillis();
        String path = outPath + "\\terrain\\" + times + "\\";
        File dirFile = new File(path + "appearance");
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String pngPath = path + "appearance\\terrain.png";
        TiffToRGBUtil.tifToPng(tifPath, pngPath);
        JSONObject jsonObject = getModule("terrainmodule.json");
        jsonObject.put("vertices", TiffCoordinateExtractorUtil.getCoordinate(tifPath));
        FileWriter fileWriter = new FileWriter(path + "terrain.json");
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        String filePatn = inPath + "\\tongzhou\\";
        File file = new File(filePatn);
        if (!file.exists()) {
            file.mkdirs();
        }
        SemUtils.cityJsonToSem(path + "terrain.json", filePatn + "terrain.sem");
        return success(filePatn + "terrain.sem");
    }
    public R<String> gridToCityJson(List<GridDto> dtos, String semUrl) throws Exception {
        long times = System.currentTimeMillis();
        String path = outPath + "\\grid\\" + times + "\\";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        JSONObject jsonObject = getModule("grid.json");
        JSONArray array = jsonObject.getJSONArray("vertices");
        for (GridDto dto : dtos
        ) {
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(dto.getLon());
            jsonArray.add(dto.getLat());
            jsonArray.add(0);
            array.add(jsonArray);
        }
        jsonObject.put("vertices", array);
        FileWriter fileWriter = new FileWriter(path + "grid.json");
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        SemUtils.cityJsonToSem(path + "grid.json", semUrl + "grid.sem");
        return success(semUrl + "grid.sem");
    }
    public R<String> riverToSem(String semUrl) throws Exception {
        long times = System.currentTimeMillis();
        String path = outPath + "\\river\\" + times + "\\";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        JSONObject jsonObject = getModule("river.json");
        FileWriter fileWriter = new FileWriter(path + "river.json");
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        SemUtils.cityJsonToSem(path + "river.json", semUrl + "river.sem");
        return success(semUrl + "river.sem");
    }
    public R<String> landuseToSem(String semUrl) throws Exception {
        long times = System.currentTimeMillis();
        String path = outPath + "\\landuse\\" + times + "\\";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        JSONObject jsonObject = getModule("landuse.json");
        FileWriter fileWriter = new FileWriter(path + "landuse.json");
        fileWriter.write(jsonObject.toJSONString());
        fileWriter.close();
        SemUtils.cityJsonToSem(path + "landuse.json", semUrl + "landuse.sem");
        return success(semUrl + "landuse.sem");
    }
    public JSONObject getModule(String moduleName) {
        JSONObject jsonObject = new JSONObject();
        try {
            URL resource = Resources.getResource(moduleName);
            String fileContent = Resources.toString(resource, StandardCharsets.UTF_8);
            jsonObject = JSONObject.parseObject(fileContent);
            System.out.println(fileContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}