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

import com.ycwl.basic.constant.SourceType;
import com.ycwl.basic.integration.common.manager.DeviceConfigManager;
import com.ycwl.basic.integration.common.manager.ScenicConfigManager;
import com.ycwl.basic.model.pc.faceSample.entity.FaceSampleEntity;
import com.ycwl.basic.model.pc.source.entity.MemberSourceEntity;
import com.ycwl.basic.repository.DeviceRepository;
import com.ycwl.basic.repository.FaceRepository;
import com.ycwl.basic.service.pc.helper.ScenicConfigFacade;
import com.ycwl.basic.task.VideoPieceGetter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 视频重切处理器
 * 负责处理视频重切任务的创建逻辑
 *
 * @author longbinbin
 * @date 2025-01-31
 */
@Slf4j
@Component
public class VideoRecreationHandler {

    @Autowired
    private FaceRepository faceRepository;

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private ScenicConfigFacade scenicConfigFacade;

    /**
     * 处理视频重切逻辑
     * 当非新用户且照片数量大于视频数量时，创建视频重切任务
     *
     * @param scenicId               景区ID
     * @param memberSourceEntityList 源文件关联列表
     * @param faceId                 人脸ID
     * @param memberId               会员ID
     * @param sampleListIds          样本ID列表（用于日志）
     * @param isNew                  是否新用户
     */
    public void handleVideoRecreation(Long scenicId,
                                      List<MemberSourceEntity> memberSourceEntityList,
                                      Long faceId,
                                      Long memberId,
                                      List<Long> sampleListIds,
                                      boolean isNew) {
        // 新用户不执行视频重切逻辑
        if (isNew) {
            return;
        }

        // 检查景区是否禁用源视频功能
        if (scenicConfigFacade.isDisableSourceVideo(scenicId)) {
            log.debug("视频重切逻辑跳过：景区禁用了源视频功能");
            return;
        }

        // 统计视频和照片数量
        long videoCount = memberSourceEntityList.stream()
                .filter(item -> SourceType.isVideo(item.getType()))
                .count();
        long photoCount = memberSourceEntityList.stream()
                .filter(item -> SourceType.isImage(item.getType()))
                .count();

        List<FaceSampleEntity> faceSampleList = faceRepository.getFaceSampleList(faceId);
        if (faceSampleList.isEmpty()) {
            log.info("faceId:{} sample list not exist", faceId);
            return;
        }

        // 筛选样本ID
        List<Long> faceSampleIds = faceSampleList.stream()
                .sorted(Comparator.comparing(FaceSampleEntity::getCreateAt).reversed())
                .collect(Collectors.groupingBy(FaceSampleEntity::getDeviceId))
                .entrySet()
                .stream().flatMap(entry -> {
                    DeviceConfigManager configManager = deviceRepository.getDeviceConfigManager(entry.getKey());
                    if (configManager.getInteger("limit_video", 0) > 0) {
                        return entry.getValue().subList(0, Math.min(entry.getValue().size(), configManager.getInteger("limit_video", 0))).stream();
                    }
                    return entry.getValue().stream();
                }).toList()
                .stream().map(FaceSampleEntity::getId).toList();

        log.debug("视频重切逻辑：视频数量 {}, 照片数量 {}", videoCount, photoCount);

        // 只有照片数量大于视频数量时才创建重切任务
        if (photoCount > videoCount) {
            VideoPieceGetter.Task task = new VideoPieceGetter.Task();
            task.faceId = faceId;
            task.faceSampleIds = faceSampleIds;
            task.templateId = null;
            task.memberId = memberId;
            task.callback = () -> {
                log.info("视频重切任务回调: {}", task);
            };

            VideoPieceGetter.addTask(task);
            log.debug("视频重切任务已创建：faceId={}, memberId={}, sampleIds={}",
                    faceId, memberId, sampleListIds.size());
        } else {
            log.debug("视频重切逻辑跳过：照片数量({})未超过视频数量({})", photoCount, videoCount);
        }
    }
}
