package com.izouma.dingdong.service;

import cn.hutool.core.collection.CollUtil;
import com.izouma.dingdong.domain.Chat;
import com.izouma.dingdong.repo.ChatRepo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class ChatService {

    private ChatRepo chatRepo;

    /*
    我的聊天列表
     */
    public List<Chat> my(Long userId) {
        List<Chat> chats = chatRepo.findAllBySendUserIdOrReceiveUserId(userId, userId);
        //发送
        Set<Long> sends = chats.stream().map(Chat::getSendUserId).collect(Collectors.toSet());
        //接受
        Set<Long> receives = chats.stream().map(Chat::getReceiveUserId).collect(Collectors.toSet());
        sends.addAll(receives);
        sends.remove(userId);

        if (CollUtil.isEmpty(sends)) {
            return null;
        }

        return sends.stream().map(s ->
                this.showChat(s, userId).get(0)
        ).collect(Collectors.toList());
    }

    /*
    显示两个人之间的具体对话
     */
    public List<Chat> showChat(Long userOne, Long userTwo) {
        List<Chat> sendChats = chatRepo.findAllBySendUserIdAndReceiveUserId(userOne, userTwo);
        List<Chat> receiveChats = chatRepo.findAllBySendUserIdAndReceiveUserId(userTwo, userOne);
        sendChats.addAll(receiveChats);
        sendChats.sort((a, b) -> b.getId().compareTo(a.getId()));
        return sendChats;
    }

    /*
    超过一天自动删除
     */
    public void delChat(Long userId) {
        List<Chat> chats = chatRepo.findAllBySendUserIdOrReceiveUserId(userId, userId);
        chats.forEach(chat -> {
            if (LocalDateTime.now().isAfter(chat.getSendTime().plusDays(1))) {
                chatRepo.delete(chat);
            }
        });
    }
}
