package com.etotem.cfc.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etotem.cfc.entity.AiYunyiMapping;
import com.etotem.cfc.mapper.AiYunyiMappingMapper;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 爱云医 AI 检测编排宿主:照片路径(能力键 {@code ai.aiyunyi.detect},S-cfc-472)
* 与视频路径(能力键 {@code ai.aiyunyi.detectVideo},S-cfc-473)共用同一编排宿主。
*
*
服务端统一收口鉴权与转发:私钥/令牌只在 {@link AicdsGatewayService} 内使用,前端仅带小程序 token。
* 本类负责把「登录 → 商品 → 下单 → 建检测人 → 激活 → 套餐子项 → 录入数据 → 报告」串成一条链路,
* 并通过 {@code aiyunyi_mapping} 映射保证同一成员重复识别幂等;视频类型另取 H5 检测页地址。
*/
@Service
public class AicdsDetectionService {
/** 商品列表为空时的归一提示(§4.5)。 */
private static final String NO_SPU_MESSAGE = "该服务尚未开通";
/** 无可用子项时的归一提示(§4.5)。 */
private static final String NO_ITEMS_MESSAGE = "次数已用完";
private static final int DETECTION_TYPE_NORMAL = 0;
private static final int DETECTION_TYPE_CANCER = 3;
/** 视频路径:AIBMP=1、AIBMP-PRO=2(§3.4)。 */
private static final int INSPECTION_TYPE_AIBMP = 1;
private static final int INSPECTION_TYPE_AIBMP_PRO = 2;
/** 网关:签名/令牌/转发统一收口,字段非 final 便于 Mockito mock 单测。 */
@Resource
private AicdsGatewayService aicdsGatewayService;
/** 本地幂等映射表(aiyunyi_mapping)。 */
@Resource
private AiYunyiMappingMapper aiyunyiMappingMapper;
/**
* 构造器注入网关,使宿主可在纯单测中以 Mockito mock 注入(§8 mock gateway)。
* 同时满足 Spring 自动装配。
*/
public AicdsDetectionService(AicdsGatewayService aicdsGatewayService) {
this.aicdsGatewayService = aicdsGatewayService;
}
/** 无参构造器:便于纯反射单测(无 Spring 上下文)直接构造宿主。 */
public AicdsDetectionService() {
}
/**
* 照片路径主流程入口(对应 POST /api/aiyunyi/detect)。
*
* request 可含:memberId / familyId / inspectionType / accessToken / userId 及 5 组素材 URL 列表。
*/
public Map detect(Map request) {
Map input = request == null ? Collections.emptyMap() : request;
Map result = new LinkedHashMap();
String accessToken = text(input.get("accessToken"));
String userId = text(input.get("userId"));
int inspectionType = intValue(input.get("inspectionType"));
long memberId = longValue(input.get("memberId"));
long familyId = longValue(input.get("familyId"));
// 1) 登录:换取业务 accessToken
Map login = identify(input, accessToken, userId);
String bizToken = text(login.get("accessToken"));
if (isBlank(bizToken)) {
bizToken = accessToken;
}
// 2) 商品列表:空则归一提示
Map spuPage = spuPage(input, bizToken, userId);
if (isEmpty(spuPage)) {
result.put("message", NO_SPU_MESSAGE);
return result;
}
// 3) 商品明细
Map detail = getDetail(spuPage, bizToken, userId);
// 4) 下单
Map order = orderCreate(detail, bizToken, userId);
// 5) 建检测人
Map createdUser = detectionUserCreate(input, order, bizToken, userId);
long detectionUserId = longValue(createdUser.get("detectionUserId"));
long detectionReportUserId = longValue(createdUser.get("detectionReportUserId"));
// 6) 激活检测人
enterDetectionUser(detectionUserId, bizToken, userId);
// 7) 套餐分页
Map packagePage = packagePage(createdUser, bizToken, userId);
// 8) 套餐子项:无可用则归一提示
Map items = getItems(packagePage, bizToken, userId);
if (isEmpty(items)) {
result.put("message", NO_ITEMS_MESSAGE);
return result;
}
long detectionPackageId = longValue(items.get("detectionPackageId"));
long detectionPackageItemId = longValue(items.get("detectionPackageItemId"));
// 幂等映射:同一成员重复识别复用已建检测人/未用子项
AiYunyiMapping mapping = findOrCreateMapping(memberId, familyId, detectionUserId,
detectionPackageId, detectionPackageItemId, inspectionType, 0);
result.put("mappingId", mapping == null ? 0L : mapping.getId());
// 9) 分流:照片录入数据,视频先取检测页
String route = resolveRoute(inspectionType);
if ("path".equals(route)) {
Map path = getPath(detectionUserId, detectionPackageItemId, bizToken, userId);
result.put("path", path);
} else {
int requestType = inspectionType == DETECTION_TYPE_CANCER ? DETECTION_TYPE_CANCER : DETECTION_TYPE_NORMAL;
Map payload = buildEnterDetectionDataRequest(detectionUserId, detectionReportUserId,
detectionPackageId, detectionPackageItemId,
list(input.get("basicUrls")), list(input.get("reportUrls")),
list(input.get("familyHistoryVoiceUrls")), list(input.get("diseaseVoiceUrls")),
list(input.get("attachmentUrls")), requestType);
Map entered = enterDetectionData(payload, bizToken, userId);
result.put("entered", entered);
}
// 10) 拉取报告(异步生成)
Map report = reportGet(detectionUserId, detectionPackageItemId, bizToken, userId);
result.put("report", report);
return result;
}
/**
* 检测类型分流(§3.4):0/3 走录入检测数据,1/2 走取 H5 检测页。
*/
public String resolveRoute(int inspectionType) {
if (inspectionType == DETECTION_TYPE_NORMAL || inspectionType == DETECTION_TYPE_CANCER) {
return "data";
}
return "path";
}
/**
* 查找或创建本地幂等映射(§3.5):同一成员/家庭/检测类型复用已有记录。
*/
public AiYunyiMapping findOrCreateMapping(long memberId, long familyId, long detectionUserId,
long detectionPackageId, long detectionPackageItemId,
int inspectionType, int status) {
if (aiyunyiMappingMapper == null) {
return null;
}
QueryWrapper query = new QueryWrapper();
query.eq("member_id", memberId).eq("family_id", familyId)
.eq("aiyunyi_inspection_type", inspectionType);
AiYunyiMapping existing = aiyunyiMappingMapper.selectOne(query);
if (existing != null) {
existing.setAiyunyiDetectionUserId(detectionUserId);
existing.setAiyunyiPackageId(detectionPackageId);
existing.setAiyunyiPackageItemId(detectionPackageItemId);
existing.setStatus(status);
aiyunyiMappingMapper.updateById(existing);
return existing;
}
AiYunyiMapping mapping = new AiYunyiMapping();
mapping.setMemberId(memberId);
mapping.setFamilyId(familyId);
mapping.setAiyunyiDetectionUserId(detectionUserId);
mapping.setAiyunyiPackageId(detectionPackageId);
mapping.setAiyunyiPackageItemId(detectionPackageItemId);
mapping.setAiyunyiInspectionType(inspectionType);
mapping.setStatus(status);
aiyunyiMappingMapper.insert(mapping);
return mapping;
}
/**
* 构造录入检测数据请求体(契约 §A.4)。
*
* basicUrlList 固定 12 项(id=index、type=0、isQualified 留空);
* reportUrlList type=3;家族病史语音 type=1;已知病症语音 type=2;体表异常 type=4;
* request.type 仅允许 0(普通)/3(癌症),视频类型快速失败。
*/
public Map buildEnterDetectionDataRequest(long detectionUserId,
long detectionReportUserId,
long detectionPackageId,
long detectionPackageItemId,
List basicUrls,
List reportUrls,
List familyHistoryVoiceUrls,
List diseaseVoiceUrls,
List attachmentUrls,
int type) {
if (type != DETECTION_TYPE_NORMAL && type != DETECTION_TYPE_CANCER) {
throw new IllegalArgumentException(
"爱云医录入检测数据 type 仅允许 0(普通)/3(癌症),实际 " + type);
}
Map request = new LinkedHashMap();
request.put("detectionUserId", detectionUserId);
request.put("detectionReportUserId", detectionReportUserId);
request.put("detectionPackageId", detectionPackageId);
request.put("detectionPackageItemId", detectionPackageItemId);
request.put("basicUrlList", buildUrlItems(basicUrls, DETECTION_TYPE_NORMAL, true));
request.put("familyHistoryUrlList", buildUrlItems(familyHistoryVoiceUrls, 1, false));
request.put("diseaseUrlList", buildUrlItems(diseaseVoiceUrls, 2, false));
request.put("reportUrlList", buildUrlItems(reportUrls, DETECTION_TYPE_CANCER, false));
request.put("attachmentUrlList", buildUrlItems(attachmentUrls, 4, false));
request.put("type", type);
return request;
}
// ==================== 视频分支(ai.aiyunyi.detectVideo,S-cfc-473) ====================
/**
* AC3/AC4:取视频检测 H5 页地址。两个必填 ID 原样透传给网关 getPath,
* 返回响应中的 {@code data.path},不做改写、截断或默认填空串。
*/
public String detectVideo(long detectionPackageItemId, long detectionReportUserId) {
Object response = aicdsGatewayService.getPath(detectionPackageItemId, detectionReportUserId);
// 兼容网关直接返回 path 字符串的调用形态(code 缺省视为 0)。
if (response instanceof CharSequence) {
String directPath = response.toString();
requireNonBlankPath(directPath);
return directPath;
}
if (!(response instanceof Map)) {
throw new IllegalStateException(
"爱云医视频检测 getPath 响应为空或格式非法,无法取得检测页面地址(§4.5)");
}
Map, ?> body = (Map, ?>) response;
int code = intValue(body.get("code"));
if (code != 0) {
throw new IllegalStateException(
"爱云医视频检测 getPath 失败,code=" + code + "(§4.5 错误归一)");
}
Object data = body.get("data");
Object path = (data instanceof Map) ? ((Map, ?>) data).get("path") : null;
if (path == null) {
throw new IllegalStateException(
"爱云医视频检测 getPath 响应缺少 data.path,禁止返回空 URL(§A.5)");
}
String h5Path = path.toString();
requireNonBlankPath(h5Path);
return h5Path;
}
/** AC5:仅 1(AIBMP)/2(AIBMP-PRO) 走视频 getPath 路径;0/3 及非法值均返回 false。 */
public boolean isVideoInspectionType(int inspectionType) {
return inspectionType == INSPECTION_TYPE_AIBMP
|| inspectionType == INSPECTION_TYPE_AIBMP_PRO;
}
/**
* AC6:web-view 采集完成后的收尾——先轮询 packagePage 确认完成,
* 再调 reportGet 拉报告。顺序不可颠倒;网关异常不在此吞掉。
*/
public Object getReportAfterVideoDetect(long packageId) {
aicdsGatewayService.getPackagePage(packageId);
return aicdsGatewayService.getReport(packageId);
}
// ==================== 照片编排步骤(顺序与 §5 时序一致) ====================
private Map identify(Map input, String accessToken, String userId) {
Map body = new LinkedHashMap();
body.put("appKey", text(input.get("appKey")));
return invoke("/v1/identify", body, accessToken, userId);
}
private Map spuPage(Map input, String accessToken, String userId) {
Map body = new LinkedHashMap();
body.put("inspectionType", intValue(input.get("inspectionType")));
return invoke("/v1/spu/page", body, accessToken, userId);
}
private Map getDetail(Map spuPage, String accessToken, String userId) {
Map body = new LinkedHashMap();
body.put("spuId", spuPage.get("spuId"));
return invoke("/v1/spu/get-detail", body, accessToken, userId);
}
private Map orderCreate(Map detail, String accessToken, String userId) {
Map body = new LinkedHashMap();
body.put("spuId", detail.get("spuId"));
return invoke("/v1/order/create", body, accessToken, userId);
}
private Map detectionUserCreate(Map input, Map order,
String accessToken, String userId) {
Map body = new LinkedHashMap();
body.put("memberId", input.get("memberId"));
body.put("orderId", order.get("orderId"));
return invoke("/v1/detection-user/create", body, accessToken, userId);
}
private Map enterDetectionUser(long detectionUserId, String accessToken, String userId) {
Map body = new LinkedHashMap();
body.put("detectionUserId", detectionUserId);
return invoke("/v1/enter/detection_user", body, accessToken, userId);
}
private Map packagePage(Map createdUser, String accessToken, String userId) {
Map body = new LinkedHashMap();
body.put("detectionUserId", createdUser.get("detectionUserId"));
return invoke("/v1/package/page", body, accessToken, userId);
}
private Map getItems(Map packagePage, String accessToken, String userId) {
Map body = new LinkedHashMap();
body.put("packageId", packagePage.get("packageId"));
return invoke("/v1/package/get-items", body, accessToken, userId);
}
private Map getPath(long detectionUserId, long packageItemId,
String accessToken, String userId) {
Map body = new LinkedHashMap();
body.put("detectionUserId", detectionUserId);
body.put("packageItemId", packageItemId);
return invoke("/v1/get-path", body, accessToken, userId);
}
private Map enterDetectionData(Map payload,
String accessToken, String userId) {
return invoke("/v1/enter/detection_data", payload, accessToken, userId);
}
private Map reportGet(long detectionUserId, long packageItemId,
String accessToken, String userId) {
Map body = new LinkedHashMap();
body.put("detectionUserId", detectionUserId);
body.put("packageItemId", packageItemId);
return invoke("/v1/report/get", body, accessToken, userId);
}
/** 统一经网关转发(鉴权/熔断/超时由网关负责)。 */
@SuppressWarnings("unchecked")
private Map invoke(String path, Object body, String accessToken, String userId) {
if (aicdsGatewayService == null) {
return new LinkedHashMap();
}
ResponseEntity