package com.red.circle.other.app.command.sys.query;

import com.red.circle.common.business.dto.cmd.app.AppIdLongCmd;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.sys.SysActivityUserCountCO;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.mongo.entity.sys.SysActivityCount;
import com.red.circle.other.infra.database.mongo.service.sys.SysActivityCountService;
import com.red.circle.other.inner.model.dto.sys.SysActivityCountType;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.num.NumUtils;
import java.util.Map;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 系统活动-用户贡献.
 *
 * @author pengliang on 2022/8/16
 */
@Component
@RequiredArgsConstructor
public class SysActivityUserCountQryExe {

  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final SysActivityCountService sysActivityCountService;

  public SysActivityUserCountCO execute(AppIdLongCmd cmd) {

    Map<SysActivityCountType, SysActivityCount> sysActivityCounts = sysActivityCountService.getUserCount(
        cmd.getId(),
        cmd.getReqUserId());

    UserProfileDTO userProfile = userProfileAppConvertor.toUserProfileDTO(
        userProfileGateway.getByUserId(cmd.getReqUserId())
    );

    if (CollectionUtils.isEmpty(sysActivityCounts)) {
      return new SysActivityUserCountCO()
          .setUserProfile(userProfile)
          .setButOneQuantity(0L)
          .setButOneQuantityFormat("0")
          .setButTwoQuantity(0L)
          .setButTwoQuantityFormat("0");
    }

    SysActivityCount wealth = sysActivityCounts.get(SysActivityCountType.WEALTH);
    SysActivityCount charm = sysActivityCounts.get(SysActivityCountType.CHARM);
    return new SysActivityUserCountCO()
        .setUserProfile(userProfile)
        .setButOneQuantity(Optional.ofNullable(wealth)
            .map(SysActivityCount::getQuantity)
            .orElse(0L))
        .setButOneQuantityFormat(Optional.ofNullable(wealth)
            .map(count -> NumUtils.formatLong(count.getQuantity()))
            .orElse("0"))
        .setButTwoQuantity(Optional.ofNullable(charm)
            .map(SysActivityCount::getQuantity)
            .orElse(0L))
        .setButTwoQuantityFormat(Optional.ofNullable(charm)
            .map(count -> NumUtils.formatLong(count.getQuantity()))
            .orElse("0"));
  }
}
