package com.izouma.dingdong.service;

import cn.hutool.core.collection.CollUtil;
import com.izouma.dingdong.domain.Chat;
import com.izouma.dingdong.domain.User;
import com.izouma.dingdong.dto.ChatDTO;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.ChatRepo;
import com.izouma.dingdong.repo.UserRepo;
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;
    private UserRepo userRepo;

    /*
    我的聊天列表
     */
    public List<ChatDTO> 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());
        List<ChatDTO> dto = new ArrayList<>();
        sends.forEach(s ->
                dto.add(
                        this.toDto(
                                chatRepo.findFirstBySendUserIdAndReceiveUserIdOrReceiveUserIdAndSendUserIdOrderByIdDesc(s, userId, s, userId)
                        )));
        return dto;
    }

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

    /*
    超过一天自动删除
     */
    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);
            }
        });
    }

    /*
    toDTO
     */
    public ChatDTO toDto(Chat chat) {
        ChatDTO dto = ChatDTO.builder()
                .content(chat.getContent())
                .isRead(chat.getIsRead())
                .receiveUserId(chat.getReceiveUserId())
                .sendTime(chat.getSendTime())
                .sendUserId(chat.getSendUserId())
                .build();
        User receive = userRepo.findById(chat.getReceiveUserId()).orElseThrow(new BusinessException("无用户"));
        dto.setReceiveAvatar(receive.getAvatar());
        dto.setReceiveNickname(receive.getNickname());

        User send = userRepo.findById(chat.getSendUserId()).orElseThrow(new BusinessException("无用户"));
        dto.setSendAvatar(send.getAvatar());
        dto.setSendNickname(send.getNickname());
        return dto;
    }
}
