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

import com.red.circle.common.business.dto.cmd.UserIdCmd;
import com.red.circle.other.infra.utils.ZonedDateTimeUtils;
import com.red.circle.tool.core.date.DateUtils;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.user.relation.cp.CpUserProfileCO;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.cache.service.user.UserCpValueCacheService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.enums.user.UserCpLevelEnum;

import java.time.ZoneId;
import java.util.Optional;

import com.red.circle.tool.core.date.LocalDateTimeUtils;
import com.red.circle.tool.core.date.ZonedId;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户cp对象获取.
 *
 * @author pengliang on 2021/4/14
 */
@Component
@RequiredArgsConstructor
public class UserCpRelationQryExe {

  private final UserProfileGateway userProfileGateway;
  private final CpRelationshipService cpRelationshipService;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final UserCpValueCacheService userCpValueCacheService;

  public CpUserProfileCO execute(UserIdCmd cmd) {
    return Optional.ofNullable(cpRelationshipService.getByUserId(cmd.getReqUserId(), cmd.getUserId()))
        .map(cpRelationship -> new CpUserProfileCO()
            .setUserProfile(getUserProfile(cpRelationship.getCpUserId()))
            .setDays(DateUtils.toDurationDays(cpRelationship.getCreateTime(), DateUtils.now()))
            .setFirstDay(cpRelationship.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString())
        )
        .orElse(null);
  }

  private UserProfileDTO getUserProfile(Long cpUserId) {
    return userProfileAppConvertor.toUserProfileDTO(userProfileGateway
        .getByUserId(cpUserId));
  }

  private UserCpLevelEnum getLevel(Long userId1, Long userId2) {

    Long val = userCpValueCacheService.getValue(userId1, userId2);
    if (val > 350000) {
      return UserCpLevelEnum.HONOR_CP;
    }
    if (val > 200000) {
      return UserCpLevelEnum.TORRID_CP;
    }
    if (val > 100000) {
      return UserCpLevelEnum.SINCERE_CP;
    }
    if (val > 50000) {
      return UserCpLevelEnum.SWEET_CP;
    }
    return UserCpLevelEnum.LOVE_CP;
  }


}
