package cn.reghao.tnb.content.app.chat.service;

import cn.reghao.jutil.jdk.string.SnowFlake;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.app.chat.db.mapper.*;
import cn.reghao.tnb.content.app.chat.model.constant.ChatType;
import cn.reghao.tnb.content.app.chat.model.dto.chat.*;
import cn.reghao.tnb.content.app.chat.model.po.chat.ChatDialog;
import cn.reghao.tnb.user.api.dto.ContactDetail;
import cn.reghao.tnb.user.api.iface.UserContactService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2022-04-20 19:25:02
 */
@Service
public class ChatDialogService {
    @DubboReference(check = false)
    private UserContactService contactService;

    private final SnowFlake snowFlake;
    private final ChatDialogMapper chatDialogMapper;

    public ChatDialogService(ChatDialogMapper chatDialogMapper) {
        this.snowFlake = new SnowFlake(1L, 1L);
        this.chatDialogMapper = chatDialogMapper;
    }

    public ChatInitialRet createChatDialog(ChatInitial chatInitial) {
        long loginUser = UserContext.getUserId();
        long receiverId = chatInitial.getReceiverId();
        int chatType = chatInitial.getTalkType();
        ChatDialog chatDialog;
        if (chatType == 1) {
            chatDialog = p2pChatDialog(receiverId, loginUser);
        } else {
            chatDialog = groupChatDialog(receiverId, loginUser);
        }

        if (!chatDialog.isDisplay()) {
            chatDialogMapper.updateSetDisplay(chatDialog.getId(), chatDialog.getUserId(), true);
        }

        ChatUserInfo chatUserInfo = getDialogUserInfo(loginUser, chatType, receiverId);
        if (chatUserInfo == null) {
            return null;
        }

        return new ChatInitialRet(chatDialog, chatUserInfo);
    }

    private ChatDialog groupChatDialog(long receiverId, long userId) {
        ChatDialog chatDialog = chatDialogMapper.findByReceiverAndUserId(receiverId, userId);
        if (chatDialog == null) {
            long chatId = snowFlake.nextId();
            chatDialog = new ChatDialog(chatId, ChatType.group.getCode(), receiverId, userId, true);
            chatDialogMapper.save(chatDialog);
        }

        return chatDialog;
    }

    private ChatDialog p2pChatDialog(long receiverId, long userId) {
        ChatDialog chatDialog = chatDialogMapper.findByReceiverAndUserId(receiverId, userId);
        if (chatDialog == null) {
            long chatId = snowFlake.nextId();
            chatDialog = new ChatDialog(chatId, ChatType.single.getCode(), receiverId, userId, true);
            ChatDialog chatDialog1 = new ChatDialog(chatId, ChatType.single.getCode(), userId, receiverId, false);
            // TODO 保证批量操作全部成功 or 全部失败
            chatDialogMapper.saveAll(List.of(chatDialog, chatDialog1));
        }

        return chatDialog;
    }

    private ChatUserInfo getDialogUserInfo(long userId, int chatType, long receiverId) {
        ChatUserInfo chatUserInfo = null;
        if (chatType == 1) {
            ContactDetail contactDetail = contactService.getContactDetail(receiverId);
            chatUserInfo = new ChatUserInfo(contactDetail);
        } else {
            //chatUserInfo = groupInfoMapper.findDialogGroupInfo(receiverId);
        }

        return chatUserInfo;
    }

    public List<ChatInitialRet> getChatDialogs() {
        long loginUser = UserContext.getUserId();
        List<ChatDialog> chatDialogs = chatDialogMapper.findChatDialogsByUserId(loginUser);
        return chatDialogs.stream()
                .map(chatDialog -> {
                    int chatType = chatDialog.getChatType();
                    long receiverId = chatDialog.getReceiverId();
                    ChatUserInfo chatUserInfo = getDialogUserInfo(loginUser, chatType, receiverId);
                    if (chatUserInfo == null) {
                        return null;
                    }
                    return new ChatInitialRet(chatDialog, chatUserInfo);
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    public void deleteChatDialog(long dialogId) {
        long loginUser = UserContext.getUserId();
        chatDialogMapper.updateSetDisplay(dialogId, loginUser, false);
    }

    public void setChatDialogTop(ChatTop chatTop) {
        long loginUser = UserContext.getUserId();
        long dialogId = chatTop.getListId();
        int type = chatTop.getType();
        boolean top = type == 1;
        chatDialogMapper.updateSetTop(dialogId, loginUser, top);
    }

    public void setChatDialogDisturb(ChatDisturb chatDisturb) {
        long loginUser = UserContext.getUserId();
        boolean disturb = chatDisturb.getIsDisturb() == 1;
        long receiverId = chatDisturb.getReceiverId();
        ChatDialog chatDialog = chatDialogMapper.findByReceiverAndUserId(receiverId, loginUser);
        if (chatDialog != null) {
            chatDialogMapper.updateSetDisturb(chatDialog.getId(), loginUser, disturb);
        }
    }

    public void clearUnread(long receiverId) {
        long loginUser = UserContext.getUserId();
    }
}
