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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.common.business.enums.SendPropsOrigin;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.framework.dto.ResultResponse;
import com.red.circle.other.app.dto.cmd.activity.WeekStarExchangeCmd;
import com.red.circle.other.infra.common.activity.PropsActivitySendCommon;
import com.red.circle.other.infra.common.activity.send.SendRewardParam;
import com.red.circle.other.infra.database.mongo.entity.game.egg.GameEggStockConfig;
import com.red.circle.other.infra.database.rds.entity.game.GameUserShardsBackpack;
import com.red.circle.other.infra.gateway.lottery.LotteryBackpackGateway;
import com.red.circle.other.inner.endpoint.activity.PropsActivityClient;
import com.red.circle.other.inner.endpoint.material.props.FragmentsBackpackClient;
import com.red.circle.other.inner.endpoint.material.props.api.FragmentsBackpackClientApi;
import com.red.circle.other.inner.enums.activity.PropsActivityTypeEnum;
import com.red.circle.other.inner.model.cmd.material.PrizeDescribe;
import com.red.circle.other.inner.model.dto.activity.props.ActivityPropsGroup;
import com.red.circle.other.inner.model.dto.activity.props.ActivityPropsRule;
import com.red.circle.other.inner.model.dto.activity.props.ActivityResource;
import com.red.circle.other.inner.model.dto.activity.props.ActivityRewardProps;
import com.red.circle.other.inner.model.dto.material.FragmentsBackpackDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 周星碎片兑换执行器.
 *
 * @author pengshigang on 2025/9/19
 */
@Component
@RequiredArgsConstructor
public class WeekStarExchangeExe {

    private final FragmentsBackpackClientApi fragmentsBackpackClientApi;
    private final PropsActivitySendCommon sendPropsManager;
    private final PropsActivityClient propsActivityClient;
    private final FragmentsBackpackClient fragmentsBackpackClient;
    private final LotteryBackpackGateway lotteryBackpackGateway;

    public Long execute(WeekStarExchangeCmd cmd) {

        // 1. 校验碎片背包
        List<FragmentsBackpackDTO> backpackList = fragmentsBackpackClientApi
                .listByUserIdByFragmentsIds(cmd.getUserId(), Set.of(cmd.getFragmentsId()))
                .getBody();

        ResponseAssert.notEmpty(CommonErrorCode.DATA_ERROR, backpackList);

        FragmentsBackpackDTO backpack = backpackList.get(0);
        if (backpack.getQuantity() == null || backpack.getQuantity() <= 0) {
          throw new RuntimeException("Insufficient amount of debris.");
        }

      ActivityPropsRule activityPropsRule = propsActivityClient.getByRuleId(cmd.getPropsGroupId()).getBody();
      if (activityPropsRule == null) {
        throw new RuntimeException("activityPropsRule is null.");
      }

      JSONObject obj = JSON.parseObject(activityPropsRule.getJsonData());
      Integer needFragments = obj.getInteger("need_fragments");
      if (needFragments == null ||  needFragments <= 0) {
        throw new RuntimeException("needFragments is null or needFragments <= 0.");
      }
      if (backpack.getQuantity() < needFragments) {
        throw new RuntimeException("Insufficient amount of debris.");
      }

      // 校验配置
      ActivityPropsGroup body = propsActivityClient.getActivityPropsGroup(cmd.getReqSysOrigin().getOrigin(), activityPropsRule.getResourceGroupId()).getBody();
      if (body == null || body.getActivityRewardProps().isEmpty()) {
        throw new RuntimeException("ActivityPropsGroup is null.");
      }

      List<ActivityRewardProps> activityRewardProps = body.getActivityRewardProps();
      ActivityRewardProps rewardProps = activityRewardProps.get(0);

      // 2. 扣除碎片
      fragmentsBackpackClientApi.decrFragments(
              cmd.getUserId(),
              Set.of(cmd.getFragmentsId()),
              needFragments
      );

      // 记录碎片扣除
      String bizNo = "exchange:" + IdWorker.getTimeId();
      lotteryBackpackGateway.recordFragmentDeduct(cmd.getUserId(), needFragments, "exchange", bizNo);

      // 发送奖品
      sendPropsManager.sendGroup(SendRewardParam.builder()
            .acceptUserId(cmd.getUserId())
            .origin(SendPropsOrigin.EGG)
            .sysOrigin(SysOriginPlatformEnum.valueOf(cmd.getReqSysOrigin().getOrigin()))
            .trackId(cmd.getPropsGroupId())
            .build(),
        getPrizeDescribes(rewardProps));

        return 1L; // 返回兑换数量
    }

  private List<PrizeDescribe> getPrizeDescribes(ActivityRewardProps rewardProps) {

    PrizeDescribe prize = new PrizeDescribe()
        .setTrackId(rewardProps.getId())
        .setType(rewardProps.getType())
        .setDetailType(rewardProps.getDetailType())
        .setContent(rewardProps.getContent())
        .setQuantity(rewardProps.getQuantity());
    return List.of(prize);
  }

  public List<ActivityResource> listActivityResource(SysOriginPlatformEnum sysOrigin, PropsActivityTypeEnum propsActivityTypeEnum) {
    return propsActivityClient.listActivityResource(sysOrigin, propsActivityTypeEnum).getBody();
  }

  public List<FragmentsBackpackDTO> listFragmentsByUserId(Long userId, Set<Long> fragmentsIds) {
    return fragmentsBackpackClient.listByUserIdByFragmentsIds(userId, fragmentsIds).getBody();
  }
}
