package com.emotion.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emotion.common.BasePageRequest;
import com.emotion.common.PageResult;
import com.emotion.dto.request.MessagePageRequest;
import com.emotion.dto.request.MessageSearchRequest;
import com.emotion.dto.request.MessageRecentRequest;
import com.emotion.dto.request.MessageCreateRequest;
import com.emotion.dto.response.MessageResponse;
import com.emotion.entity.Message;
import com.emotion.mapper.MessageMapper;
import com.emotion.service.MessageService;
import com.emotion.util.UserContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息服务实现类
 * 
 * @author huazhongmin
 * @date 2025-09-08
 */
@Slf4j
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public IPage<Message> getPage(BasePageRequest request) {
        Page<Message> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.like(Message::getContent, request.getKeyword());
        }
        
        wrapper.eq(Message::getIsDeleted, 0).orderByDesc(Message::getCreateTime);
        return this.page(page, wrapper);
    }

    @Override
    public PageResult<MessageResponse> getPageWithResponse(MessagePageRequest request) {
        // 从上下文中获取当前用户ID
        String userId = UserContextUtils.requireCurrentUserId();

        // 调用用户消息分页查询方法
        PageResult<MessageResponse> pageResult = getUserMessagesWithPage(request);
        return pageResult;
    }

    @Override
    public IPage<Message> getPageByConversationId(BasePageRequest request, String conversationId) {
        Page<Message> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId)
                .eq(Message::getIsDeleted, 0)
                .orderByAsc(Message::getMessageOrder);
        return this.page(page, wrapper);
    }

    @Override
    public List<Message> getByConversationId(String conversationId) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId)
               .eq(Message::getIsDeleted, 0)
                .orderByAsc(Message::getMessageOrder);
        return this.list(wrapper);
    }

    @Override
    public List<Message> getBySender(String sender) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getSender, sender)
               .eq(Message::getIsDeleted, 0)
                .orderByDesc(Message::getCreateTime);
        return this.list(wrapper);
    }

    @Override
    public List<Message> getByTimeRange(String conversationId, LocalDateTime startTime, LocalDateTime endTime) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId)
                .between(Message::getCreateTime, startTime, endTime)
               .eq(Message::getIsDeleted, 0)
                .orderByAsc(Message::getMessageOrder);
        return this.list(wrapper);
    }

    @Override
    public Message getLastMessageByConversationId(String conversationId) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId)
               .eq(Message::getIsDeleted, 0)
                .orderByDesc(Message::getMessageOrder)
               .last("LIMIT 1");
        return this.getOne(wrapper);
    }

    @Override
    public List<Message> getRepliesByParentId(String parentMessageId) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getParentMessageId, parentMessageId)
               .eq(Message::getIsDeleted, 0)
                .orderByAsc(Message::getMessageOrder);
        return this.list(wrapper);
    }

    @Override
    public Long countByConversationId(String conversationId) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId)
               .eq(Message::getIsDeleted, 0);
        return this.count(wrapper);
    }

    @Override
    public Long countBySender(String sender) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getSender, sender)
               .eq(Message::getIsDeleted, 0);
        return this.count(wrapper);
    }

    @Override
    public Long countUnreadMessages(String conversationId) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId)
               .eq(Message::getIsRead, 0)
               .eq(Message::getIsDeleted, 0);
        return this.count(wrapper);
    }

    @Override
    public boolean updateStatus(String messageId, String status) {
        Message message = new Message();
        message.setId(messageId);
        message.setStatus(status);
        return this.updateById(message);
    }

    @Override
    public boolean updateReadStatus(String messageId, Integer isRead) {
        Message message = new Message();
        message.setId(messageId);
        message.setIsRead(isRead);
        return this.updateById(message);
    }

    @Override
    public boolean markConversationMessagesAsRead(String conversationId) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId)
               .eq(Message::getIsRead, 0)
                .eq(Message::getIsDeleted, 0);

        Message updateMessage = new Message();
        updateMessage.setIsRead(1);

        return this.update(updateMessage, wrapper);
    }

    @Override
    public Message createMessage(Message message) {
        // 设置默认值
        if (message.getTimestamp() == null) {
            message.setTimestamp(LocalDateTime.now());
        }
        if (message.getStatus() == null) {
            message.setStatus("sent");
        }
        if (message.getIsRead() == null) {
            message.setIsRead(0);
        }

        // 设置消息顺序 - 在同一个会话中递增
        if (message.getMessageOrder() == null) {
            Long nextOrder = getNextMessageOrder(message.getConversationId());
            message.setMessageOrder(nextOrder);
        }

        this.save(message);
        return message;
    }

    /**
     * 获取会话中下一个消息顺序
     *
     * @param conversationId 会话ID
     * @return 下一个消息顺序
     */
    private Long getNextMessageOrder(String conversationId) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId)
                .eq(Message::getIsDeleted, 0)
                .orderByDesc(Message::getMessageOrder)
                .last("LIMIT 1");

        Message lastMessage = this.getOne(wrapper);
        if (lastMessage != null && lastMessage.getMessageOrder() != null) {
            return lastMessage.getMessageOrder() + 1;
        }
        return 1L;
    }

    @Override
    public boolean markAsRead(String messageId) {
        return updateReadStatus(messageId, 1);
    }

    @Override
    public List<Message> getByUserIdAndTimeRange(String userId, LocalDateTime startTime, LocalDateTime endTime) {
        // 使用 MyBatis-Plus 条件构造器，直接根据消息表的 user_id 字段查询
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getUserId, userId)
                .between(Message::getCreateTime, startTime, endTime)
                .eq(Message::getIsDeleted, 0)
                .orderByAsc(Message::getMessageOrder);
        return this.list(wrapper);
    }

    @Override
    public IPage<Message> getByUserIdWithPage(String userId, Integer current, Integer size) {
        // 使用 MyBatis-Plus 分页 + 条件构造器
        Page<Message> page = new Page<>(current, size);
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getUserId, userId)
                .eq(Message::getIsDeleted, 0)
                .orderByAsc(Message::getMessageOrder);
        return this.page(page, wrapper);
    }

    @Override
    public List<Message> searchByUserIdAndKeyword(String userId, String keyword, Integer limit) {
        // 使用 MyBatis-Plus 分页 + 条件构造器，避免硬编码 SQL
        Page<Message> page = new Page<>(1, limit);
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getUserId, userId)
                .eq(Message::getIsDeleted, 0)
                .like(StringUtils.hasText(keyword), Message::getContent, keyword)
                .orderByAsc(Message::getMessageOrder);
        IPage<Message> result = this.page(page, wrapper);
        return result.getRecords();
    }

    @Override
    public List<Message> getRecentByUserId(String userId, Integer limit) {
        // 使用 MyBatis-Plus 分页查询最近消息
        Page<Message> page = new Page<>(1, limit);
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getUserId, userId)
                .eq(Message::getIsDeleted, 0)
                .orderByDesc(Message::getMessageOrder);
        IPage<Message> result = this.page(page, wrapper);
        return result.getRecords();
    }

    @Override
    public PageResult<MessageResponse> getUserMessagesWithPage(MessagePageRequest request) {
        // 从上下文中获取当前用户ID
        String userId = UserContextUtils.requireCurrentUserId();

        // 调用原有的分页查询方法
        IPage<Message> page = getByUserIdWithPage(userId, Math.toIntExact(request.getCurrent()),
                Math.toIntExact(request.getSize()));

        // 转换为响应对象
        List<MessageResponse> responses = page.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        // 构建分页结果
        PageResult<MessageResponse> pageResult = new PageResult<>();
        pageResult.setCurrent(page.getCurrent());
        pageResult.setSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setPages(page.getPages());
        pageResult.setRecords(responses);

        return pageResult;
    }

    @Override
    public List<MessageResponse> searchUserMessages(MessageSearchRequest request) {
        // 从上下文中获取当前用户ID
        String userId = UserContextUtils.requireCurrentUserId();

        // 调用原有的搜索方法
        List<Message> messages = searchByUserIdAndKeyword(userId, request.getKeyword(), request.getLimit());

        // 转换为响应对象
        return messages.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<MessageResponse> getUserRecentMessages(MessageRecentRequest request) {
        // 从上下文中获取当前用户ID
        String userId = UserContextUtils.requireCurrentUserId();

        // 调用原有的获取最近消息方法
        List<Message> messages = getRecentByUserId(userId, request.getLimit());

        // 转换为响应对象
        return messages.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public MessageResponse createMessageFromRequest(MessageCreateRequest request) {
        // 从上下文中获取当前用户ID
        String userId = UserContextUtils.requireCurrentUserId();

        // 构建消息对象
        Message message = new Message();
        message.setConversationId(request.getConversationId());
        message.setCreateBy(userId);
        message.setContent(request.getContent());
        message.setType(request.getContentType());
        message.setSender(request.getSenderType());

        // 调用原有的创建方法
        Message savedMessage = createMessage(message);

        // 转换为响应对象
        return convertToResponse(savedMessage);
    }

    @Override
    public MessageResponse getMessageById(String id) {
        Message message = getById(id);
        if (message == null) {
            return null;
        }

        // 转换为响应对象
        return convertToResponse(message);
    }

    @Override
    public PageResult<MessageResponse> searchWithResponse(MessageSearchRequest request) {
        // 从上下文中获取当前用户ID
        String userId = UserContextUtils.requireCurrentUserId();

        // 构建分页对象
        Page<Message> page = new Page<>(1L, request.getLimit().longValue());

        // 调用搜索方法
        List<Message> messages = searchByUserIdAndKeyword(userId, request.getKeyword(), request.getLimit());

        // 设置分页信息
        page.setRecords(messages);
        page.setTotal(messages.size());

        // 转换为响应对象
        List<MessageResponse> responses = messages.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        // 构建分页结果
        PageResult<MessageResponse> pageResult = new PageResult<>();
        pageResult.setRecords(responses);
        pageResult.setCurrent(page.getCurrent());
        pageResult.setSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setPages(page.getPages());

        return pageResult;
    }

    @Override
    public PageResult<MessageResponse> getRecentWithResponse(MessageRecentRequest request) {
        // 从上下文中获取当前用户ID
        String userId = UserContextUtils.requireCurrentUserId();

        // 构建分页对象
        Page<Message> page = new Page<>(1L, request.getLimit().longValue());

        // 调用获取最近消息方法
        List<Message> messages = getRecentByUserId(userId, request.getLimit());

        // 设置分页信息
        page.setRecords(messages);
        page.setTotal(messages.size());

        // 转换为响应对象
        List<MessageResponse> responses = messages.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        // 构建分页结果
        PageResult<MessageResponse> pageResult = new PageResult<>();
        pageResult.setRecords(responses);
        pageResult.setCurrent(page.getCurrent());
        pageResult.setSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setPages(page.getPages());

        return pageResult;
    }

    @Override
    public MessageResponse updateMessage(String id, String content) {
        Message message = this.getById(id);
        if (message == null || message.getIsDeleted() == 1) {
            return null;
        }

        // 更新内容
        message.setContent(content);
        this.updateById(message);

        // 转换为响应对象
        return convertToResponse(message);
    }

    @Override
    public boolean deleteMessage(String id) {
        Message message = this.getById(id);
        if (message == null) {
            return false;
        }

        // 使用 MyBatis-Plus 的 removeById 方法，自动处理逻辑删除
        return this.removeById(id);
    }

    /**
     * 转换为响应对象
     */
    private MessageResponse convertToResponse(Message message) {
        MessageResponse response = new MessageResponse();
        BeanUtils.copyProperties(message, response);
        response.setId(message.getId());
        if (message.getCreateTime() != null) {
            response.setCreateTime(message.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (message.getUpdateTime() != null) {
            response.setUpdateTime(message.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        return response;
    }
}