6c
2025-12-12 16ddfc8e22559480a2b039b896f1e882f286c9c9
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
package com.product.integration.service;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.product.admin.service.PublicService;
import com.product.common.lang.ExceptionUtils;
import com.product.common.lang.StringUtils;
import com.product.core.cache.DataPoolCacheImpl;
import com.product.core.config.Global;
import com.product.core.dao.BaseDao;
import com.product.core.entity.DataTableEntity;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.RequestParameterEntity;
import com.product.core.exception.BaseException;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.core.util.ReflectUtil;
import com.product.file.service.FileManagerService;
import com.product.integration.config.CmnConst;
import com.product.integration.config.IntegrationCode;
import com.product.integration.service.idel.IInterfaceIntegrationService;
import com.product.util.BaseUtil;
import com.product.util.SystemParamReplace;
import com.product.util.http.HttpRequestUtil;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.io.File;
import java.io.IOException;
import java.util.*;
 
/**
 * 实现功能:
 *
 * @author 作者[夜丶光]
 * @version 1.0.00  2025-12-01 11:15
 */
@Service
public class InterfaceIntegrationService implements IInterfaceIntegrationService {
    @Autowired
    private BaseDao baseDao;
    @Autowired
    private PublicService publicService;
    @Autowired
    private FileManagerService fileManagerService;
 
    /**
     * 查询数据
     * @param fse
     * @return
     */
    public FieldSetEntity find(FieldSetEntity fse) {
        FieldSetEntity integrationFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION, fse.getUUID(), true);
        DataTableEntity responseInfoDte = integrationFse.getSubDataTable(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION_RESPONSE_INFO);
        Map<String, String> acceptKayMap = Maps.newHashMap();
        acceptKayMap.put("uuid", "front_uuid");
        JSONArray arr = BaseUtil.dataTableToTreeData(responseInfoDte, CmnConst.TRICODE, 3, acceptKayMap, null, null);
        integrationFse.removeSubData(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION_RESPONSE_INFO);
        integrationFse.setValue(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION_RESPONSE_INFO, arr.toString());
        return integrationFse;
    }
 
    /**
     * 保存
     * @param fse
     * @return
     */
    @Override
    public String save(FieldSetEntity fse) {
        String responseInfo = fse.getString(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION_RESPONSE_INFO);
 
        // 清理响应结构子表
        String uuid = fse.getUUID();
        if (!StringUtils.isEmpty(uuid)) {
            baseDao.delete(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION_RESPONSE_INFO, String.format("%s=?", CmnConst.PARENT_UUID), new Object[]{uuid});
        }
 
        DataTableEntity responseInfoDte = dealResponseInfo(responseInfo);
        fse.addSubDataTable(responseInfoDte);
        uuid = publicService.saveFieldSetEntity(fse);
 
        // 验证定时任务是否创建,若是未创建,那么创建定时任务
        generateTimedTask(fse);
 
        return uuid;
    }
    /**
     * 处理响应数据结构
     * @param responseInfo  响应树结构子表信息
     * @return
     */
    private DataTableEntity dealResponseInfo(String responseInfo) {
        DataTableEntity responseInfoDte = new DataTableEntity();
        try {
            if (!StringUtils.isEmpty(responseInfo)) {
                saveDealResponseInfoPart(responseInfoDte, JSONArray.parseArray(responseInfo), "");
            }
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(IntegrationCode.INTERFACE_INTEGRATION_SAVE_DEAL_RESPONSE_INFO_FAIL);
        }
        return responseInfoDte;
    }
    /**
     * 保存-处理响应数据结构-循环方法
     * @param responseInfoDte   存储容器,响应子表数据dte
     * @param responseInfoArr   响应子表数据待处理数组
     * @param parentCode        父编码
     */
    private void saveDealResponseInfoPart(DataTableEntity responseInfoDte, JSONArray responseInfoArr, String parentCode) {
        for (int i = 0; i < responseInfoArr.size(); i++) {
            JSONObject responseInfoObj = responseInfoArr.getJSONObject(i);
            FieldSetEntity fse = new FieldSetEntity(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION_RESPONSE_INFO);
            List<String> passList = Arrays.asList("promptName", "children", "front_uuid");
            List<String> fieldList = Arrays.asList("name", "type", "db_info", "unique_sign");
            String code = String.format("%s%0" + 3 + "d", parentCode, i + 1);
            responseInfoObj.forEach((key, value) -> {
                if (!passList.contains(key)) {
                    fse.setValue(key, value);
                }
            });
            fieldList.forEach(fieldName -> {
                if (StringUtils.isEmpty(fse.getString(fieldName))) {
                    fse.setValue(fieldName, "");
                }
            });
            fse.setValue(CmnConst.TRICODE, code);
            responseInfoDte.addFieldSetEntity(fse);
            saveDealResponseInfoPart(responseInfoDte, responseInfoObj.getJSONArray(CmnConst.CHILDREN), code);
        }
    }
 
    /**
     * 验证定时任务是否创建,若是未创建,那么创建定时任务
     * @param fse
     */
    public void generateTimedTask(FieldSetEntity fse) {
        String invokeTarget = String.format("interfaceIntegrationService.timedTaskTrigger('%s')", fse.getUUID());
        FieldSetEntity timedTaskFse = baseDao.getFieldSetEntityByFilter(CmnConst.PRODUCT_SYS_TIMED_TASK, String.format("%s=?", CmnConst.INVOKE_TARGET), new Object[]{invokeTarget}, false);
        if (FieldSetEntity.isEmpty(timedTaskFse)) {
            timedTaskFse = new FieldSetEntity(CmnConst.PRODUCT_SYS_TIMED_TASK);
            timedTaskFse.setValue(CmnConst.JOB_GROUP, "system");
            timedTaskFse.setValue(CmnConst.MISFIRE_POLICY, "3");
            timedTaskFse.setValue(CmnConst.CONCURRENT, 0);
            timedTaskFse.setValue(CmnConst.INVOKE_TARGET, invokeTarget);
            BaseUtil.createCreatorAndCreationTime(timedTaskFse);
        } else {
            BaseUtil.updatedRegeneratorAndUpdateTime(SpringMVCContextHolder.getCurrentUser(), timedTaskFse);
        }
        timedTaskFse.setValue(CmnConst.JOB_NAME, String.format("接口集成-%s", fse.getString(CmnConst.NAME)));
        timedTaskFse.setValue(CmnConst.CRON_EXPRESSION, fse.getString(CmnConst.FREQUENCY));
        timedTaskFse.setValue(CmnConst.IS_CONCEAL, 0);
        timedTaskFse.setValue(CmnConst.STATUS, 1);
        baseDao.saveFieldSetEntity(timedTaskFse);
 
    }
 
    /**
     * 定时任务触发方法
     * @param uuid  接口集成uuid
     */
    public void timedTaskTrigger(String uuid) {
        String code = "";
        String message = "";
        StringBuilder content = new StringBuilder(128);
        String errorInfo = null;
        try {
            // 数据准备
            FieldSetEntity paramFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION, uuid, true);
            DataTableEntity requestParamDte = paramFse.getSubDataTable(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION_REQUEST_PARAM);
            DataTableEntity requestHederDte = paramFse.getSubDataTable(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION_REQUEST_HEADER);
            String requestType = paramFse.getString(CmnConst.REQUEST_TYPE);
            String url = paramFse.getString(CmnConst.ADDRESS);
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(okhttp3.MultipartBody.FORM);
            // 请求头信息
            Map<String, String> headerMap = Maps.newHashMap();
            if (!DataTableEntity.isEmpty(requestHederDte)) {
                for (int i = 0; i < requestHederDte.getRows(); i++) {
                    FieldSetEntity fse = requestHederDte.getFieldSetEntity(i);
                    headerMap.put(fse.getString(CmnConst.NAME), dealValue(fse.getString(CmnConst.VALUE)));
                }
            }
            // 添加请求参数信息
            Map<String, String> paramMap = Maps.newHashMap();
            if (!DataTableEntity.isEmpty(requestParamDte)) {
                for (int i = 0; i < requestParamDte.getRows(); i++) {
                    FieldSetEntity fse = requestParamDte.getFieldSetEntity(i);
                    paramMap.put(fse.getString(CmnConst.NAME), dealValue(fse.getString(CmnConst.VALUE)));
                }
            }
 
            // 请求参数方法自定义处理
            String customRequestParamInfo = paramFse.getString(CmnConst.REQUEST_PARAM_CUSTOM_METHOD);
            if (!StringUtils.isEmpty(customRequestParamInfo)) {
                String[] customMethodInfoArr = customRequestParamInfo.split("\\.");
                String beanName = customMethodInfoArr[0];
                String methodName = customMethodInfoArr[1];
                ReflectUtil.invoke(beanName, methodName, new Object[]{headerMap, paramMap});
                content.append(String.format("%s 执行自定义方法[%s]补充处理请求参数\n", BaseUtil.getCurTimeWithMill(), customRequestParamInfo));
            }
 
            // 发起请求
            Object requestResult;
            try {
                if ("post".equals(requestType)) {
                    paramMap.forEach(builder::addFormDataPart);
                    RequestBody requestBody = builder.build();
                    requestResult = HttpRequestUtil.request(url, "POST", "multipart/form-data", requestBody, JSONObject.class, headerMap);
                } else {
                    StringBuilder urlParamPart = new StringBuilder(128);
                    paramMap.forEach((name, value) -> {
                        if (urlParamPart.length() > 0) {
                            urlParamPart.append("&");
                        } else {
                            urlParamPart.append("?");
                        }
                        urlParamPart.append(name).append("=").append(value);
                    });
                    requestResult = HttpRequestUtil.request(url + urlParamPart, "GET", "application/json", null, JSONObject.class, headerMap);
                }
                System.out.println(requestResult);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(IntegrationCode.INTERFACE_INTEGRATION_REQUEST_DATA_FAIL);
            }
 
            // 数据处理
            String customResponseInfo = paramFse.getString(CmnConst.RESPONSE_CUSTOM_METHOD);
            if (!StringUtils.isEmpty(customResponseInfo)) {
                // 自定义方法处理
                String[] customMethodInfoArr = customResponseInfo.split("\\.");
                String beanName = customMethodInfoArr[0];
                String methodName = customMethodInfoArr[1];
                ReflectUtil.invoke(beanName, methodName, new Object[]{paramFse, requestResult});
                content.append(String.format("%s 执行自定义数据处理方法[%s]\n", BaseUtil.getCurTimeWithMill(), customResponseInfo));
            } else {
                // 默认方法处理
                FieldSetEntity clientFse = baseDao.getFieldSetEntityByFilter("product_sys_clients", "1=1", new Object[]{}, false);
                String clientUUID = clientFse.getUUID();
 
                String coverSign = paramFse.getString(CmnConst.IS_COVER);
                DataTableEntity responseInfoDte = paramFse.getSubDataTable(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION_RESPONSE_INFO);
                if (DataTableEntity.isEmpty(responseInfoDte)) {
                    content.append(String.format("%s 响应结构配置信息为空\n", BaseUtil.getCurTimeWithMill()));
                    return;
                }
                Map<String, String> keyMap = Maps.newHashMap();
                for (Object key : responseInfoDte.getFieldSetEntity(0).getFields()) {
                    keyMap.put(key.toString(), String.format("[%s]", key));
                }
                JSONObject structureObj = BaseUtil.dataTableToTreeDataObj(responseInfoDte, CmnConst.NAME, CmnConst.TRICODE, 3, keyMap, null, null);
                if (structureObj.isEmpty()) {
                    return;
                }
                JSONObject resultObj = (JSONObject) requestResult;
                JSONObject dealtDataObj = dealResult(resultObj, structureObj);
                for (Map.Entry<String, Object> entry : dealtDataObj.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    if (CmnConst.CODE.equals(key)) {
                        code = value != null ? value.toString() : null;
                    } else if (CmnConst.MESSAGE.equals(key)) {
                        message = value != null ? value.toString() : null;
                    } else {
                        // 表处理
                        JSONObject tableObj = (JSONObject) value;
                        Set<String> uniqueFieldSet = (Set<String>) tableObj.get(CmnConst.UNIQUE_SIGN);
                        DataTableEntity waitDealDte = (DataTableEntity) tableObj.get(CmnConst.TABLE);
                        // 优先处理文件内容,需要根据表结构信息进行处理
                        dealFile(waitDealDte, clientUUID);
                        String tableName = waitDealDte.getTableName().toString();
                        if (uniqueFieldSet == null || uniqueFieldSet.isEmpty()) {
                            if ("1".equals(coverSign)) {
                                // 覆盖
                                baseDao.executeUpdate(String.format("TRUNCATE TABLE %s", tableName));
                                content.append(String.format("%s 开始-处理[%s]表-无标识且覆盖\n", BaseUtil.getCurTimeWithMill(), tableName));
                                content.append(String.format("%s 清理[%s]表\n", BaseUtil.getCurTimeWithMill(), tableName));
                            } else {
                                content.append(String.format("%s 开始-处理[%s]表-无标识不覆盖\n", BaseUtil.getCurTimeWithMill(), tableName));
                            }
                            BaseUtil.generateTime(waitDealDte);
                            baseDao.add(waitDealDte);
                        } else {
                            StringBuilder filter = new StringBuilder(128);
                            List<String> paramList = Lists.newArrayList();
                            for (int i = 0; i < waitDealDte.getRows(); i++) {
                                FieldSetEntity waitDealFse = waitDealDte.getFieldSetEntity(i);
                                if (filter.length() > 0) {
                                    filter.append("\nOR ");
                                }
                                StringBuilder singleFilter = new StringBuilder(128);
                                for (String uniqueField : uniqueFieldSet) {
                                    if (singleFilter.length() > 0) {
                                        singleFilter.append(" AND ");
                                    }
                                    singleFilter.append(uniqueField).append("=?");
                                    paramList.add(waitDealFse.getString(uniqueField));
                                }
                                filter.append("(").append(singleFilter).append(")");
                            }
                            if ("1".equals(coverSign)) {
                                // 覆盖
                                content.append(String.format("%s 开始-处理[%s]表-无标识且覆盖\n", BaseUtil.getCurTimeWithMill(), tableName));
                                baseDao.executeUpdate(String.format("DELETE FROM %s WHERE %s", tableName, filter), paramList.toArray());
                                content.append(String.format("%s 根据唯一标识字段[%s]进行清理\n", BaseUtil.getCurTimeWithMill(), BaseUtil.collection2String(uniqueFieldSet)));
                                baseDao.add(waitDealDte);
                            } else {
                                // 不覆盖
                                content.append(String.format("%s 开始-处理[%s]表-无标识不覆盖\n", BaseUtil.getCurTimeWithMill(), tableName));
                                DataTableEntity waitUpdateDte = baseDao.listTable(tableName, filter.toString(), paramList.toArray());
                                int waitAddCount = 0;
                                Map<JSONObject, FieldSetEntity> waitUpdateMap = Maps.newHashMap();
                                for (int i = 0; i < waitUpdateDte.getRows(); i++) {
                                    FieldSetEntity waitUpdateFse = waitUpdateDte.getFieldSetEntity(i);
                                    JSONObject keyObj = extractFseAimField2Obj(waitUpdateFse, uniqueFieldSet);
                                    waitUpdateMap.put(keyObj, waitUpdateFse);
                                }
                                for (int i = 0; i < waitDealDte.getRows(); i++) {
                                    FieldSetEntity waitDealFse = waitDealDte.getFieldSetEntity(i);
                                    JSONObject keyObj = extractFseAimField2Obj(waitDealFse, uniqueFieldSet);
                                    FieldSetEntity waitUpdateFse = waitUpdateMap.get(keyObj);
                                    if (waitUpdateFse != null) {
                                        waitUpdateFse.getValues().forEach((fieldNameObj, fieldValue) -> {
                                            String fieldName = fieldNameObj.toString();
                                            if (StringUtils.isEmpty(waitDealFse.getString(fieldName))) {
                                                waitDealFse.setValue(fieldName, fieldValue);
                                            }
                                        });
                                        waitDealFse.setValue(CmnConst.UPDATED_UTC_DATETIME, new Date());
                                    } else {
                                        waitAddCount++;
                                    }
                                }
                                baseDao.update(waitDealDte);
                                content.append(String.format("%s 根据[%s]表唯一标识字段[%s]进行更新\n", BaseUtil.getCurTimeWithMill(), tableName, BaseUtil.collection2String(uniqueFieldSet)));
                                content.append(String.format("%s 更新[%s]条数据\n", BaseUtil.getCurTimeWithMill(), waitUpdateDte.getRows()));
                                content.append(String.format("%s 新增[%s]条数据\n", BaseUtil.getCurTimeWithMill(), waitAddCount));
                            }
                        }
                        content.append(String.format("%s 完成-执行默认方法处理数据-操作[%s]数据,共[%s]条\n", BaseUtil.getCurTimeWithMill(), tableName, waitDealDte.getRows()));
                    }
                }
                code = dealtDataObj.getString(CmnConst.CODE);
                message = dealtDataObj.getString(CmnConst.MESSAGE);
            }
 
            // 完成后方法调用
            String customAfterSaveInfo = paramFse.getString(CmnConst.AFTER_SAVE_CUSTOM_METHOD);
            if (!StringUtils.isEmpty(customAfterSaveInfo)) {
                String[] customMethodInfoArr = customAfterSaveInfo.split("\\.");
                String beanName = customMethodInfoArr[0];
                String methodName = customMethodInfoArr[1];
                ReflectUtil.invoke(beanName, methodName, new Object[]{requestResult});
                content.append(String.format("%s 执行自定义保存后方法[%s]\n", BaseUtil.getCurTimeWithMill(), customAfterSaveInfo));
            }
        } catch (BaseException e) {
            errorInfo = ExceptionUtils.getStackTraceAsString(e);
 
            e.printStackTrace();
            throw new BaseException(e);
        } catch (Exception e) {
            errorInfo = ExceptionUtils.getStackTraceAsString(e);
 
            e.printStackTrace();
            throw new BaseException(IntegrationCode.INTERFACE_INTEGRATION_REQUEST_DEAL_DATA_FAIL);
        } finally {
            // 日志记录
            recordLog(uuid, code, message, content.toString(), errorInfo);
        }
    }
 
    /**
     * 优先处理文件内容,需要根据表结构信息进行处理
     * @param waitDealDte
     * @param clientUUID
     * @throws IOException
     */
    private void dealFile(DataTableEntity waitDealDte, String clientUUID) throws IOException {
        String tableName = waitDealDte.getTableName().toString();
        DataTableEntity tableDte = DataPoolCacheImpl.getInstance().getCacheData("所有表信息", new String[]{tableName});
        if (DataTableEntity.isEmpty(tableDte)) {
            throw new BaseException(IntegrationCode.GET_SYSTEM_CACHE_TABLE_STRUCTURE_FAIL.getValue(), IntegrationCode.GET_SYSTEM_CACHE_TABLE_STRUCTURE_FAIL.getText() + ":" + tableName);
        }
        FieldSetEntity tableFse = tableDte.getFieldSetEntity(0);
        DataTableEntity fieldDte = DataPoolCacheImpl.getInstance().getCacheData("所有字段信息并按表分组", new String[]{tableFse.getUUID()});
        if (DataTableEntity.isEmpty(fieldDte)) {
            throw new BaseException(IntegrationCode.GET_SYSTEM_CACHE_FIELD_INFO_FAIL.getValue(), IntegrationCode.GET_SYSTEM_CACHE_FIELD_INFO_FAIL.getText() + ":" + tableName);
        }
        Map<String, FieldSetEntity> fieldMap = BaseUtil.dte2Map(fieldDte, CmnConst.FIELD_NAME);
        List<String> fileTypeList = Arrays.asList("file", "file-image", "blob-attachment");
        for (int i = 0; i < waitDealDte.getRows(); i++) {
            FieldSetEntity waitDealFse = waitDealDte.getFieldSetEntity(i);
            for (Map.Entry<Object, Object> entry : waitDealFse.getValues().entrySet()) {
                String fieldName = entry.getKey().toString();
                String value = entry.getValue().toString();
                FieldSetEntity fieldFse = fieldMap.get(fieldName);
                if (fieldFse != null && fileTypeList.contains(fieldFse.getString(CmnConst.FIELD_TYPE))) {
                    // 文件处理
                    String fileName = waitDealFse.getString(String.format("~%s~", fieldName));
                    String attachmentUUID = saveFile(tableName, fieldName, fileName, value, clientUUID);
                    waitDealFse.setValue(fieldName, attachmentUUID);
                }
            }
        }
    }
 
    /**
     * 保存文件返回uuid
     * @param tableName         表名
     * @param fieldName         字段名
     * @param fileName          文件名
     * @param base64Content     文件流字符串
     * @param clientUUID        客户uuid,通常是默认顶级
     * @return
     * @throws IOException
     */
    private String saveFile(String tableName, String fieldName, String fileName, String base64Content, String clientUUID) throws IOException {
        String outPath = Global.getSystemConfig("upload.file.path", "") + File.separator + BaseUtil.getCurDateTime("yyyy/MM/dd") + File.separator + UUID.randomUUID() + "_" + fileName;
        byte[] fileBytes = Base64.getDecoder().decode(base64Content);
        FileUtils.writeByteArrayToFile(new File(outPath), fileBytes);
 
        RequestParameterEntity requestParameterEntity = new RequestParameterEntity();
        Map<String, File> fileMap = new HashMap<>();
        fileMap.put(fileName, new File(outPath));
        requestParameterEntity.setFiles(fileMap);
        FieldSetEntity fseAttachment = new FieldSetEntity();
        fseAttachment.setTableName(tableName);
        fseAttachment.setValue("~field_name~", fieldName);
        fseAttachment.setValue(UUID.randomUUID().toString(), fileName);
        fseAttachment.setValue("client_uuid", clientUUID);
        requestParameterEntity.setFormData(fseAttachment);
        FieldSetEntity resultFse = fileManagerService.uploadFile(requestParameterEntity);
 
        return resultFse.getString(fieldName);
    }
 
    /**
     * 提取fse中指定字段信息转化为JSONObject
     * @param fse                   待处理数据
     * @param acceptCollection      接收字段的集合
     * @return
     */
    private JSONObject extractFseAimField2Obj(FieldSetEntity fse, Collection<String> acceptCollection) {
        JSONObject resultObj = new JSONObject();
        acceptCollection.forEach(fieldName -> resultObj.put(fieldName, fse.getString(fieldName)));
        return resultObj;
    }
 
    /**
     * 处理值,若是含有系统参数,那么替换,若是不含,则直接返回
     * @param value
     * @return
     */
    private String dealValue(String value) {
        if (value.contains("{")) {
            return SystemParamReplace.systemParamsReplace(value);
        } else {
            return value;
        }
    }
 
    /**
     * 处理结果信息-默认方法
     * @param resultObj     结果内容obj
     * @param structureObj  结构信息arr
     * @return
     */
    private JSONObject dealResult(JSONObject resultObj, JSONObject structureObj) {
        JSONObject infoObj = new JSONObject();
        dealResultPart(infoObj, resultObj, structureObj, "");
        return infoObj;
    }
    private void dealResultPart(JSONObject infoObj, JSONObject resultObj, JSONObject structureObj, String curTableName) {
        if (structureObj == null || resultObj.isEmpty()) {
            return;
        }
        FieldSetEntity fse = null;
        if (!StringUtils.isEmpty(curTableName)) {
            fse = new FieldSetEntity(curTableName);
            DataTableEntity dte = (DataTableEntity) infoObj.getJSONObject(curTableName).get(CmnConst.TABLE);
            dte.addFieldSetEntity(fse);
        }
        for (Map.Entry<String, Object> entry : resultObj.entrySet()) {
            String resultKey = entry.getKey();
            Object resultValue = entry.getValue();
            JSONObject singleStructureObj = structureObj.getJSONObject(resultKey);
            if (singleStructureObj == null || singleStructureObj.isEmpty()) {
                if (fse != null) {
                    fse.setValue(resultKey, resultValue);
                }
            } else {
                String dealtCodeField = String.format("[%s]", CmnConst.CODE);
                String dealtMessageField = String.format("[%s]", CmnConst.MESSAGE);
                String dealtTypeField = String.format("[%s]", CmnConst.TYPE);
                String dealtDBInfoField = String.format("[%s]", CmnConst.DB_INFO);
                if ("1".equals(singleStructureObj.getString(dealtTypeField)) && StringUtils.isEmpty(infoObj.getString(dealtCodeField))) {
                    // 状态码
                    infoObj.put(CmnConst.CODE, resultValue);
                } else if ("2".equals(singleStructureObj.getString(dealtTypeField)) && StringUtils.isEmpty(infoObj.getString(dealtMessageField))) {
                    // 消息内容
                    infoObj.put(CmnConst.MESSAGE, resultValue);
                } else if ("3".equals(singleStructureObj.getString(dealtTypeField))) {
                    // 表
                    JSONObject tableInfoObj = new JSONObject();
                    curTableName = singleStructureObj.getString(dealtDBInfoField);
                    infoObj.put(curTableName, tableInfoObj);
                    DataTableEntity dte = new DataTableEntity();
                    tableInfoObj.put(CmnConst.TABLE, dte);
                    Set<String> uniqueSignSet = Sets.newHashSet();
                    tableInfoObj.put(CmnConst.UNIQUE_SIGN, uniqueSignSet);
                } else if ("4".equals(singleStructureObj.getString(dealtTypeField))) {
                    // 字段
                    if (fse != null) {
                        fse.setValue(singleStructureObj.getString(dealtDBInfoField), resultValue);
                    }
                    String dealtUniqueSignField = String.format("[%s]", CmnConst.UNIQUE_SIGN);
                    if ("1".equals(singleStructureObj.getString(dealtUniqueSignField))) {
                        Set<String> uniqueSignSet = (Set<String>) infoObj.getJSONObject(curTableName).get(CmnConst.UNIQUE_SIGN);
                        uniqueSignSet.add(singleStructureObj.getString(dealtDBInfoField));
                    }
                }
            }
            if (resultValue instanceof JSONArray) {
                JSONArray arr = (JSONArray) resultValue;
                for (int i = 0; i < arr.size(); i++) {
                    dealResultPart(infoObj, arr.getJSONObject(i), singleStructureObj, curTableName);
                }
            } else if (resultValue instanceof JSONObject) {
                if (singleStructureObj != null) {
                    dealResultPart(infoObj, (JSONObject) resultValue, singleStructureObj, curTableName);
                }
            }
        }
        JSONObject tableInfoObj = resultObj.getJSONObject(curTableName);
        if (tableInfoObj != null) {
            ((DataTableEntity) tableInfoObj.get(curTableName)).addFieldSetEntity(fse);
        }
    }
 
    /**
     * 日志记录
     * @param configUUID    配置uuid
     * @param code          状态码
     * @param message       返回消息内容
     * @param content       执行明细内容
     */
    private void recordLog(String configUUID, String code, String message, String content) {
        recordLog(configUUID, code, message, content, null);
    }
 
    /**
     * 日志记录
     * @param configUUID    配置uuid
     * @param code          状态码
     * @param message       返回消息内容
     * @param content       执行明细内容
     * @param errorInfo     错误信息
     */
    private void recordLog(String configUUID, String code, String message, String content, String errorInfo) {
        FieldSetEntity logFse = new FieldSetEntity(CmnConst.PRODUCT_SYS_INTERFACE_INTEGRATION_LOG);
        logFse.setValue(CmnConst.CREATED_UTC_DATETIME, new Date());
        logFse.setValue(CmnConst.CONFIG_UUID, configUUID);
        logFse.setValue(CmnConst.CODE, code);
        logFse.setValue(CmnConst.MESSAGE, message);
        if (!StringUtils.isEmpty(errorInfo)) {
            content = BaseUtil.getCurTimeWithMill() + " 执行失败\n" + content;
        } else {
            content = BaseUtil.getCurTimeWithMill() + " 执行成功\n" + content;
        }
        logFse.setValue(CmnConst.CONTENT, content);
        logFse.setValue(CmnConst.ERROR_INFO, errorInfo);
        baseDao.saveFieldSetEntity(logFse);
    }
}