package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.config.TokenUtils;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Account;
import com.example.entity.ChatMessage;
import com.example.entity.Doctor;
import com.example.entity.DoctorPatient;
import com.example.entity.Patient;
import com.example.exception.CustomException;
import com.example.mapper.ChatMessageMapper;
import com.example.mapper.DoctorMapper;
import com.example.mapper.PatientMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

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

@Service
public class ChatMessageService {

    @Resource
    private ChatMessageMapper chatMessageMapper;
    
    @Resource
    private DoctorPatientService doctorPatientService;
    
    @Resource
    private DoctorMapper doctorMapper;
    
    @Resource
    private PatientMapper patientMapper;
    
    /**
     * 发送消息 - 通过HTTP接口调用
     */
    public ChatMessage sendMessage(ChatMessage chatMessage) {
        // 获取当前用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 根据当前用户角色设置发送者信息
        chatMessage.setSenderId(currentUser.getId());
        chatMessage.setSenderType(currentUser.getRole());
        
        // 检查发送者和接收者是否有关联关系
        checkRelationship(chatMessage.getSenderId(), chatMessage.getSenderType(), 
                        chatMessage.getReceiverId(), chatMessage.getReceiverType());
        
        // 设置消息状态
        chatMessage.setSendTime(new Date());
        chatMessage.setIsRead(false);
        
        // 保存消息
        chatMessageMapper.insert(chatMessage);
        
        return chatMessage;
    }
    
    /**
     * 直接保存消息 - 通过WebSocket调用，不依赖TokenUtils
     */
    public ChatMessage directSaveMessage(ChatMessage chatMessage) {
        // 检查发送者和接收者是否有关联关系
        checkRelationship(chatMessage.getSenderId(), chatMessage.getSenderType(), 
                        chatMessage.getReceiverId(), chatMessage.getReceiverType());
        
        // 保存消息
        chatMessageMapper.insert(chatMessage);
        
        return chatMessage;
    }
    
    /**
     * 获取聊天历史记录
     */
    public List<ChatMessage> getChatHistory(Integer contactId, String contactType) {
        // 获取当前用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 检查关系
        checkRelationship(currentUser.getId(), currentUser.getRole(), contactId, contactType);
        
        // 查询聊天记录
        List<ChatMessage> messages = chatMessageMapper.selectChatHistory(
                currentUser.getId(), currentUser.getRole(), contactId, contactType);
        
        // 将对方发送的未读消息标记为已读
        chatMessageMapper.markAsRead(currentUser.getId(), currentUser.getRole(), contactId, contactType);
        
        // 填充发送者和接收者的名称
        fillUserInfo(messages);
        
        return messages;
    }
    
    /**
     * 获取联系人列表
     */
    public List<Map<String, Object>> getContactList() {
        // 获取当前用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 根据用户角色获取联系人
        if ("doctor".equals(currentUser.getRole())) {
            // 医生获取其患者列表
            List<DoctorPatient> relations = doctorPatientService.selectByDoctorId(currentUser.getId(), null);
            for (DoctorPatient relation : relations) {
                if ("正常".equals(relation.getStatus()) && relation.getPatient() != null) {
                    Map<String, Object> contact = new HashMap<>();
                    contact.put("contactId", relation.getPatientId());
                    contact.put("contactType", "patient");
                    contact.put("contactName", relation.getPatient().getName());
                    contact.put("contactAvatar", relation.getPatient().getAvatar());
                    // 查询未读消息数
                    int unread = chatMessageMapper.countUnreadMessages(
                            currentUser.getId(), currentUser.getRole(), relation.getPatientId(), "patient");
                    contact.put("unreadCount", unread);
                    
                    // 查询最新一条消息
                    List<ChatMessage> lastMessages = chatMessageMapper.selectChatHistory(
                            currentUser.getId(), currentUser.getRole(), relation.getPatientId(), "patient");
                    if (!lastMessages.isEmpty()) {
                        contact.put("lastMessage", lastMessages.get(lastMessages.size() - 1));
                    }
                    
                    result.add(contact);
                }
            }
        } else if ("patient".equals(currentUser.getRole())) {
            // 患者获取其医生列表
            List<DoctorPatient> relations = doctorPatientService.selectByPatientId(currentUser.getId(), null);
            for (DoctorPatient relation : relations) {
                if ("正常".equals(relation.getStatus()) && relation.getDoctor() != null) {
                    Map<String, Object> contact = new HashMap<>();
                    contact.put("contactId", relation.getDoctorId());
                    contact.put("contactType", "doctor");
                    contact.put("contactName", relation.getDoctor().getName());
                    contact.put("contactAvatar", relation.getDoctor().getAvatar());
                    // 查询未读消息数
                    int unread = chatMessageMapper.countUnreadMessages(
                            currentUser.getId(), currentUser.getRole(), relation.getDoctorId(), "doctor");
                    contact.put("unreadCount", unread);
                    
                    // 查询最新一条消息
                    List<ChatMessage> lastMessages = chatMessageMapper.selectChatHistory(
                            currentUser.getId(), currentUser.getRole(), relation.getDoctorId(), "doctor");
                    if (!lastMessages.isEmpty()) {
                        contact.put("lastMessage", lastMessages.get(lastMessages.size() - 1));
                    }
                    
                    result.add(contact);
                }
            }
        }
        
        return result;
    }
    
    /**
     * 检查用户关系
     */
    private void checkRelationship(Integer senderId, String senderType, Integer receiverId, String receiverType) {
        // 检查医生和患者是否存在关联关系
        if ("doctor".equals(senderType) && "patient".equals(receiverType)) {
            List<DoctorPatient> relations = doctorPatientService.selectByDoctorId(senderId, null);
            boolean hasRelation = relations.stream()
                    .anyMatch(dp -> dp.getPatientId().equals(receiverId) && "正常".equals(dp.getStatus()));
            
            if (!hasRelation) {
                throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "您与该患者没有关联关系");
            }
        } else if ("patient".equals(senderType) && "doctor".equals(receiverType)) {
            List<DoctorPatient> relations = doctorPatientService.selectByPatientId(senderId, null);
            boolean hasRelation = relations.stream()
                    .anyMatch(dp -> dp.getDoctorId().equals(receiverId) && "正常".equals(dp.getStatus()));
            
            if (!hasRelation) {
                throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "您与该医生没有关联关系");
            }
        } else {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "无效的聊天关系");
        }
    }
    
    /**
     * 填充用户信息
     */
    private void fillUserInfo(List<ChatMessage> messages) {
        for (ChatMessage message : messages) {
            // 填充发送者信息
            if ("doctor".equals(message.getSenderType())) {
                Doctor doctor = doctorMapper.selectById(message.getSenderId());
                if (doctor != null) {
                    message.setSenderName(doctor.getName());
                    message.setSenderAvatar(doctor.getAvatar());
                }
            } else if ("patient".equals(message.getSenderType())) {
                Patient patient = patientMapper.selectById(message.getSenderId());
                if (patient != null) {
                    message.setSenderName(patient.getName());
                    message.setSenderAvatar(patient.getAvatar());
                }
            }
            
            // 可以根据需要填充接收者信息
        }
    }
} 