package com.red.circle.other.app.listener.gift.strategy;

import com.alibaba.fastjson.JSON;
import com.red.circle.mq.business.model.event.gift.OfflineProcessGiftEvent;
import com.red.circle.other.app.command.rocket.RocketEnergyAddCmdExe;
import com.red.circle.other.app.common.gift.GameLuckyGiftCommon;
import com.red.circle.other.app.dto.cmd.RocketEnergyAddCmd;
import com.red.circle.other.infra.database.cache.service.other.EnumConfigCacheService;
import com.red.circle.other.infra.database.cache.service.other.RoomManagerCacheService;
import com.red.circle.other.infra.database.mongo.entity.gift.GiftAcceptUser;
import com.red.circle.other.infra.database.mongo.entity.gift.GiftGiveRunningWater;
import com.red.circle.other.infra.database.mongo.entity.gift.GiftValue;
import com.red.circle.other.infra.database.mongo.service.gift.GiftGiveRunningWaterService;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.other.inner.enums.config.EnumConfigKey;
import com.red.circle.other.inner.enums.material.GiftCurrencyType;
import com.red.circle.other.inner.enums.material.GiftTabEnum;
import com.red.circle.tool.core.text.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/**
 * 火箭统计相关 - 礼物送出时增加火箭能量
 *
 * @author system
 * @date 2025-01-15
 */
@Slf4j
@Service("ROCKET_COUNT_LISTENER")
@RequiredArgsConstructor
public class GiftSendRocketListener implements GiftStrategy {

    private final RocketEnergyAddCmdExe rocketEnergyAddCmdExe;
    private final GiftGiveRunningWaterService giftGiveRunningWaterService;
    private final GameLuckyGiftCommon gameLuckyGiftCommon;
    private final EnumConfigCacheService enumConfigCacheService;

    @Override
    public void processor(OfflineProcessGiftEvent event) {
        log.info("【火箭能量增加】接收礼物事件: {}", JSON.toJSONString(event));

        // 1. 查询礼物流水
        GiftGiveRunningWater runningWater = giftGiveRunningWaterService.getByIdPrimary(
                event.getRunningWaterId());

        if (Objects.isNull(runningWater)) {
            log.warn("【火箭能量增加】没有找到流水信息，忽略处理");
            return;
        }

        // 7. 只处理在房间内送出的礼物
        String originId = runningWater.getOriginId();
        if (originId == null || !originId.matches("\\d+")) {
            log.debug("【火箭能量增加】非房间场景，跳过处理");
            return;
        }

        // 跳过白名单用户
//        String rocketRoomList = enumConfigCacheService.getValue(
//                EnumConfigKey.ROCKET_ROOM_LIST, runningWater.getSysOrigin());
//        if (StringUtils.isBlank(rocketRoomList) || !rocketRoomList.contains(originId)) {
//            return;
//        }

        // 2. 只处理金币礼物
        if (!GiftCurrencyType.GOLD.eq(runningWater.getGiftValue().getCurrencyType())) {
            log.debug("【火箭能量增加】非金币礼物，跳过处理");
            return;
        }

        giftGiveRunningWaterService.addLog(runningWater.getId(), "开始：火箭能量增加");

        try {
            // 3. 获取礼物信息
            GiftValue giftValue = runningWater.getGiftValue();

            // 4. 判断是否为幸运礼物
            boolean isLuckyGift = isLuckyGift(giftValue);

            // 5. 获取幸运礼物比例
            BigDecimal luckyGiftRatio = BigDecimal.ZERO;
            if (isLuckyGift) {
                luckyGiftRatio = gameLuckyGiftCommon.getLuckyGiftShareRatio(runningWater.getSysOrigin());
                log.info("【火箭能量增加】幸运礼物比例：{}", luckyGiftRatio);
            }

            // 6. 计算实际金币价值（考虑幸运礼物加成）
            Long actualGoldValue = getActualAmount(isLuckyGift, giftValue.getActualAmount(), luckyGiftRatio);

            Long roomId = Long.parseLong(originId);

            // 8. 获取送礼用户信息
            Long userId = runningWater.getUserId();

            // 9. 构建命令并执行
            RocketEnergyAddCmd cmd = new RocketEnergyAddCmd();
            cmd.setRoomId(roomId);
            cmd.setUserId(userId);
            cmd.setGiftGoldValue(actualGoldValue);
            cmd.setIsLucky(isLuckyGift);

            rocketEnergyAddCmdExe.execute(cmd);

            log.info("【火箭能量增加】处理成功: roomId={}, userId={}, goldValue={}, isLucky={}",
                    roomId, userId, actualGoldValue, isLuckyGift);

        } catch (Exception e) {
            log.error("【火箭能量增加】处理异常: runningWaterId={}", runningWater.getId(), e);
        } finally {
            giftGiveRunningWaterService.addLog(runningWater.getId(), "结束：火箭能量增加");
        }
    }

    /**
     * 判断是否为幸运礼物
     */
    private boolean isLuckyGift(GiftValue giftValue) {
        return giftValue.getGiftType() != null &&
                giftValue.getGiftType().contains(GiftTabEnum.LUCKY_GIFT.name());
    }

    /**
     * 计算实际金额（考虑幸运礼物加成）
     */
    private Long getActualAmount(boolean isLuckyGift, BigDecimal amount, BigDecimal luckyGiftRatio) {
        if (isLuckyGift && luckyGiftRatio != null && luckyGiftRatio.compareTo(BigDecimal.ZERO) > 0) {
            // 幸运礼物按比例计算
            return amount.multiply(luckyGiftRatio)
                    .setScale(0, RoundingMode.DOWN)
                    .longValue();
        }
        return amount.longValue();
    }
}
