package com.red.circle.game.fruit.infrastructure.database.repository.impl;


import com.google.common.collect.Maps;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.game.fruit.application.convertor.GameFruitTaskAppConvertor;
import com.red.circle.game.fruit.application.dto.clientobject.GameFruitTaskAwardConfigCO;
import com.red.circle.game.fruit.infrastructure.database.cache.service.GameFruitTaskCacheService;
import com.red.circle.game.fruit.infrastructure.database.dao.GameFruitTaskAwardConfigDAO;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitTaskAwardConfig;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitUserTaskReceive;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitAwardRecordService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitTaskAwardConfigService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitUserDaysRankingService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitUserTaskReceiveService;
import com.red.circle.game.fruit.inner.enums.GameFruitTaskEnum;
import com.red.circle.game.fruit.inner.model.cmd.GameFruitTaskConfigQryCmd;
import com.red.circle.other.inner.endpoint.activity.PropsActivityClient;
import com.red.circle.other.inner.model.dto.activity.props.ActivityPropsGroup;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 摩天轮游戏任务奖项配置 服务实现类.
 * </p>
 *
 * @author zongpubin on 2023-12-13 17:12
 */
@Service
@RequiredArgsConstructor
public class GameFruitTaskAwardConfigServiceImpl extends
    BaseServiceImpl<GameFruitTaskAwardConfigDAO, GameFruitTaskAwardConfig> implements
    GameFruitTaskAwardConfigService {

  private final GameFruitUserDaysRankingService gameFruitUserDaysRankingService;
  private final PropsActivityClient propsActivityCnfClient;
  private final GameFruitTaskAppConvertor gameFruitTaskAppConvertor;
  private final GameFruitTaskCacheService gameFruitTaskCacheService;
  private final GameFruitAwardRecordService gameFruitAwardRecordService;
  private final GameFruitUserTaskReceiveService gameFruitUserTaskReceiveService;

  @Override
  public PageResult<GameFruitTaskAwardConfig> getGameFruitTaskConfig(
      GameFruitTaskConfigQryCmd query) {
    return query().eq(GameFruitTaskAwardConfig::getBountyId, query.getBountyId())
        .orderByDesc(GameFruitTaskAwardConfig::getCreateTime).page(query.getPageQuery());
  }

  @Override
  public Map<Long, List<GameFruitTaskAwardConfigCO>> mapTaskAwardConfigs(String originSys,
      Long userId) {
    Map<String, Long> taskCompleteMap = Maps.newHashMap();

    List<GameFruitTaskAwardConfig> awardConfigs = query().eq(GameFruitTaskAwardConfig::getSysOrigin,
        originSys).list();
    if (CollectionUtils.isEmpty(awardConfigs)) {
      return Maps.newHashMap();
    }
    Map<Long, ActivityPropsGroup> activityPropsGroupMap = ResponseAssert.requiredSuccess(
        propsActivityCnfClient.mapActivityPropsGroup(originSys,
            awardConfigs.stream().map(GameFruitTaskAwardConfig::getResourceGroupId).collect(
                Collectors.toSet())));

    Map<Long, GameFruitUserTaskReceive> taskReceicedMap = gameFruitUserTaskReceiveService.getByUserIdAndAwardId(
        userId, awardConfigs.stream().map(GameFruitTaskAwardConfig::getId).collect(
            Collectors.toSet()));

    // 每天某项中奖次数
    Long someTimes = Long.valueOf(gameFruitTaskCacheService.getGameFruitTaskAward(userId,
        GameFruitTaskEnum.WINNING_ONE_OF_THE_PRIZES_ONE.name()));
    // 每天披萨或蔬菜中奖次数
    Long pizzaTimes = Long.valueOf(gameFruitTaskCacheService.getGameFruitTaskAward(userId,
        GameFruitTaskEnum.WINNING_ONE_OF_THE_PRIZES_TWO.name()));
    // 每天游戏连赢轮数
    Long userWinRounds = Long.valueOf(gameFruitTaskCacheService.getUserWinRounds(userId));
    // 每周赢的轮数
    Long weekWinRounds = gameFruitAwardRecordService.countWeekWinRounds(userId);
    // 盈利金币数
    Long weekWinEarning = gameFruitUserDaysRankingService.countWeekEarning(userId);
    // 一周玩游戏天数
    Long weekPlayDays = gameFruitUserDaysRankingService.countWeekPlayDays(userId);
    // 周争霸赛
    Long weekCompetition = Long.valueOf(gameFruitTaskCacheService.getGameFruitTaskAward(userId,
        GameFruitTaskEnum.WEEK_COMPETITION.name()));

    taskCompleteMap.put(GameFruitTaskEnum.WINNING_ONE_OF_THE_PRIZES_ONE.name(), someTimes);
    taskCompleteMap.put(GameFruitTaskEnum.WINNING_ONE_OF_THE_PRIZES_TWO.name(), pizzaTimes);
    taskCompleteMap.put(GameFruitTaskEnum.NUMBER_OF_WINNING_ROUNDS.name(), userWinRounds);
    taskCompleteMap.put(GameFruitTaskEnum.NUMBER_OF_PROFIT_ROUNDS.name(), weekWinRounds);
    taskCompleteMap.put(GameFruitTaskEnum.NUMBER_OF_PROFIT_COINS.name(), weekWinEarning);
    taskCompleteMap.put(GameFruitTaskEnum.NUMBER_OF_DAYS_WEEK.name(), weekPlayDays);
    taskCompleteMap.put(GameFruitTaskEnum.WEEK_COMPETITION.name(), weekCompetition);

    return gameFruitTaskAppConvertor.toListGameFruitTaskAwardConfigCO(
        awardConfigs).stream().peek(awardConfigCO -> {
      if (Objects.nonNull(awardConfigCO.getAwardPhoto())) {
        awardConfigCO.setAwardPhotos(
            StringUtils.splitAsList(awardConfigCO.getAwardPhoto(), ","));
      }

      ActivityPropsGroup activityPropsGroup = activityPropsGroupMap.get(
          awardConfigCO.getResourceGroupId());

      if (Objects.nonNull(activityPropsGroup) && CollectionUtils.isNotEmpty(
          activityPropsGroup.getActivityRewardProps())) {
        awardConfigCO.setActivityRewardProps(activityPropsGroup.getActivityRewardProps());
      }

      GameFruitUserTaskReceive taskReceive = taskReceicedMap.get(
          awardConfigCO.getId());
      awardConfigCO.setReceived(Objects.nonNull(taskReceive));
      awardConfigCO.setCompletedCount(taskCompleteMap.get(awardConfigCO.getTaskType()));
      if (!Objects.equals(awardConfigCO.getTaskType(),
          GameFruitTaskEnum.WEEK_COMPETITION.name()) &&
          !Objects.equals(awardConfigCO.getTaskType(),
              GameFruitTaskEnum.TASK_COMPLETE_DAY.name()) &&
          !Objects.equals(awardConfigCO.getTaskType(),
              GameFruitTaskEnum.TASK_COMPLETE_WEEK.name())
      ) {
        awardConfigCO.setCompleted(
            taskCompleteMap.get(awardConfigCO.getTaskType()) >= awardConfigCO.getQuantity());
      }

    }).collect(Collectors.groupingBy(GameFruitTaskAwardConfigCO::getBountyId));

  }

  @Override
  public GameFruitTaskAwardConfig getByTaskType(String taskType) {
    return query().eq(GameFruitTaskAwardConfig::getTaskType, taskType).last(PageConstant.LIMIT_ONE)
        .getOne();
  }
}
