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

import com.google.common.collect.Lists;

import com.red.circle.other.app.dto.clientobject.user.user.UserImCountCO;
import com.red.circle.other.app.dto.cmd.user.user.UserImCountCmd;
import com.red.circle.other.infra.database.cache.service.other.EnumConfigCacheService;
import com.red.circle.other.infra.database.cache.service.user.CacheEnumConfigManagerService;
import com.red.circle.other.infra.database.rds.entity.user.user.ImCount;
import com.red.circle.other.infra.database.rds.enums.OtherConfigEnum;
import com.red.circle.other.infra.database.rds.service.user.user.ImCountService;
import com.red.circle.other.inner.model.dto.sys.EnumConfigDTO;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户点亮爱心
 *
 * @author zongpubin on 2023/11/16
 */

@Component
@AllArgsConstructor
public class UserImCountQueryExe {

  private final ImCountService imCountService;

  private final CacheEnumConfigManagerService cacheEnumConfigManagerService;

  private final EnumConfigCacheService enumConfigCacheService;

  public UserImCountCO execute(UserImCountCmd cmd) {

    List<String> loves = Optional.ofNullable(
            enumConfigCacheService.getByCode(
                OtherConfigEnum.USER_CP_LOVE_NUMBER.getKey(), cmd.getReqSysOrigin().getOrigin()))
        .map(data -> Arrays.asList(((EnumConfigDTO) data).getVal().split(","))).orElse(Lists.newArrayList());

    Long minLove =
        Long.valueOf(loves.get(0)) < Long.valueOf(loves.get(1)) ? Long.valueOf(loves.get(0))
            : Long.valueOf(loves.get(1));
    Long maxLove =
        Long.valueOf(loves.get(0)) < Long.valueOf(loves.get(1)) ? Long.valueOf(loves.get(1))
            : Long.valueOf(loves.get(0));

    ImCount imCount = imCountService.getByUserIds(cmd.getReqUserId(), cmd.getAcceptUserId(),
        cmd.getReqSysOrigin().getOrigin());

    //  接收信息用户，发送im统计信息
    ImCount acceptUserImCount = imCountService.getByUserIds(cmd.getAcceptUserId(),
        cmd.getReqUserId(),
        cmd.getReqSysOrigin().getOrigin());

    if (Objects.isNull(imCount) || Objects.isNull(acceptUserImCount)) {
      return UserImCountCO.builder()
          .messageCount(0L)
          .lightLove(Boolean.FALSE)
          .minLove(minLove)
          .maxLove(maxLove)
          .build();
    }

    return UserImCountCO.builder()
        .messageCount(imCount.getMessageCount() >= acceptUserImCount.getMessageCount()
            ? acceptUserImCount.getMessageCount() : imCount.getMessageCount())
        .lightLove(imCount.getLightLove())
        .minLove(minLove)
        .maxLove(maxLove)
        .build();
  }
}
