package com.xly.service; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * ERP 后端(xlyEntry)薄 HTTP 客户端。 * *

xlyAi 的读写业务逻辑在 ERP 后端,xlyAi 只是像前端一样发同样的 API 请求。本类负责: *

*/ @Service public class ErpClient { private static final Logger log = LoggerFactory.getLogger(ErpClient.class); private final ObjectMapper mapper; private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); @Value("${erp.baseurl}") private String baseUrl; @Value("${erp.dev-login.brand:1111111111}") private String brand; @Value("${erp.dev-login.subsidiary:1111111111}") private String subsidiary; @Value("${erp.dev-login.username:admin}") private String username; @Value("${erp.dev-login.password:666666}") private String password; private volatile String cachedToken; public ErpClient(ObjectMapper mapper) { this.mapper = mapper; } /** 用配置的 dev 账号登录 ERP,缓存返回的 Authorization token。 */ private synchronized String login() { try { String url = baseUrl + "/checklogin/" + brand + "/" + subsidiary; String body = mapper.writeValueAsString(Map.of("username", username, "password", password)); HttpRequest req = HttpRequest.newBuilder(URI.create(url)) .header("Content-Type", "application/json;charset=UTF-8") .timeout(Duration.ofSeconds(20)) .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)) .build(); HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); JsonNode root = mapper.readTree(resp.body()); if (root.path("code").asInt() != 1) { throw new IllegalStateException("ERP 登录失败: " + root.path("msg").asText()); } String token = root.path("dataset").path("rows").path(0).path("token").asText(null); if (token == null || token.isBlank()) { throw new IllegalStateException("ERP 登录未返回 token"); } cachedToken = token; log.info("ERP dev-login ok (user={}), token cached", username); return token; } catch (Exception e) { throw new RuntimeException("ERP 登录异常: " + e.getMessage(), e); } } private String token() { String t = cachedToken; return (t != null && !t.isBlank()) ? t : login(); } /** * 读取某表单一页数据,返回整个响应根节点(含 code / msg / dataset)。 * 会话过期(code=-2)时自动重登一次并重试。 */ public JsonNode readForm(String formId, String moduleId, int page, int pageSize, String filterField, String filterValue) { JsonNode root = doRead(formId, moduleId, page, pageSize, filterField, filterValue, token()); if (root.path("code").asInt() == -2) { login(); root = doRead(formId, moduleId, page, pageSize, filterField, filterValue, token()); } return root; } private JsonNode doRead(String formId, String moduleId, int page, int pageSize, String filterField, String filterValue, String tok) { try { String url = baseUrl + "/business/getBusinessDataByFormcustomId/" + formId + "?sModelsId=" + moduleId + "&sName="; List> bFilter = new ArrayList<>(); if (filterField != null && !filterField.isBlank() && filterValue != null && !filterValue.isBlank()) { Map f = new LinkedHashMap<>(); f.put("bFilterName", filterField); f.put("bFilterCondition", "like"); f.put("bFilterValue", filterValue.trim()); bFilter.add(f); } String body = mapper.writeValueAsString(Map.of( "pageNum", page, "pageSize", pageSize, "bFilter", bFilter)); HttpRequest req = HttpRequest.newBuilder(URI.create(url)) .header("Content-Type", "application/json;charset=UTF-8") .header("Authorization", tok) .timeout(Duration.ofSeconds(30)) .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)) .build(); HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); return mapper.readTree(resp.body()); } catch (Exception e) { throw new RuntimeException("ERP 读取异常: " + e.getMessage(), e); } } /** * 执行一次字段更新(addUpdateDelBusinessData, handleType=update)。会话过期自动重登重试。 * 请求体格式与 ERP 前端一致:{@code {data:[{sTable, name:"master", column:[{handleType:"update", sId, field:value}]}]}}。 */ public JsonNode updateForm(String moduleId, String table, String billId, String field, String value) { JsonNode root = doUpdate(moduleId, table, billId, field, value, token()); if (root.path("code").asInt() == -2) { login(); root = doUpdate(moduleId, table, billId, field, value, token()); } return root; } private JsonNode doUpdate(String moduleId, String table, String billId, String field, String value, String tok) { try { String url = baseUrl + "/business/addUpdateDelBusinessData?sModelsId=" + moduleId; Map col = new LinkedHashMap<>(); col.put("handleType", "update"); col.put("sId", billId); col.put(field, value); Map dataItem = new LinkedHashMap<>(); dataItem.put("sTable", table); dataItem.put("name", "master"); dataItem.put("column", List.of(col)); String body = mapper.writeValueAsString(Map.of("data", List.of(dataItem))); HttpRequest req = HttpRequest.newBuilder(URI.create(url)) .header("Content-Type", "application/json;charset=UTF-8") .header("Authorization", tok) .timeout(Duration.ofSeconds(30)) .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)) .build(); HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); return mapper.readTree(resp.body()); } catch (Exception e) { throw new RuntimeException("ERP 更新异常: " + e.getMessage(), e); } } }