package com.red.circle.other.app.command.rocket;

import com.red.circle.other.app.convertor.RocketConvertor;
import com.red.circle.other.app.dto.clientobject.RocketContributorCO;
import com.red.circle.other.app.dto.clientobject.RocketStatusCO;
import com.red.circle.other.app.dto.cmd.RocketStatusQueryCmd;
import com.red.circle.other.domain.rocket.RocketContributor;
import com.red.circle.other.domain.rocket.RocketLevel;
import com.red.circle.other.domain.rocket.RocketStatus;
import com.red.circle.other.domain.rocket.RocketStatusEnum;
import com.red.circle.other.infra.gateway.RocketStatusGatewayImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 火箭状态查询执行器
 *
 * @author system
 * @date 2025-01-15
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RocketStatusQryExe {

    private final RocketStatusGatewayImpl rocketStatusGateway;

    /**
     * Top排行显示数量
     */
    private static final int TOP_DISPLAY_COUNT = 10;

    /**
     * 执行查询（只返回Top10贡献者）
     */
    public RocketStatusCO execute(RocketStatusQueryCmd cmd) {
        // 1. 查询火箭状态（性能优化）
        String today = LocalDate.now().toString();
        RocketStatus rocketStatus = rocketStatusGateway
                .findByRoomIdAndDateWithoutContributors(cmd.getRoomId(), today);
        
        if (rocketStatus == null) {
            // 返回初始状态
            return buildInitialStatus(cmd.getRoomId());
        }

        // 2. 使用转换器转换为CO
        RocketStatusCO statusCO = RocketConvertor.toStatusCO(rocketStatus);

        // 3. 填充当前用户相关信息
        if (cmd.getReqUserId() != null) {
//            fillUserInfo(statusCO, rocketStatus, cmd.getReqUserId());
        }

        return statusCO;
    }

    /**
     * 查询完整状态（包含所有贡献者）
     * 用于：需要完整数据的特殊场景
     */
    public RocketStatusCO executeWithFullContributors(RocketStatusQueryCmd cmd) {
        String today = LocalDate.now().toString();
        RocketStatus rocketStatus = rocketStatusGateway.findByRoomIdAndDate(cmd.getRoomId(), today);
        
        if (rocketStatus == null) {
            return buildInitialStatus(cmd.getRoomId());
        }

        RocketStatusCO statusCO = RocketConvertor.toStatusCO(rocketStatus);

        if (cmd.getReqUserId() != null) {
            fillUserInfo(statusCO, rocketStatus, cmd.getReqUserId());
        }

        return statusCO;
    }

    /**
     * 构建初始状态
     */
    private RocketStatusCO buildInitialStatus(Long roomId) {
        RocketStatusCO statusCO = new RocketStatusCO();
        statusCO.setRoomId(String.valueOf(roomId));
        statusCO.setDate(LocalDate.now().toString());
        statusCO.setLevel(1);
        statusCO.setLevelName("一级火箭");
        statusCO.setCurrentEnergy(0L);
        statusCO.setMaxEnergy(150000L);
        statusCO.setEnergyPercent(BigDecimal.ZERO);
        statusCO.setStatus(RocketStatusEnum.CHARGING.name());
        statusCO.setStatusDesc("充能中");
        statusCO.setTopContributors(new ArrayList<>());
        statusCO.setTotalContributors(0);
        statusCO.setClaimCount(0);
        statusCO.setCanClaim(false);
        statusCO.setHasClaimed(false);
        return statusCO;
    }

    /**
     * 填充当前用户信息
     */
    private void fillUserInfo(RocketStatusCO statusCO, RocketStatus rocketStatus, Long userId) {
        // 判断是否可领取
        statusCO.setCanClaim(rocketStatus.canClaim());
        
        // TODO: 查询是否已领取 (需要查询MySQL rocket_reward_claim_log)
        statusCO.setHasClaimed(false);

        // 查找当前用户贡献
        // 注意：如果使用了Top查询，这里可能查不到（用户不在Top10内）
        // 可以考虑单独查询该用户的贡献数据
        if (rocketStatus.getContributors() != null) {
            rocketStatus.getContributors().stream()
                    .filter(c -> c.getUserId().equals(userId))
                    .findFirst()
                    .ifPresent(contributor -> {
                        statusCO.setMyContribution(contributor.getEnergy());
                        statusCO.setMyContributionRate(contributor.getContributionRate());
                    });
        }
        
        // 如果用户不在Top10内，可以单独查询（可选优化）
        if (statusCO.getMyContribution() == null) {
            // TODO: 使用聚合查询单独获取该用户的贡献数据
            statusCO.setMyContribution(0L);
            statusCO.setMyContributionRate(BigDecimal.ZERO);
        }
    }
}
