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

import com.ycwl.basic.constant.FreeStatus;
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.mapper.SourceMapper;
import com.ycwl.basic.model.pc.face.entity.FaceEntity;
import com.ycwl.basic.model.pc.source.entity.MemberSourceEntity;
import com.ycwl.basic.model.pc.source.entity.SourceEntity;
import com.ycwl.basic.repository.DeviceRepository;
import com.ycwl.basic.service.pc.helper.ScenicConfigFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 源文件关联处理器
 * 负责处理人脸匹配后的源文件关联逻辑
 *
 * @author longbinbin
 * @date 2025-01-31
 */
@Slf4j
@Component
public class SourceRelationProcessor {

    @Autowired
    private SourceMapper sourceMapper;

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private ScenicConfigFacade scenicConfigFacade;

    /**
     * 处理源文件关联逻辑
     * 根据匹配的样本ID创建MemberSourceEntity列表
     *
     * @param sampleListIds 匹配的样本ID列表
     * @param face          人脸实体
     * @return MemberSourceEntity列表
     */
    public List<MemberSourceEntity> processMemberSources(List<Long> sampleListIds, FaceEntity face) {
        if (sampleListIds == null || sampleListIds.isEmpty()) {
            return Collections.emptyList();
        }

        List<SourceEntity> sourceEntities = sourceMapper.listBySampleIds(sampleListIds);
        if (sourceEntities.isEmpty()) {
            return Collections.emptyList();
        }

        // 按设备分组并应用限制
        List<SourceEntity> filteredSourceEntities = sourceEntities.stream()
                .sorted(Comparator.comparing(SourceEntity::getCreateTime).reversed())
                .collect(Collectors.groupingBy(SourceEntity::getDeviceId))
                .entrySet()
                .stream().flatMap(entry -> {
                    DeviceConfigManager configManager = deviceRepository.getDeviceConfigManager(entry.getKey());
                    if (configManager.getInteger("limit_video", 0) > 0) {
                        // 优先保留所有图片，然后限制视频数量
                        return Stream.concat(
                                entry.getValue().stream().filter(item -> SourceType.isImage(item.getType())),
                                entry.getValue().stream().filter(item -> SourceType.isVideo(item.getType()))
                                        .limit(Math.min(entry.getValue().size(), configManager.getInteger("limit_video", 0)))
                        );
                    }
                    return entry.getValue().stream();
                }).toList();

        // 创建MemberSourceEntity列表
        return filteredSourceEntities.stream().map(sourceEntity -> {
            DeviceConfigManager deviceConfig = deviceRepository.getDeviceConfigManager(sourceEntity.getDeviceId());
            MemberSourceEntity memberSourceEntity = new MemberSourceEntity();
            memberSourceEntity.setScenicId(face.getScenicId());
            memberSourceEntity.setFaceId(face.getId());
            memberSourceEntity.setMemberId(face.getMemberId());
            memberSourceEntity.setSourceId(sourceEntity.getId());
            memberSourceEntity.setType(sourceEntity.getType());

            // 设置免费状态 - 默认收费
            memberSourceEntity.setIsFree(FreeStatus.PAID.getCode());

            if (deviceConfig != null) {
                // 视频类型检查
                if (SourceType.isVideo(sourceEntity.getType())) {
                    if (Integer.valueOf(1).equals(deviceConfig.getInteger("video_free"))) {
                        memberSourceEntity.setIsFree(FreeStatus.FREE.getCode());
                    }
                }
                // 图片类型检查
                else if (SourceType.isImage(sourceEntity.getType())) {
                    if (Integer.valueOf(1).equals(deviceConfig.getInteger("image_free"))) {
                        memberSourceEntity.setIsFree(FreeStatus.FREE.getCode());
                    }
                }
            }

            return memberSourceEntity;
        }).collect(Collectors.toList());
    }

    /**
     * 处理免费源文件逻辑
     * 根据景区配置和是否新用户决定哪些照片可以免费
     *
     * @param memberSourceEntityList 源文件关联列表
     * @param scenicId               景区ID
     * @param isNew                  是否新用户
     * @return 免费的源文件ID列表
     */
    public List<Long> processFreeSourceLogic(List<MemberSourceEntity> memberSourceEntityList,
                                             Long scenicId,
                                             boolean isNew) {
        List<Long> freeSourceIds = new ArrayList<>();

        if (memberSourceEntityList.isEmpty()) {
            return freeSourceIds;
        }

        if (isNew) {
            // 新用户送照片逻辑
            List<MemberSourceEntity> photoSource = memberSourceEntityList.stream()
                    .filter(item -> FreeStatus.isPaid(item.getIsFree()))  // 只考虑收费的
                    .filter(item -> SourceType.isImage(item.getType()))  // 只考虑照片类型
                    .toList();

            Integer photoFreeNum = scenicConfigFacade.getPhotoFreeNum(scenicId);
            if (photoFreeNum != null && photoFreeNum > 0) {

                int freePhotoCount = Math.min(photoFreeNum, photoSource.size());
                freeSourceIds.addAll(photoSource.stream()
                        .limit(freePhotoCount)
                        .map(MemberSourceEntity::getSourceId)
                        .toList());

                log.debug("新用户免费照片逻辑：配置免费数量 {}, 实际可用 {}, 赠送 {} 张",
                        photoFreeNum, photoSource.size(), freePhotoCount);
            }
        }

        return freeSourceIds;
    }
}
