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

import com.ycwl.basic.constant.FreeStatus;
import com.ycwl.basic.model.pc.puzzle.entity.MemberPuzzleEntity;
import com.ycwl.basic.puzzle.mapper.MemberPuzzleMapper;
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;

/**
 * 拼图关联记录处理器
 * 负责创建和管理member_puzzle关联记录
 */
@Slf4j
@Component
public class PuzzleRelationProcessor {

    @Autowired
    private MemberPuzzleMapper memberPuzzleMapper;

    @Autowired
    private ScenicConfigFacade scenicConfigFacade;

    /**
     * 创建拼图关联记录
     *
     * @param memberId 会员ID
     * @param scenicId 景区ID
     * @param faceId   人脸ID
     * @param recordId 拼图生成记录ID
     */
    public void createPuzzleRelation(Long memberId, Long scenicId, Long faceId, Long recordId) {
        if (faceId == null || recordId == null) {
            log.warn("创建拼图关联记录失败：faceId或recordId为空, faceId={}, recordId={}", faceId, recordId);
            return;
        }

        MemberPuzzleEntity entity = new MemberPuzzleEntity();
        entity.setMemberId(memberId);
        entity.setScenicId(scenicId);
        entity.setFaceId(faceId);
        entity.setRecordId(recordId);
        entity.setIsBuy(0);

        // 处理免费逻辑
        Integer isFree = processFreeLogic(scenicId, faceId);
        entity.setIsFree(isFree);

        try {
            memberPuzzleMapper.addRelation(entity);
            log.debug("创建拼图关联记录成功: faceId={}, recordId={}, isFree={}", faceId, recordId, isFree);
        } catch (Exception e) {
            log.error("创建拼图关联记录失败: faceId={}, recordId={}", faceId, recordId, e);
        }
    }

    /**
     * 处理免费逻辑
     * 根据景区配置的puzzle_free_num决定是否免费
     *
     * @param scenicId 景区ID
     * @param faceId   人脸ID
     * @return 免费状态码
     */
    private Integer processFreeLogic(Long scenicId, Long faceId) {
        Integer puzzleFreeNum = scenicConfigFacade.getPuzzleFreeNum(scenicId);

        if (puzzleFreeNum == null || puzzleFreeNum <= 0) {
            return FreeStatus.PAID.getCode();
        }

        // 统计已有的免费拼图数量
        int existingFreeCount = memberPuzzleMapper.countFreeByFaceId(faceId);

        if (existingFreeCount < puzzleFreeNum) {
            log.debug("免费拼图逻辑: scenicId={}, faceId={}, 配置免费数量={}, 已免费={}, 本次免费",
                    scenicId, faceId, puzzleFreeNum, existingFreeCount);
            return FreeStatus.FREE.getCode();
        }

        return FreeStatus.PAID.getCode();
    }
}
