package com.izouma.jmrh.service;

import com.izouma.jmrh.domain.*;
import com.izouma.jmrh.dto.MessageDTO;
import com.izouma.jmrh.enums.MessageType;
import com.izouma.jmrh.enums.PostType;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.*;
import com.izouma.jmrh.utils.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
@Slf4j
@AllArgsConstructor
public class MessageService {
    private MessageRepo      messageRepo;
    private ConversationRepo conversationRepo;
    private UserRepo         userRepo;

    public Page<MessageDTO> all(String sessionId, MessageType type, Pageable pageable) {
        if (type != null) {
            return messageRepo.all(sessionId, type, pageable);
        }
        return messageRepo.all(sessionId, pageable);
    }

    public void readAll(Long userId, String sessionId) {
        if (StringUtils.isNotEmpty(sessionId)) {
            messageRepo.readAll(sessionId, userId);
        } else {
            messageRepo.readAll(userId);
        }
    }

    public void send(Long userId, Long toUserId, String sessionId, MessageType type, String content) {
        String lastMessage;
        switch (type) {
            case TEXT:
                lastMessage = content.length() > 20 ? content.substring(0, 20) + "……" : content;
                break;
            case SND:
                lastMessage = "[资源供需]";
                break;
            default:
                lastMessage = "";
        }
        conversationRepo.updateConversation(sessionId, LocalDateTime.now(), lastMessage);
        messageRepo.save(Message.builder()
                .userId(userId)
                .toUserId(toUserId)
                .sessionId(sessionId)
                .type(type)
                .content(content)
                .read(false)
                .build());
    }

    public void sendCommentMsg(Long fromUserId, Long toUserId, Comment comment, Post post) {
        User user = userRepo.findById(fromUserId).orElseThrow(new BusinessException("用户不存在"));
        String sessionId = "comment-" + toUserId;
        conversationRepo.updateConversation(sessionId, LocalDateTime.now(), "");
        messageRepo.save(Message.builder()
                .userId(null)
                .toUserId(toUserId)
                .sessionId(sessionId)
                .type(MessageType.COMMENT)
                .postId(post.getId())
                .content(new JsonUtils.Builder()
                        .add("nickname", post.getType() == PostType.OFFICIAL ? "官方平台" : user.getNickname())
                        .add("avatar", post.getType() == PostType.OFFICIAL
                                ? "https://jxjmrh.oss-cn-hangzhou.aliyuncs.com/application/icon/guan.png"
                                : user.getAvatar())
                        .add("message", comment.getContent())
                        .build())
                .read(false)
                .build());
    }

    public void sendLikeMsg(Long fromUserId, Long toUserId, String type, Post post, Comment comment) {
        User user = userRepo.findById(fromUserId).orElseThrow(new BusinessException("用户不存在"));
        String sessionId = "like-" + toUserId;
        conversationRepo.updateConversation(sessionId, LocalDateTime.now(), "");
        messageRepo.save(Message.builder()
                .userId(null)
                .toUserId(toUserId)
                .sessionId(sessionId)
                .type(MessageType.LIKE)
                .postId(Optional.ofNullable(post).map(BaseEntity::getId).orElse(null))
                .commentId(Optional.ofNullable(comment).map(BaseEntity::getId).orElse(null))
                .content(new JsonUtils.Builder()
                        .add("nickname", user.getNickname())
                        .add("avatar", user.getAvatar())
                        .add("message", comment == null ? "赞了我的话题" : "赞了我的回复")
                        .add("type", type)
                        .build())
                .read(false)
                .build());
    }
}
