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

import com.ycwl.basic.facebody.adapter.IFaceBodyAdapter;
import com.ycwl.basic.integration.common.manager.ScenicConfigManager;
import com.ycwl.basic.model.pc.faceSample.entity.FaceSampleEntity;
import com.ycwl.basic.model.task.resp.SearchFaceRespVo;
import com.ycwl.basic.repository.FaceRepository;
import com.ycwl.basic.service.pc.helper.ScenicConfigFacade;
import com.ycwl.basic.service.task.TaskFaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 人脸识别补救策略
 * 负责执行人脸识别的补救逻辑
 *
 * @author longbinbin
 * @date 2025-01-31
 */
@Slf4j
@Component
public class FaceRecoveryStrategy {

    @Autowired
    private FaceRepository faceRepository;

    @Autowired
    private TaskFaceService faceService;

    @Autowired
    private ScenicConfigFacade scenicConfigFacade;

    /**
     * 执行人脸识别补救逻辑
     * 当匹配结果数量少于阈值时，使用第一个匹配结果重新进行人脸搜索
     *
     * @param originalResult  原始搜索结果
     * @param scenicConfig    景区配置
     * @param faceBodyAdapter 人脸识别适配器
     * @param scenicId        景区ID
     * @return 补救后的搜索结果（如果不需要补救或补救失败则返回原始结果）
     */
    public SearchFaceRespVo executeFaceRecoveryLogic(SearchFaceRespVo originalResult,
                                                     ScenicConfigManager scenicConfig,
                                                     IFaceBodyAdapter faceBodyAdapter,
                                                     Long scenicId) {
        if (originalResult == null || originalResult.getSampleListIds() == null ||
                originalResult.getFirstMatchRate() == null || originalResult.getSampleListIds().isEmpty()) {
            return originalResult;
        }

        if (scenicConfig == null) {
            return originalResult;
        }

        // 检查是否需要执行补救逻辑
        Integer helperThreshold = scenicConfigFacade.getFaceDetectHelperThreshold(scenicId);
        if (helperThreshold == null || helperThreshold <= 0) {
            return originalResult;
        }

        // 检查匹配结果数量是否少于阈值
        if (originalResult.getSampleListIds().size() >= helperThreshold) {
            return originalResult;
        }

        log.info("执行人脸识别补救逻辑，原匹配数量: {}, 阈值: {}",
                originalResult.getSampleListIds().size(), helperThreshold);

        // 获取第一个匹配结果
        Long firstResultId = originalResult.getSampleListIds().getFirst();
        FaceSampleEntity faceSample = faceRepository.getFaceSample(firstResultId);

        if (faceSample == null) {
            log.warn("补救逻辑失败：无法找到人脸样本, sampleId: {}", firstResultId);
            return originalResult;
        }

        // 使用人脸样本重新进行搜索
        try {
            SearchFaceRespVo recoveryResult = faceService.searchFace(faceBodyAdapter,
                    String.valueOf(scenicId),
                    faceSample.getFaceUrl(),
                    "人脸补救措施1");

            if (recoveryResult != null && recoveryResult.getSampleListIds() != null &&
                    !recoveryResult.getSampleListIds().isEmpty()) {
                log.info("补救逻辑成功，新匹配数量: {}", recoveryResult.getSampleListIds().size());
                return recoveryResult;
            }
        } catch (Exception e) {
            log.warn("补救逻辑执行失败", e);
        }

        return originalResult;
    }
}
