package com.ycwl.basic.service.pc.impl;

import com.ycwl.basic.facebody.adapter.IFaceBodyAdapter;
import com.ycwl.basic.facebody.entity.SearchFaceResp;
import com.ycwl.basic.integration.device.dto.device.DeviceV2DTO;
import com.ycwl.basic.mapper.FaceDetectLogAiCamMapper;
import com.ycwl.basic.model.pc.faceDetectLog.entity.FaceDetectLogAiCamEntity;
import com.ycwl.basic.repository.DeviceRepository;
import com.ycwl.basic.service.pc.FaceDetectLogAiCamService;
import com.ycwl.basic.utils.JacksonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FaceDetectLogAiCamServiceImpl implements FaceDetectLogAiCamService {

    private final FaceDetectLogAiCamMapper faceDetectLogAiCamMapper;
    private final DeviceRepository deviceRepository;

    @Override
    public void searchAndLog(Long scenicId, Long faceId, String faceUrl, IFaceBodyAdapter adapter) {
        List<DeviceV2DTO> devices = deviceRepository.getAllDeviceByScenicId(scenicId);
        for (DeviceV2DTO device : devices) {
            if (!device.getType().equals("AI_CAM")) {
                continue;
            }
            searchDeviceAndLog(scenicId, device.getId(), faceId, faceUrl, adapter);
        }
    }

    private SearchFaceResp searchDeviceAndLog(Long scenicId, Long deviceId, Long faceId, String faceUrl, IFaceBodyAdapter adapter) {
        String dbName = "AiCam" + deviceId;

        SearchFaceResp resp = null;
        try {
            // 调用适配器搜索人脸
            resp = adapter.searchFace(dbName, faceUrl);
        } catch (Exception e) {
            log.error("AI相机人脸搜索异常: scenicId={}, deviceId={}, faceId={}", scenicId, deviceId, faceId, e);
            // 发生异常时记录空结果或错误信息，视业务需求而定。这里暂不中断流程，继续记录日志
        }

        try {
            // 记录日志
            FaceDetectLogAiCamEntity logEntity = new FaceDetectLogAiCamEntity();
            logEntity.setScenicId(scenicId);
            logEntity.setDeviceId(deviceId);
            logEntity.setFaceId(faceId);
            logEntity.setDbName(dbName);
            logEntity.setFaceUrl(faceUrl);
            logEntity.setCreateTime(new Date());

            if (resp != null) {
                logEntity.setScore(resp.getOriginalFaceScore()); // 记录图片中检测到的人脸质量分或首位匹配分?
                // SearchFaceResp 的 getOriginalFaceScore 通常是图片质量分，getFirstMatchRate 是最佳匹配分
                // 需根据 SearchFaceResp 定义确认。假设 getFirstMatchRate() 是匹配分
                // 实际上 searchFace 返回的是匹配列表。

                // 记录原始响应
                logEntity.setMatchRawResult(JacksonUtil.toJSONString(resp));
            } else {
                logEntity.setMatchRawResult("{\"error\": \"search failed or exception\"}");
            }

            faceDetectLogAiCamMapper.add(logEntity);

        } catch (Exception e) {
            log.error("保存AI相机人脸识别日志失败: faceId={}", faceId, e);
        }

        return resp;
    }
}
