13693261870
2025-06-24 8565bd83fcd670ec8379084d600eb97d18037d21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package com.terra.system.service.show;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.terra.system.entity.ctrl.DownloadReqEntity;
import com.terra.system.entity.ctrl.KeyValueEntity;
import com.terra.system.entity.data.DownloadEntity;
import com.terra.system.entity.sys.AttachEntity;
import com.terra.system.entity.sys.UserEntity;
import com.terra.system.helper.*;
import com.terra.system.mapper.all.BasicMapper;
import com.terra.system.mapper.all.GeomBaseMapper;
import com.terra.system.mapper.data.DownloadMapper;
import com.terra.system.service.all.BaseQueryService;
import com.terra.system.service.data.MetaService;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
 
import java.io.File;
import java.util.*;
 
/**
 * 资料馆
 * @author WWW
 */
@Service
@SuppressWarnings("ALL")
public class DataLibService {
    @Resource
    PathHelper pathHelper;
 
    @Resource
    MetaService metaService;
 
    @Resource
    DownloadMapper downloadMapper;
 
    @Resource
    BaseQueryService baseQueryService;
 
    private final static Log log = LogFactory.getLog(DataLibService.class);
 
    /**
     * 查询DB中溢出的单位编码
     */
    public List<String> selectDbOverflowDep(UserEntity ue, DownloadReqEntity dr) {
        if (!StringHelper.isEmpty(dr.getWkt())) {
            return selectDbOverflowDep4Wkt(ue, dr);
        }
 
        return selectDbOverflowDep4Prop(ue, dr);
    }
 
    /**
     * 查询DB中溢出的单位编码-空间查询
     */
    public List<String> selectDbOverflowDep4Wkt(UserEntity ue, DownloadReqEntity dr) {
        List<String> rs = new ArrayList<>();
        for (String entity : dr.getEntities()) {
            GeomBaseMapper<?> baseMapper = ClassHelper.getGeoBaseMapper(entity);
            if (null == baseMapper) {
                continue;
            }
 
            QueryWrapper wrapper = getWrapper4DbOverflow(ue, dr);
            Integer srid = baseQueryService.getSrid(baseMapper);
            wrapper.apply(String.format("ST_Intersects(ST_PolygonFromText('%s', %d), geom)", dr.getWkt(), srid));
 
            List<String> ids = baseMapper.selectObjs(wrapper);
            addDepCodes(rs, ids);
        }
 
        return rs;
    }
 
    /**
     * 查询DB中溢出的单位编码-属性查询
     */
    public List<String> selectDbOverflowDep4Prop(UserEntity ue, DownloadReqEntity dr) {
        List<String> rs = new ArrayList<>();
        BasicMapper<?> baseMapper = ClassHelper.getBasicMapper(dr.getEntities().get(0));
        if (null == baseMapper) {
            return rs;
        }
 
        QueryWrapper wrapper = getWrapper4DbOverflow(ue, dr);
        List<String> ids = baseMapper.selectObjs(wrapper);
        addDepCodes(rs, ids);
 
        return rs;
    }
 
    /**
     * 查询DB中溢出单位编码的查询包装器
     */
    private <T> QueryWrapper<T> getWrapper4DbOverflow(UserEntity ue, DownloadReqEntity dr) {
        QueryWrapper<T> wrapper = new QueryWrapper<T>();
        wrapper.select("depid");
        wrapper.groupBy("depid");
        wrapper.apply("depid is not null and depid not like '" + ue.getDepcode() + "%'");
 
        if (null != dr.getIds() && dr.getIds().size() > 0) {
            wrapper.apply(String.format("gid in (%s)", StringHelper.join(dr.getIds(), ",")));
        } else {
            baseQueryService.addFilterWrapper(wrapper, dr.getFilter());
        }
 
        String dirs = copeCodes(dr.getDirs(), "dirid");
        if (!StringHelper.isEmpty(dirs)) {
            wrapper.apply(dirs);
        }
        if (!StringHelper.isEmpty(dr.getDepcode())) {
            wrapper.likeRight("depid", dr.getDepcode());
        }
 
        return wrapper;
    }
 
    /**
     * 添加单位编码
     */
    private void addDepCodes(List<String> rs, List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            return;
        }
 
        for (String id : ids) {
            if (StringHelper.isEmpty(id)) {
                continue;
            }
            if (!rs.contains(id)) {
                rs.add(id);
            }
        }
    }
 
    /**
     * 请求DB数据下载
     */
    public String downloadDbReq(UserEntity ue, DownloadReqEntity dr) throws Exception {
        Map<String, List<?>> dataMap = new HashMap<>(2);
        Map<String, List<AttachEntity>> annexMap = new HashMap<>(2);
        queryData(dr, dataMap, annexMap);
        if (dataMap.size() == 0) {
            return null;
        }
 
        String tempName = StringHelper.YMDHMS2_FORMAT.format(new Date());
        String tempPath = pathHelper.getTempPath(tempName);
        String gdbPath = tempPath + File.separator + "tabs.gdb";
 
        File gdbFile = new File(gdbPath);
        if (gdbFile.exists() && gdbFile.isDirectory()) {
            FileHelper.deleteDir(gdbPath);
        }
        GdbHelper.createGdb(gdbPath, dataMap);
 
        String zipFile = pathHelper.getDownloadFullPath() + File.separator + tempName + ".gdb.zip";
        ZipFile zip = Zip4jHelper.createZipFile(zipFile, dr.getPwd());
        ZipParameters params = Zip4jHelper.getZipParams(true);
        zip.addFolder(new File(gdbPath), params);
        // zip.addFolder(new File(annexPath), params)
        metaService.addAnnex(zip, params, annexMap);
 
        String dbPwd = Md5Helper.reverse(Md5Helper.generate(dr.getPwd()));
        DownloadEntity de = getDownloadEntity(ue, zipFile, dbPwd);
        int rows = downloadMapper.insert(de);
 
        return rows > 0 ? de.getGuid() : null;
    }
 
    /**
     * 查询数据+附件
     */
    private void queryData(DownloadReqEntity dr, Map<String, List<?>> dataMap, Map<String, List<AttachEntity>> annexMap) {
        for (String entity : dr.getEntities()) {
            try {
                BasicMapper baseMapper = ClassHelper.getBasicMapper(entity);
                if (null == baseMapper) {
                    continue;
                }
 
                QueryWrapper wrapper = createQueryWrapper(baseMapper, dr);
                metaService.addData(entity, baseMapper, wrapper, dataMap, annexMap);
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
    }
 
    /**
     * 创建查询包装器
     */
    private <T> QueryWrapper<T> createQueryWrapper(BasicMapper baseMapper, DownloadReqEntity dr) {
        QueryWrapper<T> wrapper = new QueryWrapper<T>();
 
        String dirs = copeCodes(dr.getDirs(), "dirid");
        if (!StringHelper.isEmpty(dirs)) {
            wrapper.apply(dirs);
        }
        if (!StringHelper.isEmpty(dr.getDepcode())) {
            // wrapper.apply(String.format("depid like '%s'", StringHelper.getRightLike(dr.getDepcode())))
            wrapper.likeRight("depid", dr.getDepcode());
        }
        if (baseMapper instanceof GeomBaseMapper) {
            wrapper.select("ST_AsText(geom) as geom, *");
            if (!StringHelper.isEmpty(dr.getWkt())) {
                Integer srid = baseQueryService.getSrid((GeomBaseMapper) baseMapper);
                wrapper.apply(String.format("ST_Intersects(ST_PolygonFromText('%s', %d), geom)", dr.getWkt(), srid));
            }
        }
        if (null != dr.getIds() && dr.getIds().size() > 0) {
            wrapper.apply(String.format("gid in (%s)", StringHelper.join(dr.getIds(), ",")));
        } else {
            baseQueryService.addFilterWrapper(wrapper, dr.getFilter());
        }
 
        return wrapper;
    }
 
    /**
     * 创建附件 *
     */
    private void createAnnex(String annexPath, Map<String, List<AttachEntity>> annexMap) {
        if (annexMap.size() == 0) {
            return;
        }
 
        String uploadPath = pathHelper.getConfig().getUploadPath();
        for (String key : annexMap.keySet()) {
            String targetPath = annexPath + File.separator + key;
            File targetFile = new File(targetPath);
            if (!targetFile.exists() || !targetFile.isDirectory()) {
                targetFile.mkdirs();
            }
 
            for (AttachEntity ae : annexMap.get(key)) {
                try {
                    File srcFile = new File(uploadPath + File.separator + ae.getPath());
                    if (!srcFile.exists() || srcFile.isDirectory()) {
                        continue;
                    }
 
                    File destFile = new File(targetPath + File.separator + ae.getName());
                    if (destFile.exists() && !destFile.isDirectory()) {
                        continue;
                    }
 
                    FileHelper.copyFile(srcFile, destFile);
                } catch (Exception ex) {
                    log.error(ex.getMessage(), ex);
                }
            }
        }
    }
 
    /**
     * 获取下载实体类
     */
    private DownloadEntity getDownloadEntity(UserEntity ue, String file, String pwd) {
        DownloadEntity de = new DownloadEntity();
        de.setName(FileHelper.getFileName(file));
        // 1-Shp文件,2-专题图,3-元数据,4-业务数据,5-管道分析,6-统计报告,7-附件文件,8-瓦片文件
        de.setType(4);
        de.setSizes(FileHelper.sizeToMb(new File(file).length()));
        de.setDepid(ue.getDepid());
        de.setDcount(0);
        de.setPwd(pwd);
        de.setUrl(FileHelper.getRelativePath(file));
        de.setDescr("业务数据文件");
        de.setGuid(FileHelper.getFileMd5(file));
        de.setCreateUser(ue.getId());
        // de.setGeom(null)
 
        return de;
    }
 
    /**
     * 处理编码
     */
    public static String copeCodes(String codes, String field) {
        if (StringHelper.isEmpty(codes) || StringHelper.isSqlInjection(codes)) {
            return null;
        }
 
        //List<String> list = Arrays.asList(codes.split(","));
        //List<String> list = codesAsList(codes);
        //list = copeDirCodes(list);
        //setRightLike(list, field);
 
        //return "(" + StringHelper.join(list, " or ") + ")";
 
        List<String> list = new ArrayList<>();
        for (String dir : codes.split(",")) {
            list.add("^" + dir);
        }
 
        return field + " ~ '" + StringHelper.join(list, "|") + "'";
    }
 
    /**
     * 单位编码转集合 *
     */
    private static List<String> codesAsList(String codes) {
        List<String> list = Arrays.asList(codes.split(","));
        Set set = new HashSet(list);
 
        List<String> newList = new ArrayList<>(set);
        Collections.sort(newList);
 
        return newList;
    }
 
    /**
     * 处理目录编码 *
     */
    private static List<String> copeDirCodes(List<String> list) {
        List<String> prjList = getDirCodesByLen(list, 0, 2);
        List<String> appList = getDirCodesByLen(list, 3, 30);
        if (prjList.isEmpty() && appList.isEmpty()) {
            return list;
        }
        if (prjList.isEmpty()) {
            return appList;
        }
        if (appList.isEmpty()) {
            return prjList;
        }
 
        return filterCodes(prjList, appList);
    }
 
    /**
     * 根据长度获取单位编码 *
     */
    private static List<String> getDirCodesByLen(List<String> list, int start, int end) {
        List<String> rs = new ArrayList<>();
        for (String code : list) {
            if (StringHelper.isEmpty(code)) {
                continue;
            }
 
            if (code.length() >= start && code.length() <= end) {
                rs.add(code);
            }
        }
 
        return rs;
    }
 
    /**
     * 过滤项目编码 *
     */
    private static List<String> filterCodes(List<String> prjList, List<String> appList) {
        int i = 0;
        while (i < appList.size()) {
            boolean flag = false;
            for (String prj : prjList) {
                if (appList.get(i).startsWith(prj)) {
                    flag = true;
                    break;
                }
            }
 
            if (!flag) {
                appList.remove(i);
                continue;
            }
            i++;
        }
 
        return appList;
    }
 
    /**
     * 设置 右like *
     */
    private static void setRightLike(List<String> list, String field) {
        if (list.isEmpty()) {
            list.add("1 = 2");
            return;
        }
 
        for (int i = 0, c = list.size(); i < c; i++) {
            String str = String.format("%s like '%s%%'", field, list.get(i));
            list.set(i, str);
        }
    }
 
    /**
     * 根据资料类别获取目录编码
     */
    public String getDirsByTypes(String types, String dirs, String field) {
        if (StringUtils.isEmpty(types) && StringUtils.isEmpty(dirs)) {
            return null;
        }
 
        if (!StringUtils.isEmpty(types)) {
            List<KeyValueEntity> list = baseQueryService.selectDirsByTypes(types.split(","), copeCodes(dirs, "code"));
            if (null == list || list.isEmpty()) {
                return "1 = 2";
            }
 
            return copeDirs(list, field);
        }
 
        return copeCodes(dirs, field);
    }
 
    /**
     * 处理目录编码:dircode ~ '^0A|^0E'
     */
    public static String copeDirs(List<KeyValueEntity> kvs, String field) {
        List<String> list = new ArrayList<>();
        for (KeyValueEntity kv : kvs) {
            String[] dirs = kv.getValue().split(",");
            for (String dir : dirs) {
                list.add("^" + dir);
            }
        }
 
        return field + " ~ '" + StringHelper.join(list, "|") + "'";
    }
}