# Conflicts:
#	web-domain/src/main/java/com/zcloud/primeport/domain/gateway/DaHuaGateway.java
#	web-infrastructure/src/main/java/com/zcloud/primeport/dahua/api/DaHuaPersonApi.java
#	web-infrastructure/src/main/java/com/zcloud/primeport/gatewayimpl/DaHuaGatewayImpl.java
koumen
shenzhidan 2026-07-28 17:09:54 +08:00
commit 3277481dc1
7 changed files with 395 additions and 12 deletions

View File

@ -1,8 +1,8 @@
spring:
config:
import:
# - classpath:nacos.yml
- classpath:prodnacos.yml
- classpath:nacos.yml
# - classpath:prodnacos.yml
- classpath:sdk.yml
- classpath:swagger.yml
# - classpath:ds.yml

View File

@ -35,7 +35,7 @@ public class DaHuaController {
@ApiOperation("同步人员到大华平台-新增")
@PostMapping("/person/sync")
public SingleResponse<Boolean> syncPerson(@Validated @RequestBody DaHuaPersonSyncCmd cmd) {
public SingleResponse<Object> syncPerson(@Validated @RequestBody DaHuaPersonSyncCmd cmd) {
if (daHuaService == null) {
throw new RuntimeException("大华服务未配置");

View File

@ -28,7 +28,7 @@ public class DaHuaServiceImpl implements DaHuaServiceI {
}
@Override
public SingleResponse<Boolean> syncPerson(DaHuaPersonSyncCmd cmd) {
public SingleResponse<Object> syncPerson(DaHuaPersonSyncCmd cmd) {
Long personId = daHuaGateway.generatePersonId();
System.out.println("大华自动生成人员ID: " + personId);
cmd.setId(personId);
@ -37,12 +37,13 @@ public class DaHuaServiceImpl implements DaHuaServiceI {
Boolean dhSuccess = (Boolean) syncResult.get("success");
String dhCode = (String) syncResult.get("code");
String dhErrMsg = (String) syncResult.get("errMsg");
SingleResponse<Boolean> resp = new SingleResponse<>();
Object dhData = syncResult.get("dhData");
SingleResponse<Object> resp = new SingleResponse<>();
resp.setSuccess(dhSuccess != null ? dhSuccess : passed);
resp.setErrCode(dhCode);
resp.setErrMessage(dhErrMsg);
resp.setData(passed);
System.out.println("大华同步人员最终返回 - success:" + resp.isSuccess() + ", errCode:" + resp.getErrCode() + ", errMessage:" + resp.getErrMessage() + ", data:" + resp.getData());
resp.setData(dhData);
System.out.println("大华同步人员最终返回 - success:" + resp.isSuccess() + ", errCode:" + resp.getErrCode() + ", errMessage:" + resp.getErrMessage() + ", data(dhData):" + dhData);
return resp;
}

View File

@ -15,7 +15,7 @@ public interface DaHuaServiceI {
SingleResponse<Long> generatePersonId();
SingleResponse<Boolean> syncPerson(DaHuaPersonSyncCmd cmd);
SingleResponse<Object> syncPerson(DaHuaPersonSyncCmd cmd);
SingleResponse<Boolean> updatePerson(DaHuaPersonSyncCmd cmd);

View File

@ -29,4 +29,6 @@ public interface DaHuaGateway {
Map<String, Object> deleteCar(List<String> carNumList);
Map<String, Object> queryAccessRecord(DaHuaAccessRecordCmd cmd);
String uploadPersonImg(String imageBase64);
}

View File

@ -25,6 +25,7 @@ public class DaHuaPersonApi {
private static final String CAR_PAGE_URL = "/evo-apigw/evo-brm/1.2.0/car/subsystem/page";
private static final String CAR_DELETE_URL = "/evo-apigw/evo-brm/1.0.0/car/delete";
private static final String ACCESS_RECORD_URL = "/evo-apigw/evo-accesscontrol/1.0.0/card/accessControl/swingCardRecord/bycondition/combined";
private static final String PERSON_UPLOAD_IMG_URL = "/evo-apigw/evo-brm/1.0.0/person/subsystem/third/upload/img";
public boolean isConfigured() {
return daHuaApiClient != null;
@ -131,4 +132,16 @@ public class DaHuaPersonApi {
headers.put("Authorization", "bearer " + token);
return daHuaApiClient.postJson(ACCESS_RECORD_URL, body, headers);
}
public GeneralResponse uploadPersonImg(String imageBase64) throws ClientException {
if (daHuaApiClient == null) {
return null;
}
String token = daHuaApiClient.getToken();
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "bearer " + token);
Map<String, Object> body = new HashMap<>();
body.put("imageBase64", imageBase64);
return daHuaApiClient.postJson(PERSON_UPLOAD_IMG_URL, body, headers);
}
}

View File

@ -1,5 +1,6 @@
package com.zcloud.primeport.gatewayimpl;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dahuatech.icc.exception.ClientException;
@ -15,7 +16,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -99,9 +102,17 @@ public class DaHuaGatewayImpl implements DaHuaGateway {
if (daHuaPersonApi == null || !daHuaPersonApi.isConfigured()) {
throw new RuntimeException("大华服务未配置");
}
Map<String, Object> uploadResult = uploadAndSetPersonBiosignaturePaths(cmd);
if (uploadResult != null) {
return uploadResult;
}
Map<String, Object> body = convertToMap(cmd);
processDaHuaPersonBiosignatures(body);
System.out.println("==========[syncPerson 完整请求参数 START]==========");
System.out.println(JSONUtil.toJsonPrettyStr(body));
debugPrintPersonBiosignatures(body);
System.out.println("==========[syncPerson 完整请求参数 END]============");
log.info("大华同步人员请求参数: {}", JSONUtil.toJsonStr(body));
System.out.println("大华同步人员请求参数: " + JSONUtil.toJsonStr(body));
Map<String, Object> resultMap = new HashMap<>();
try {
GeneralResponse response = daHuaPersonApi.addPerson(body);
@ -114,19 +125,44 @@ public class DaHuaGatewayImpl implements DaHuaGateway {
resultMap.put("success", false);
resultMap.put("code", "SYSTEM_ERROR");
resultMap.put("errMsg", "response为null");
resultMap.put("dhData", null);
return resultMap;
}
JSONObject jsonObject = JSONUtil.parseObj(responseJson);
Boolean dhSuccess = jsonObject.getBool("success", false);
String dhCode = jsonObject.getStr("code", response.getCode());
String dhErrMsg = jsonObject.getStr("errMsg", "");
String dhResult = jsonObject.getStr("result", "");
Object dhResultObj = jsonObject.get("result");
Object dhData = jsonObject.get("data");
if (dhResultObj != null) {
try {
JSONObject bizObj;
if (dhResultObj instanceof String) {
bizObj = JSONUtil.parseObj((String) dhResultObj);
} else if (dhResultObj instanceof JSONObject) {
bizObj = (JSONObject) dhResultObj;
} else {
bizObj = JSONUtil.parseObj(JSONUtil.toJsonStr(dhResultObj));
}
dhSuccess = bizObj.getBool("success", dhSuccess);
dhCode = bizObj.getStr("code", dhCode);
dhErrMsg = bizObj.getStr("errMsg", dhErrMsg);
Object tmpData = bizObj.get("data");
if (tmpData != null) {
dhData = tmpData;
}
} catch (Exception e) {
log.warn("大华同步人员解析result字段失败: {}", e.getMessage());
}
}
boolean passed = "0".equals(dhCode);
resultMap.put("passed", passed);
resultMap.put("success", dhSuccess);
resultMap.put("code", dhCode);
resultMap.put("errMsg", dhErrMsg);
resultMap.put("result", dhResult);
resultMap.put("result", dhResultObj);
resultMap.put("dhData", dhData);
System.out.println("大华同步人员返回dhData: " + dhData);
if (!passed) {
log.error("大华同步人员失败: code={}, errMsg={}, response={}", dhCode, dhErrMsg, responseJson);
System.out.println("大华同步人员失败: code=" + dhCode + ", errMsg=" + dhErrMsg);
@ -138,6 +174,7 @@ public class DaHuaGatewayImpl implements DaHuaGateway {
resultMap.put("success", false);
resultMap.put("code", "CLIENT_EXCEPTION");
resultMap.put("errMsg", e.getMessage());
resultMap.put("dhData", null);
return resultMap;
}
}
@ -155,9 +192,17 @@ public class DaHuaGatewayImpl implements DaHuaGateway {
emptyMap.put("errMsg", "id不能为空");
return emptyMap;
}
Map<String, Object> uploadResult = uploadAndSetPersonBiosignaturePaths(cmd);
if (uploadResult != null) {
return uploadResult;
}
Map<String, Object> body = convertToMap(cmd);
processDaHuaPersonBiosignatures(body);
System.out.println("==========[updatePerson 完整请求参数 START]==========");
System.out.println(JSONUtil.toJsonPrettyStr(body));
debugPrintPersonBiosignatures(body);
System.out.println("==========[updatePerson 完整请求参数 END]============");
log.info("大华修改人员请求参数: {}", JSONUtil.toJsonStr(body));
System.out.println("大华修改人员请求参数: " + JSONUtil.toJsonStr(body));
Map<String, Object> resultMap = new HashMap<>();
try {
GeneralResponse response = daHuaPersonApi.updatePerson(body);
@ -215,6 +260,215 @@ public class DaHuaGatewayImpl implements DaHuaGateway {
return map;
}
private static String getStr(Map<String, Object> m, String key) {
Object v = m.get(key);
return v == null ? null : v.toString();
}
private static String onlyPureBase64(String raw) {
if (raw == null) return null;
String s = raw.trim();
if (s.isEmpty()) return s;
int comma = s.indexOf(',');
if (comma > 0 && comma < 100) {
String prefix = s.substring(0, comma).toLowerCase();
if (prefix.startsWith("data:") && prefix.contains("base64")) {
s = s.substring(comma + 1).trim();
}
}
return s.replaceAll("\\s+", "");
}
private static boolean isHttpUrl(String s) {
if (s == null) return false;
String low = s.toLowerCase().trim();
return low.startsWith("http://") || low.startsWith("https://");
}
private static boolean looksLikeBase64(String s) {
if (s == null || s.length() < 50) return false;
String t = s.trim();
if (t.startsWith("data:")) return true;
int ok = 0;
int check = Math.min(t.length(), 200);
for (int i = 0; i < check; i++) {
char c = t.charAt(i);
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|| c == '+' || c == '/' || c == '=') ok++;
}
return ((double) ok / check) > 0.95;
}
private static byte[] downloadUrlBytes(String url) {
return HttpRequest.get(url).timeout(15000).execute().bodyBytes();
}
private static String detectMimePrefix(byte[] bytes) {
if (bytes == null || bytes.length < 4) return "data:image/jpeg;base64,";
if (bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xD8 && bytes[2] == (byte) 0xFF) {
return "data:image/jpeg;base64,";
}
if (bytes.length >= 8
&& bytes[0] == (byte) 0x89
&& bytes[1] == (byte) 0x50
&& bytes[2] == (byte) 0x4E
&& bytes[3] == (byte) 0x47
&& bytes[4] == (byte) 0x0D
&& bytes[5] == (byte) 0x0A
&& bytes[6] == (byte) 0x1A
&& bytes[7] == (byte) 0x0A) {
return "data:image/png;base64,";
}
return "data:image/jpeg;base64,";
}
@SuppressWarnings("unchecked")
private static void debugPrintPersonBiosignatures(Map<String, Object> body) {
Object bios = body.get("personBiosignatures");
if (bios == null || !(bios instanceof List)) {
System.out.println("[DEBUG] personBiosignatures 字段: 不存在或不是List");
return;
}
List<Object> list = (List<Object>) bios;
System.out.println("[DEBUG] personBiosignatures 数量: " + list.size());
for (int i = 0; i < list.size(); i++) {
Object item = list.get(i);
System.out.println("[DEBUG] --- 第 " + (i + 1) + " 条 ---");
if (item instanceof Map) {
Map<String, Object> m = (Map<String, Object>) item;
System.out.println("[DEBUG] 所有字段 keys: " + String.join(", ", m.keySet()));
for (Map.Entry<String, Object> e : m.entrySet()) {
Object v = e.getValue();
if (v == null) {
System.out.println("[DEBUG] " + e.getKey() + " = null");
} else {
String s = v.toString();
String show = s.length() > 120 ? s.substring(0, 120) + "...(len=" + s.length() + ")" : s;
System.out.println("[DEBUG] " + e.getKey() + " = " + show);
}
}
} else {
System.out.println("[DEBUG] 类型不是Map, 是: " + (item == null ? "null" : item.getClass().getName()));
}
}
}
@SuppressWarnings("unchecked")
private void processDaHuaPersonBiosignatures(Map<String, Object> body) {
Object bios = body.get("personBiosignatures");
if (bios == null || !(bios instanceof List)) return;
List<Object> inList = (List<Object>) bios;
List<Map<String, Object>> outList = new ArrayList<>();
int seq = 0;
for (Object item : inList) {
seq++;
Object rawType = null;
Object rawIndex = null;
String path = null;
String rawBase64 = null;
if (item instanceof Map) {
Map<String, Object> mm = (Map<String, Object>) item;
rawType = mm.get("type");
rawIndex = mm.get("index");
path = getStr(mm, "path");
rawBase64 = getStr(mm, "base64Data");
if (rawBase64 == null) rawBase64 = getStr(mm, "data");
} else if (item instanceof DaHuaPersonSyncCmd.PersonBiosignature) {
DaHuaPersonSyncCmd.PersonBiosignature b = (DaHuaPersonSyncCmd.PersonBiosignature) item;
rawType = b.getType();
rawIndex = b.getIndex();
path = b.getPath();
rawBase64 = b.getBase64Data();
} else {
continue;
}
Map<String, Object> out = new HashMap<>();
if (rawType != null) out.put("type", rawType);
if (rawIndex != null) out.put("index", rawIndex);
String finalBase64WithPrefix = null;
boolean pathAlreadyUploaded = false;
if (path != null && !path.trim().isEmpty() && !looksLikeBase64(path) && !isHttpUrl(path)) {
pathAlreadyUploaded = true;
out.put("path", path.trim());
System.out.println("[大华人员同步] seq=" + seq + " path已通过上传接口获取, 直接使用fileUrl=" + path.trim());
log.info("[大华人员同步] seq={} 使用已上传的图片路径: {}", seq, path.trim());
} else {
out.put("path", "");
if (rawBase64 != null && !rawBase64.trim().isEmpty()) {
String t = rawBase64.trim();
if (t.toLowerCase().startsWith("data:")) {
finalBase64WithPrefix = t.replaceAll("\\s+", "");
System.out.println("[大华人员同步] seq=" + seq + " base64Data已带前缀, 直接使用, len=" + finalBase64WithPrefix.length());
} else {
String pure = t.replaceAll("\\s+", "");
if (!pure.isEmpty()) {
finalBase64WithPrefix = "data:image/jpeg;base64," + pure;
System.out.println("[大华人员同步] seq=" + seq + " base64Data无前缀, 默认补jpeg前缀, len=" + finalBase64WithPrefix.length());
}
}
}
if ((finalBase64WithPrefix == null || finalBase64WithPrefix.isEmpty())
&& path != null && !path.trim().isEmpty()) {
String p = path.trim();
if (isHttpUrl(p)) {
System.out.println("[大华人员同步] seq=" + seq + " 下载图片URL=" + p);
try {
byte[] bytes = downloadUrlBytes(p);
if (bytes != null && bytes.length > 0) {
String mimePrefix = detectMimePrefix(bytes);
String pure = Base64.getEncoder().encodeToString(bytes);
finalBase64WithPrefix = mimePrefix + pure;
System.out.println("[大华人员同步] seq=" + seq + " 下载成功, mime="
+ (mimePrefix.contains("png") ? "png" : "jpeg")
+ ", totalLen=" + finalBase64WithPrefix.length());
} else {
System.err.println("[大华人员同步] seq=" + seq + " 下载失败(返回空)");
}
} catch (Exception e) {
System.err.println("[大华人员同步] seq=" + seq + " 下载图片异常: " + e.getMessage());
log.error("下载人脸图片失败, seq={}, url={}, err={}", seq, p, e.getMessage(), e);
}
} else if (looksLikeBase64(p)) {
String t = p.trim();
if (t.toLowerCase().startsWith("data:")) {
finalBase64WithPrefix = t.replaceAll("\\s+", "");
System.out.println("[大华人员同步] seq=" + seq + " path是带前缀base64, 转存base64Data, len=" + finalBase64WithPrefix.length());
} else {
String pure = onlyPureBase64(t);
if (pure != null && !pure.isEmpty()) {
finalBase64WithPrefix = "data:image/jpeg;base64," + pure;
System.out.println("[大华人员同步] seq=" + seq + " path是纯base64, 转存base64Data并补jpeg前缀, len=" + finalBase64WithPrefix.length());
}
}
} else {
System.out.println("[大华人员同步] seq=" + seq + " path内容: "
+ (p.length() > 100 ? p.substring(0, 100) + "..." : p));
}
}
if (finalBase64WithPrefix != null && !finalBase64WithPrefix.isEmpty()) {
out.put("base64Data", finalBase64WithPrefix);
System.out.println("[大华人员同步] seq=" + seq + " 最终字段: type=" + out.get("type")
+ ", index=" + out.get("index")
+ ", path=\"\"(空字符串)"
+ ", base64Data前80=" + finalBase64WithPrefix.substring(0, Math.min(80, finalBase64WithPrefix.length())) + "...");
log.info("[大华人员同步] seq={} 最终: type={}, index={}, path=空串, base64DataLen={}",
seq, out.get("type"), out.get("index"), finalBase64WithPrefix.length());
} else {
System.out.println("[大华人员同步] seq=" + seq + " 未得到有效base64字段: type=" + out.get("type")
+ ", index=" + out.get("index") + ", path=\"\"(空字符串), 无base64Data");
}
}
outList.add(out);
}
body.put("personBiosignatures", outList);
}
@Override
public Map<String, Object> deletePerson(List<Long> ids, Integer openDeleteFlag) {
if (daHuaPersonApi == null || !daHuaPersonApi.isConfigured()) {
@ -587,4 +841,117 @@ public class DaHuaGatewayImpl implements DaHuaGateway {
return resultMap;
}
}
@Override
public String uploadPersonImg(String imageBase64) {
if (daHuaPersonApi == null || !daHuaPersonApi.isConfigured()) {
throw new RuntimeException("大华服务未配置");
}
if (imageBase64 == null || imageBase64.trim().isEmpty()) {
throw new RuntimeException("图片base64不能为空");
}
try {
GeneralResponse response = daHuaPersonApi.uploadPersonImg(imageBase64);
String responseJson = JSONUtil.toJsonStr(response);
log.info("大华上传人员图片返回结果: {}", responseJson);
System.out.println("大华上传人员图片返回结果: " + responseJson);
if (response == null) {
throw new RuntimeException("大华上传人员图片失败: response为null");
}
JSONObject jsonObject = JSONUtil.parseObj(responseJson);
Boolean outerSuccess = jsonObject.getBool("success", false);
String outerCode = jsonObject.getStr("code", "");
String outerErrMsg = jsonObject.getStr("errMsg", "");
Boolean bizSuccess = outerSuccess;
String resultCode = null;
String fileUrl = null;
String bizErrMsg = outerErrMsg;
Object resultObj = jsonObject.get("result");
if (resultObj != null) {
try {
JSONObject bizObj;
if (resultObj instanceof String) {
bizObj = JSONUtil.parseObj((String) resultObj);
} else if (resultObj instanceof JSONObject) {
bizObj = (JSONObject) resultObj;
} else {
bizObj = JSONUtil.parseObj(JSONUtil.toJsonStr(resultObj));
}
bizSuccess = bizObj.getBool("success", bizSuccess);
bizErrMsg = bizObj.getStr("errMsg", bizErrMsg);
Object bizDataObj = bizObj.get("data");
if (bizDataObj != null) {
JSONObject bizDataJson = JSONUtil.parseObj(bizDataObj);
resultCode = bizDataJson.getStr("result");
fileUrl = bizDataJson.getStr("fileUrl");
System.out.println("大华上传人员图片解析result字段成功: resultCode=" + resultCode + ", fileUrl=" + fileUrl);
}
} catch (Exception e) {
log.warn("大华上传人员图片解析result字段失败: {}", e.getMessage());
System.out.println("大华上传人员图片解析result字段失败: " + e.getMessage());
}
}
boolean resultOk = (resultCode == null || resultCode.isEmpty()) || "0".equals(resultCode);
if (!bizSuccess || !resultOk) {
String msg = "大华上传人员图片失败: success=" + bizSuccess + ", result=" + resultCode + ", outerCode=" + outerCode + ", errMsg=" + bizErrMsg;
log.error(msg);
throw new RuntimeException(msg);
}
if (fileUrl == null || fileUrl.trim().isEmpty()) {
throw new RuntimeException("大华上传人员图片失败: 未返回fileUrl");
}
System.out.println("大华上传人员图片成功, fileUrl=" + fileUrl);
return fileUrl;
} catch (ClientException e) {
log.error("大华上传人员图片异常: {}", e.getMessage(), e);
throw new RuntimeException("大华上传人员图片异常", e);
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> uploadAndSetPersonBiosignaturePaths(DaHuaPersonSyncCmd cmd) {
List<DaHuaPersonSyncCmd.PersonBiosignature> bios = cmd.getPersonBiosignatures();
if (bios == null || bios.isEmpty()) {
return null;
}
int seq = 0;
for (DaHuaPersonSyncCmd.PersonBiosignature bio : bios) {
seq++;
String base64Data = bio.getBase64Data();
if (base64Data == null || base64Data.trim().isEmpty()) {
continue;
}
String finalBase64WithPrefix;
String t = base64Data.trim();
if (t.toLowerCase().startsWith("data:")) {
finalBase64WithPrefix = t.replaceAll("\\s+", "");
} else {
String pure = t.replaceAll("\\s+", "");
if (pure.isEmpty()) {
continue;
}
finalBase64WithPrefix = "data:image/jpeg;base64," + pure;
}
System.out.println("[大华人员图片上传] seq=" + seq + " 开始上传图片, base64长度=" + finalBase64WithPrefix.length());
try {
String fileUrl = uploadPersonImg(finalBase64WithPrefix);
bio.setPath(fileUrl);
System.out.println("[大华人员图片上传] seq=" + seq + " 上传成功, path=" + fileUrl);
} catch (Exception e) {
log.error("[大华人员图片上传] seq=" + seq + " 上传失败: {}", e.getMessage(), e);
System.err.println("[大华人员图片上传] seq=" + seq + " 上传失败: " + e.getMessage());
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("passed", false);
resultMap.put("success", false);
resultMap.put("code", "IMG_UPLOAD_FAIL");
resultMap.put("errMsg", "第" + seq + "张人脸图片上传失败: " + e.getMessage());
resultMap.put("dhData", null);
return resultMap;
}
}
return null;
}
}