package biz.kq; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import core.co.haikang.HkApiClient; import core.co.haikang.HkProtocolC; import org.apache.commons.lang3.StringUtils; import ss.db.Db; import ss.db.SqlCmd; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; /** * 本地 JSP 手工排查用。 * 不接入现有 serv 路由,只提供“按学生姓名实时查询海康 auth_config/search”的独立能力。 */ public final class HkAuthConfigSearchLocalV3U { private static final HkApiClient HK_API_CLIENT = new HkApiClient(); private static final Gson GSON = new GsonBuilder() .setPrettyPrinting() .disableHtmlEscaping() .create(); private static final String DEF_TAG_ID = "frs"; private HkAuthConfigSearchLocalV3U() { } public static String queryByStudentNameJson(String studentName) { try { return GSON.toJson(queryByStudentName(studentName)); } catch (Exception e) { Map errorMap = new LinkedHashMap<>(); errorMap.put("ok", false); errorMap.put("implVersion", "2026-06-18-v3"); errorMap.put("queryStudentName", StringUtils.trimToNull(studentName)); errorMap.put("errorType", e.getClass().getName()); errorMap.put("error", e.getMessage()); errorMap.put("stackTrace", makeStackTrace(e)); return GSON.toJson(errorMap); } } public static Map queryByStudentName(String studentName) throws Exception { String name = StringUtils.trimToNull(studentName); Map root = new LinkedHashMap<>(); root.put("implVersion", "2026-06-18-v3"); root.put("queryStudentName", name); root.put("queryTime", OffsetDateTime.now().toString()); Map hkConnParm = makeHkConnParm(); root.put("hkConnSummary", makeHkConnSummary(hkConnParm)); if (StringUtils.isBlank(name)) { root.put("ok", false); root.put("msg", "缺少学生姓名,请使用 ?xm=姓名 或 ?学生姓名=姓名 访问。"); root.put("studentCount", 0); root.put("studentList", List.of()); return root; } try (Db gdba = Db.makeConn()) { if (gdba == null) { root.put("ok", false); root.put("msg", "数据库连接失败,Db.makeConn() 返回 null。"); root.put("studentCount", 0); root.put("studentList", List.of()); return root; } List> studentList = loadStudentList(gdba, name); String matchMode = "exact"; if (studentList.isEmpty()) { studentList = loadStudentListLike(gdba, name); matchMode = "like"; } for (Map student : studentList) { long ryid = rdLong(student.get("ryid")); List> itemList = loadLeaveAuthItemList(gdba, ryid); for (Map item : itemList) fillAuthConfigSearchResult(hkConnParm, item); student.put("leaveAuthItemCount", itemList.size()); student.put("leaveAuthItemList", itemList); } root.put("ok", true); root.put("matchMode", matchMode); root.put("studentCount", studentList.size()); root.put("studentList", studentList); root.put("msg", studentList.isEmpty() ? "未查询到匹配学生。" : "查询成功。"); return root; } } private static Map makeHkConnParm() { Map hkConnParm = new LinkedHashMap<>(HkConnU.makeHkConnParm()); String tagId = rdCfg("hk.leaveAuth.tagId", "HK_LEAVE_AUTH_TAG_ID"); hkConnParm.put("tagId", StringUtils.defaultIfBlank(tagId, DEF_TAG_ID)); return hkConnParm; } private static Map makeHkConnSummary(Map hkConnParm) { Map row = new LinkedHashMap<>(); row.put("host", hkConnParm.get("host")); row.put("port", hkConnParm.get("port")); row.put("appKey", hkConnParm.get("appKey")); row.put("tagId", hkConnParm.get("tagId")); return row; } private static List> loadStudentList(Db gdba, String studentName) throws Exception { String sql = "" + "select ryid,xm,ryh,rylbm,jlztm,bmid " + "from ry where xm=:xm order by ryid desc"; SqlCmd sqlCmd = new SqlCmd(sql); sqlCmd.wrStrParm("xm", studentName); try { return gdba.doSelMapListByC(sqlCmd); } catch (Exception e) { throw new RuntimeException("loadStudentList 执行失败,xm=" + studentName, e); } } private static List> loadStudentListLike(Db gdba, String studentName) throws Exception { String sql = "" + "select ryid,xm,ryh,rylbm,jlztm,bmid " + "from ry where xm like :xm order by ryid desc"; SqlCmd sqlCmd = new SqlCmd(sql); sqlCmd.wrStrParm("xm", "%" + studentName + "%"); try { return gdba.doSelMapListByC(sqlCmd); } catch (Exception e) { throw new RuntimeException("loadStudentListLike 执行失败,xm=" + studentName, e); } } private static List> loadLeaveAuthItemList(Db gdba, long ryid) throws Exception { String sql = "" + "select * from (" + " select rc.rcid,rc.rclbm,rc.kssj,rc.jssj," + " i.item_id,i.item_type,i.item_name,i.resource_scope,i.resource_keys,i.person_id," + " i.auth_beg,i.auth_end," + " i.sync_stage,i.platform_config_confirmed,i.config_search_matched," + " i.delete_confirmed,i.config_task_id,i.delete_task_id," + " i.delete_time,i.updated_at " + " from rc rc" + " join rchkla_item i on i.rcid=rc.rcid" + " where rc.fzryid=:ryid" + " order by i.updated_at desc nulls last,i.item_id desc" + " ) where rownum<=20"; SqlCmd sqlCmd = new SqlCmd(sql); sqlCmd.wrLongParm("ryid", ryid); try { return gdba.doSelMapListByC(sqlCmd); } catch (Exception e) { throw new RuntimeException("loadLeaveAuthItemList 执行失败,ryid=" + ryid, e); } } private static void fillAuthConfigSearchResult(Map hkConnParm, Map item) { String personId = rdStr(item.get("person_id")); String resourceKeys = rdStr(item.get("resource_keys")); item.put("resourceKeyCount", makeAuthConfigResourceInfoList(resourceKeys).size()); if (StringUtils.isAnyBlank(personId, resourceKeys)) { item.put("authConfigSearchSkipReason", "personId 或 resourceKeys 为空,跳过海康查询。"); return; } Map req = makeAuthConfigSearchReq(personId, resourceKeys); item.put("authConfigSearchReq", req); try { Map resp = searchAuthConfigRespMapWithRaw(hkConnParm, req, item); item.put("authConfigSearchResp", resp); item.put("authConfigSearchRespBrief", makeSearchRespBrief(resp)); item.put("currentWindowCount", countAuthConfigWindow( resp, rdStr(item.get("auth_beg")), rdStr(item.get("auth_end")), true)); item.put("foreignWindowCount", countAuthConfigWindow( resp, rdStr(item.get("auth_beg")), rdStr(item.get("auth_end")), false)); } catch (Exception e) { item.put("authConfigSearchError", e.getMessage()); } } private static Map searchAuthConfigRespMapWithRaw(Map hkConnParm, Map req, Map item) throws Exception { Method method = HkApiClient.class.getDeclaredMethod("postHkJson", Map.class, String.class, Map.class); method.setAccessible(true); JsonObject respJson = (JsonObject) method.invoke(HK_API_CLIENT, hkConnParm, HkProtocolC.HK_AUTH_CONFIG_SEARCH_API_PATH, req); item.put("authConfigSearchRespRawJson", respJson == null ? null : respJson.toString()); @SuppressWarnings("unchecked") Map respMap = GSON.fromJson(respJson, Map.class); return respMap; } private static Map makeAuthConfigSearchReq(String personId, String resourceKeys) { List> resourceInfoList = makeAuthConfigResourceInfoList(resourceKeys); Map req = new LinkedHashMap<>(); req.put("personDataIds", List.of(personId)); req.put("personDataType", "person"); req.put("resourceInfos", resourceInfoList); req.put("resourceDataType", "resource"); req.put("pageNo", 1); req.put("pageSize", Math.max(20, Math.min(200, resourceInfoList.size()))); return req; } private static List> makeAuthConfigResourceInfoList(String resourceKeys) { LinkedHashSet keySet = new LinkedHashSet<>(); if (resourceKeys != null) { for (String part : resourceKeys.split("\\|")) { String key = rdStr(part); if (key != null) keySet.add(key); } } List> out = new ArrayList<>(); for (String key : keySet) { int idx = key.lastIndexOf('#'); if (idx <= 0 || idx >= key.length() - 1) continue; String resourceIndexCode = key.substring(0, idx).trim(); int channelNo = rdChannelNo(key.substring(idx + 1)); Map row = new LinkedHashMap<>(); row.put("resourceIndexCode", resourceIndexCode); row.put("resourceType", "acsDevice"); row.put("channelNos", List.of(channelNo)); out.add(row); } return out; } private static Map makeSearchRespBrief(Map resp) { Map row = new LinkedHashMap<>(); row.put("code", resp == null ? null : resp.get("code")); row.put("msg", resp == null ? null : resp.get("msg")); Map dataMap = castMap(resp == null ? null : resp.get("data")); if (dataMap != null) { row.put("total", dataMap.get("total")); row.put("pageNo", dataMap.get("pageNo")); row.put("pageSize", dataMap.get("pageSize")); } return row; } private static int countAuthConfigWindow(Map resp, String authBeg, String authEnd, boolean currentWindow) { Map dataMap = castMap(resp == null ? null : resp.get("data")); if (dataMap == null) return 0; Object listObj = dataMap.get("list"); if (!(listObj instanceof List list)) return 0; int count = 0; for (Object itemObj : list) { Map row = castMap(itemObj); if (row == null) continue; boolean same = sameTime(rdStr(row.get("startTime")), authBeg) && sameTime(rdStr(row.get("endTime")), authEnd); if (same == currentWindow) count++; } return count; } private static boolean sameTime(String hkText, String dbText) { LocalDateTime hkTime = parseHkTime(hkText); LocalDateTime dbTime = parseDbTime(dbText); return hkTime != null && dbTime != null && hkTime.equals(dbTime); } private static LocalDateTime parseHkTime(String text) { try { return OffsetDateTime.parse(text) .atZoneSameInstant(ZoneId.of("Asia/Shanghai")) .toLocalDateTime(); } catch (Exception ignored) { return null; } } private static LocalDateTime parseDbTime(String text) { try { return Timestamp.valueOf(text).toLocalDateTime(); } catch (Exception ignored) { return null; } } @SuppressWarnings("unchecked") private static Map castMap(Object obj) { if (obj instanceof Map map) return (Map) map; return null; } private static int rdChannelNo(String text) { try { return Math.max(1, (int) Math.round(Double.parseDouble(StringUtils.trim(text)))); } catch (Exception ignored) { return 1; } } private static long rdLong(Object value) { if (value == null) return 0L; if (value instanceof Number number) return number.longValue(); try { return Long.parseLong(String.valueOf(value).trim()); } catch (Exception ignored) { return 0L; } } private static String rdStr(Object value) { if (value == null) return null; String text = String.valueOf(value).trim(); return text.isEmpty() ? null : text; } private static String rdCfg(String propName, String envName) { String value = System.getProperty(propName); if (StringUtils.isNotBlank(value)) return StringUtils.trim(value); value = System.getenv(envName); if (StringUtils.isNotBlank(value)) return StringUtils.trim(value); return null; } private static String makeStackTrace(Throwable e) { if (e == null) return null; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.flush(); return sw.toString(); } }