package com.example.system.chat.service;

import com.example.system.chat.mapper.MessageMapper;
import com.example.system.chat.mapper.SessionMassageMapper;
import com.example.system.chat.model.SessionMassage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SessionService {
    @Autowired
    private SessionMassageMapper sessionMassageMapper;
    @Autowired
    private MessageMapper messageMapper;

    /**
     * 根据用户id获取所有会话
     * @param userId
     * @return 会话列表
     */
    public List<SessionMassage> getMessageSession(Integer userId) {
        //获取所有和当前用户有关的会话id
        List<Integer> sessionIds = sessionMassageMapper.getSessionIdByUserId(userId);
        //获取这些会话中的好友信息（排除自己）
        List<SessionMassage> ret = new ArrayList<>();
        for (Integer id : sessionIds) {
            SessionMassage sessionMassage = new SessionMassage();
            sessionMassage.setSessionId(id);
            sessionMassage.setFriend(sessionMassageMapper.getSessionBySessionId(id, userId));
            String lastMessage = messageMapper.getNewMessage(id);
            if (lastMessage == null) {
                sessionMassage.setLastMessage("");
            }
            else {
                sessionMassage.setLastMessage(lastMessage);
            }
            ret.add(sessionMassage);
        }
        return ret;
    }

    //创建会话
    @Transactional
    public Object createSession(List<Integer> friendIds) {
        //创建会话
        SessionMassage sessionMassage = new SessionMassage();
        sessionMassageMapper.insertSession(sessionMassage);
        //创建会话和用户的关系
        for (Integer friendId: friendIds) {
            sessionMassageMapper.insertUserFriend(friendId, sessionMassage.getSessionId());
        }
        return sessionMassage;
    }
}
