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

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import com.google.common.collect.Maps;
import com.red.circle.common.business.enums.DynamicMessageEnum;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.app.dto.clientobject.dynamic.DynamicMessageListCO;
import com.red.circle.other.app.dto.clientobject.dynamic.MessageItemCO;
import com.red.circle.other.app.dto.cmd.dynamic.DynamicLimitCmd;
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.rds.entity.dynamic.DynamicComment;
import com.red.circle.other.infra.database.rds.entity.dynamic.DynamicContent;
import com.red.circle.other.infra.database.rds.entity.dynamic.DynamicMessage;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicCommentService;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicContentService;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicMessageService;
import com.red.circle.tool.core.collection.CollectionUtils;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 动态-我的消息列表.
 * </p>
 *
 * @author pengshigang
 * @since 2022-04-13
 */
@Component
@RequiredArgsConstructor
public class DynamicMessageQryExe {

  private final UserProfileGateway userProfileGateway;
  private final DynamicContentService dynamicContentService;
  private final DynamicMessageService dynamicMessageService;
  private final DynamicCommentService dynamicCommentService;


  public PageResult<DynamicMessageListCO> execute(DynamicLimitCmd cmd) {

    PageResult<DynamicMessage> messages = getMessages(cmd);
    if (CollectionUtils.isEmpty(messages.getRecords())) {
      return PageResult.newPageResult(0);
    }

    Map<Long, UserProfile> userMap = userProfileGateway.mapByUserIds(getUserIds(messages));
    Map<Long, DynamicContent> contentMap = getContentMap(messages);
    Map<Long, DynamicComment> commentMap = getCommentMap(messages);

    return messages.convert(message -> {

      DynamicContent dynamicContent = contentMap.get(message.getDynamicContentId());

      DynamicMessageListCO messageCO = new DynamicMessageListCO();
      messageCO.setId(message.getId());
      messageCO.setType(message.getType());
      messageCO.setUserId(message.getCreateUser());
      messageCO.setCreateTime(message.getCreateTime());
      messageCO.setDynamicId(message.getDynamicContentId());
      messageCO.setDynamicContent(dynamicContent == null ? "" : dynamicContent.getContent());
      
      // 批量查询评论ID对应的 rootCommentId
      DynamicComment comment = commentMap.get(message.getDynamicCommentId());
      if (comment != null) {
        messageCO.setRootCommentId(comment.getRootCommentId() == null ? comment.getId() : comment.getRootCommentId());
      }
      
      // 处理messageContent 和 giftCount
      parseMessageContent(messageCO, message);

      if (DynamicMessageEnum.isReportRelated(message.getType())) {
        return messageCO;
      }

      UserProfile user = userMap.get(message.getCreateUser());
      if (Objects.nonNull(user)) {
        messageCO.setUserAvatar(user.getUserAvatar());
        messageCO.setUserNickname(user.getUserNickname());
        messageCO.setUserSex(user.getUserSex());
        messageCO.setAge(user.getAge());
      }
      return messageCO;

    });

  }

    private void parseMessageContent(DynamicMessageListCO co, DynamicMessage message) {
        if (message == null || co == null) {
            return;
        }
        if (StringUtils.isBlank(message.getContent())) {
          return;
        }

        if (!DynamicMessageEnum.DYNAMIC_GIFT.name().equals(message.getType())) {
            co.setMessageContent(message.getContent());
            return;
        }
        try {
          MessageItemCO messageItemCO = JSON.parseObject(message.getContent(), MessageItemCO.class);
          co.setMessageContent(messageItemCO.getMessageContent());
          co.setGiftCount(messageItemCO.getGiftCount());
        } catch (Exception ignored) {
        }
    }

  private Map<Long, DynamicContent> getContentMap(PageResult<DynamicMessage> messages) {
    return dynamicContentService
        .mapByIds(messages.getRecords().stream().map(DynamicMessage::getDynamicContentId).collect(
            Collectors.toSet()));
  }

  private Map<Long, DynamicComment> getCommentMap(PageResult<DynamicMessage> messages) {
    Set<Long> commentIds = messages.getRecords().stream()
        .map(DynamicMessage::getDynamicCommentId)
        .filter(Objects::nonNull)
        .collect(Collectors.toSet());
    
    if (CollectionUtils.isEmpty(commentIds)) {
      return Maps.newHashMap();
    }
    
    return dynamicCommentService.mapByIds(commentIds);
  }

  private PageResult<DynamicMessage> getMessages(DynamicLimitCmd cmd) {
    return dynamicMessageService.pageByTimeDesc(cmd.getPageReq(), cmd.getReqUserId(), cmd.getDynamicMessageEnums());
  }

  private Set<Long> getUserIds(PageResult<DynamicMessage> messages) {

    return messages.getRecords().stream().map(DynamicMessage::getCreateUser)
        .filter(Objects::nonNull).collect(Collectors.toSet());
  }


}
