package com.red.circle.other.adapter.app.activity.room;

import cn.hutool.core.util.StrUtil;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.framework.web.controller.BaseController;
import com.red.circle.other.app.dto.clientobject.activity.UserCharmWealthContributeCO;
import com.red.circle.other.app.dto.clientobject.activity.UserRankCO;
import com.red.circle.other.app.dto.clientobject.activity.WeekKingQueenGroupVO;
import com.red.circle.other.app.dto.clientobject.activity.WeekKingQueenHistoryVO;
import com.red.circle.other.app.dto.clientobject.sys.ActivityConfigVO;
import com.red.circle.other.app.dto.cmd.activity.WeekKingQueenRankingQueryCmd;
import com.red.circle.other.app.service.activity.WeekKingQueenService;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.database.mongo.entity.activity.WeekKingQueenCount;
import com.red.circle.other.infra.database.mongo.service.activity.WeekKingQueenCountService;
import com.red.circle.other.inner.enums.activity.KingQueenType;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 国王王后.
 *
 * @author lisizhe on 2023/9/25
 * @eo.api-type http
 * @eo.groupName 活动服务.国王王后
 * @eo.path /activity/king-queen
 */
@RequestMapping("/activity/king-queen")
@RestController
@RequiredArgsConstructor
public class WeekKingQueenController extends BaseController {

  private final WeekKingQueenService weekKingQueenService;
  private final WeekKingQueenCountService weekKingQueenCountService;
  private final UserProfileGateway userProfileGateway;
  private static final DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
  private static final  DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

  /**
   * 排行榜.
   *
   * @eo.name 排行榜
   * @eo.url /ranking
   * @eo.method get
   * @eo.request-type formdata
   */
  @GetMapping("/ranking")
  public PageResult<UserRankCO> listRanking(@Validated WeekKingQueenRankingQueryCmd cmd) {
    return weekKingQueenService.listRanking(cmd);
  }

  /**
   * 历史top1
   */
  @GetMapping("/history")
  public List<WeekKingQueenGroupVO> history(AppExtCommand cmd) {

    List<WeekKingQueenCount> top1List = weekKingQueenCountService.listLastThreeMonthsTop1(cmd.getReqSysOrigin().getOrigin());
    Set<Long> userIds = top1List.stream().map(WeekKingQueenCount::getUserId).collect(Collectors.toSet());
    Map<Long, UserProfile> profileMap = userProfileGateway.mapByUserIds(userIds);

    // 先按 group 分组
    Map<String, List<WeekKingQueenCount>> groupMap = top1List.stream()
        .collect(Collectors.groupingBy(WeekKingQueenCount::getGroup));

    // 转成最终返回的结构
    List<WeekKingQueenGroupVO> result = new ArrayList<>();
    for (Map.Entry<String, List<WeekKingQueenCount>> entry : groupMap.entrySet()) {
      WeekKingQueenGroupVO vo = new WeekKingQueenGroupVO();

      // 转换 group 格式
      vo.setGroup(LocalDate.parse(entry.getKey(), oldFormatter).format(newFormatter));

      // 遍历同一周的数据，把 WEALTH / CHARM 分开
      for (WeekKingQueenCount e : entry.getValue()) {
        WeekKingQueenHistoryVO historyVO = new WeekKingQueenHistoryVO();
        BeanUtils.copyProperties(e, historyVO);
        historyVO.setGroup(LocalDate.parse(entry.getKey(), oldFormatter).format(newFormatter));

        UserProfile userProfile = profileMap.get(e.getUserId());
        if (userProfile != null) {
          historyVO.setAccount(userProfile.getAccount());
          historyVO.setUserAvatar(userProfile.getUserAvatar());
          historyVO.setUserNickname(userProfile.getUserNickname());
        }

        if (e.getType() == KingQueenType.WEALTH) {
          vo.setWealth(historyVO);
        } else if (e.getType() == KingQueenType.CHARM) {
          vo.setCharm(historyVO);
        }
      }

      result.add(vo);
    }

    // 按 group 排序（可选）
    result.sort(Comparator.comparing(WeekKingQueenGroupVO::getGroup).reversed());

    return result;
  }

  /**
   * 获取有效活动
   */
  @GetMapping("/effective")
  public ActivityConfigVO getEffective(AppExtCommand cmd, @RequestParam(required = false) String templateId) {
    return weekKingQueenService.getEffectiveActivity(cmd, templateId);
  }

  /**
   * 我本周贡献.
   *
   * @eo.name 我本周贡献
   * @eo.url /user-contribute
   * @eo.method get
   * @eo.request-type formdata
   */
  @GetMapping("/user-contribute")
  public UserCharmWealthContributeCO getUserContribute(AppExtCommand cmd, @RequestParam(value = "userId", required = false) String userId) {
    if (StrUtil.isNotBlank(userId)) {
      cmd.setReqUserId(Long.parseLong(userId));
    }
    return weekKingQueenService.getUserContribute(cmd);
  }

  /**
   * 倒计时.
   *
   * @eo.name 倒计时
   * @eo.url /count-down
   * @eo.method get
   * @eo.request-type formdata
   */
  @GetMapping("/count-down")
  public String countDown() {
    return weekKingQueenService.countDown();
  }

}
