package com.sikey.wa04.business.application.service.message;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sikey.wa04.business.domain.adapter.*;
import com.sikey.wa04.business.domain.entity.*;
import com.sikey.wa04.business.domain.entity.message.Message;
import com.sikey.wa04.business.domain.entity.message.MessageId;
import com.sikey.wa04.business.domain.entity.message.MessageReceivedLog;
import com.sikey.wa04.business.domain.usecase.ChatSessionFactory;
import com.sikey.wa04.business.domain.usecase.ChildIdFactory;
import com.sikey.wa04.business.infrastructure.dto.model.ContactModel;
import com.sikey.wa04.business.infrastructure.dto.request.messaging.HistoryMessageSessionRequest;
import com.sikey.wa04.business.infrastructure.dto.request.messaging.HistoryUnreadMessageRequest;
import com.sikey.wa04.business.infrastructure.dto.request.messaging.ReadUnreadMessageRequest;
import com.sikey.wa04.business.infrastructure.dto.response.messaging.HistoryMessageSessionResponse;
import com.sikey.wa04.business.infrastructure.dto.response.messaging.HistoryUnreadMessageResponse;
import com.sikey.wa04.business.infrastructure.repository.ContactRepository;
import com.sikey.wa04.common.dto.header.GenericManufacturerHeader;
import com.sikey.wa04.common.enums.ContactRole;
import com.sikey.wa04.common.enums.GroupMemberRole;
import com.sikey.wa04.common.enums.UserType;
import com.sikey.wa04.common.interceptor.CurrentRequestUser;
import com.sikey.wa04.common.utils.ObjectMapperUtil;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class HistoryMessageService {

    @Resource
    private ChildQueryAdapter childQueryAdapter;

    @Resource
    private GroupAdapter groupAdapter;

    @Resource
    private GroupMemberAdapter groupMemberAdapter;

    @Resource
    private MessageAdapter messageAdapter;

    @Resource
    private UserAdapter userAdapter;

    @Resource
    private ContactRepository contactRepository;

    @Resource
    private DeviceConfigAdapter deviceConfigAdapter;

    @Qualifier("myTaskExecutor")
    @Autowired
    private ThreadPoolTaskExecutor myTaskExecutor;

    @Resource
    private ChildAdapter childAdapter;

    /**
     * APP加载会话消息，需要返回最旧的未读消息
     *
     * @param request 请求
     * @return 响应
     */
    public HistoryMessageSessionResponse loadSession(HistoryMessageSessionRequest request) throws Exception {
        UserId userId = new UserId(CurrentRequestUser.get().getId());
        List<Child> children = childQueryAdapter.findChildren(userId);

        List<HistoryMessageSessionResponse.Session> sessions = new ArrayList<>();
        for (Child child : children) {
            // 用户角色是其他不展示群聊
            ContactModel contactModel = contactRepository.findByChildIdAndRefId(child.getId(), userId.getId());
            if (Objects.nonNull(contactModel) && Objects.nonNull(contactModel.getRefRole()) && (contactModel.getRefRole().intValue() != ContactRole.FRIEND.getValue() && contactModel.getRefRole().intValue() != ContactRole.OTHER.getValue())) {
                sessions.add(loadGroupSession(userId, child));
            }

            // Query child contacts
            List<ContactModel> contacts = contactRepository.findByChildId(child.getId());

            // Turn child into private chat
            HistoryMessageSessionResponse.Session privateSession = new HistoryMessageSessionResponse.Session().setUnreadOldMsgId(0L).setIsGroup(false);

            // Find oneself in contacts
            // In the child's perspective oneself must be a member of the address book
            ContactModel oneself = contacts.stream().filter(ct -> ct.getRefId().equals(userId.getId())).findFirst().orElseThrow();

            Integer privateUnreadCount = messageAdapter.unreadCount(userId, ChatSessionFactory.createPrivateSessionId(new ChildId(child.getId())));
            privateSession.setUnreadCount(privateUnreadCount);

            List<Message> privateUnreadMessages = messageAdapter.findUnreadMessages(userId, ChatSessionFactory.createPrivateSessionId(new ChildId(child.getId())));
            if (!privateUnreadMessages.isEmpty()) {
                //获取最旧的未读消息，因为这个列表未手动排序过，数据库是根据id升序排序，所以应该取第一条
                Message message = privateUnreadMessages.getFirst();
                privateSession.setUnreadOldMsgId(message.getId().getId());
            }
            privateSession.setSid(child.getId()).setName(child.getName()).setCid(child.getId()).setMembers(List.of(new HistoryMessageSessionResponse.SessionMember().setRefId(child.getId()).setRefType(UserType.CHILD.getValue()).setRefRole(GroupMemberRole.EVERYMAN.getValue()).setAvatar(child.getAvatar()).setName(child.getName()), new HistoryMessageSessionResponse.SessionMember().setRefId(CurrentRequestUser.get().getId()).setRefType(UserType.USER.getValue()).setRefRole(GroupMemberRole.OWNER.getValue()).setAvatar(oneself.getRemarkAvatar()).setName(oneself.getRemarkName())));
            sessions.add(privateSession);
        }
        return new HistoryMessageSessionResponse().setSessions(sessions);
    }

    /**
     * 加载手表会话消息，需要返回最新的未读消息
     *
     * @param request 请求
     * @return 响应
     */
    public HistoryMessageSessionResponse loadWristwatchSession(HistoryMessageSessionRequest request, GenericManufacturerHeader genericManufacturerHeader) throws Exception {
        UserId userId = new UserId(CurrentRequestUser.get().getId());

        Child child = childQueryAdapter.findByChildId(ChildIdFactory.create(userId.getId()));

        // log.info("[加载手表会话消息]当前儿童：{}", JSONUtil.toJsonPrettyStr(child));

        List<HistoryMessageSessionResponse.Session> sessions = new ArrayList<>();
        sessions.add(loadWristwatchGroupSession(userId, child));

        // Query child contacts
        // Any registered user in the address book will be displayed in the chat session
        List<ContactModel> contacts = contactRepository.findByChildIdOrderByIdAsc(child.getId());

        //  log.info("[加载手表会话消息]当前儿童通讯录：{}", JSONUtil.toJsonPrettyStr(contacts));

        for (ContactModel contact : contacts) {
            // Turn child into private chat
            HistoryMessageSessionResponse.Session privateSession = new HistoryMessageSessionResponse.Session().setUnreadOldMsgId(0L).setIsGroup(false);

            if (Objects.nonNull(contact.getRefType()) && contact.getRefType().intValue() == UserType.CHILD.getValue()) {
                // 儿童好友
                Child queryChild = childQueryAdapter.findByChildId(new ChildId(contact.getRefId()));
                if (Objects.nonNull(queryChild)) {
                    ChatSessionId privateSessionId = ChatSessionFactory.createPrivateSessionId(new ChildId(queryChild.getId()));
                    Integer privateUnreadCount = messageAdapter.unreadCount(userId, privateSessionId);
                    privateSession.setUnreadCount(privateUnreadCount);
                    List<Message> privateUnreadMessages = messageAdapter.findUnreadMessages(userId, privateSessionId);
                    if (!privateUnreadMessages.isEmpty()) {
                        //获取最新的未读消息，因为这个列表未手动排序过，数据库是根据id升序排序，所以应该取最后一条
                        Message message = privateUnreadMessages.getLast();
                        privateSession.setUnreadOldMsgId(message.getId().getId());
                    }
                }

                privateSession.setSid(contact.getRefId()) // 儿童好友
                        .setName(contact.getRemarkName()).setCid(child.getId()) // 当前儿童
                        .setMembers(List.of(new HistoryMessageSessionResponse.SessionMember().setRefType(UserType.CHILD.getValue()).setRefRole(GroupMemberRole.EVERYMAN.getValue()).setRefId(child.getId()).setAvatar(child.getAvatar()).setName(child.getName()), new HistoryMessageSessionResponse.SessionMember().setRefType(UserType.CHILD.getValue()).setRefRole(GroupMemberRole.EVERYMAN.getValue()).setRefId(contact.getRefId()).setAvatar(contact.getRemarkAvatar()).setName(contact.getRemarkName())));

                // 最新的消息内容
                Message message = messageAdapter.find(new MessageId(privateSession.getUnreadOldMsgId()));
                if(Objects.nonNull(message)) {
                    privateSession.setContent(message.getContent());
                    if(Objects.nonNull(message.getType())){
                        privateSession.setMessageType(message.getType().getValue());
                    }
                }


                sessions.add(privateSession);
            } else {
                // 儿童家长
                User refUser = userAdapter.findById(new UserId(contact.getRefId()));
                // log.info("[加载手表会话消息]用户：{}，用户id：{}", refUser, contact.getRefId());
                //当IsRegistered为false, 未注册时,不返回此家庭成员
                if (Objects.isNull(refUser) || !refUser.getIsRegistered()) {
                    continue;
                }

                ChatSessionId privateSessionId = ChatSessionFactory.createPrivateSessionId(refUser.getId());
                Integer privateUnreadCount = messageAdapter.unreadCount(userId, privateSessionId);
                privateSession.setUnreadCount(privateUnreadCount);

                List<Message> privateUnreadMessages = messageAdapter.findUnreadMessages(userId, privateSessionId);
                if (!privateUnreadMessages.isEmpty()) {
                    //获取最新的未读消息，因为这个列表未手动排序过，数据库是根据id升序排序，所以应该取最后一条
                    Message message = privateUnreadMessages.getLast();
                    privateSession.setUnreadOldMsgId(message.getId().getId());
                }
                privateSession.setSid(contact.getRefId()) // 家长
                        .setName(contact.getRemarkName()).setCid(child.getId()) // 当前儿童
                        .setMembers(List.of(new HistoryMessageSessionResponse.SessionMember().setRefType(UserType.CHILD.getValue()).setRefRole(GroupMemberRole.EVERYMAN.getValue()).setRefId(child.getId()).setAvatar(child.getAvatar()).setName(child.getName()), new HistoryMessageSessionResponse.SessionMember().setRefType(UserType.USER.getValue()).setRefRole(GroupMemberRole.OWNER.getValue()).setRefId(contact.getRefId()).setAvatar(contact.getRemarkAvatar()).setName(contact.getRemarkName())));

                // 最新的未读消息内容
                Message message = messageAdapter.find(new MessageId(privateSession.getUnreadOldMsgId()));
                if(Objects.nonNull(message)) {
                    privateSession.setContent(message.getContent());
                    if(Objects.nonNull(message.getType())) {
                        privateSession.setMessageType(message.getType().getValue());
                    }
                }

                sessions.add(privateSession);
            }

        }

        myTaskExecutor.execute(() -> {
            // 设备配置
            deviceConfigAdapter.deviceConfigMessageCenter(userId.getId(), genericManufacturerHeader);
        });


        // log.info("[加载手表会话消息]当前儿童会话信息：{}", JSONUtil.toJsonPrettyStr(sessions));
        return new HistoryMessageSessionResponse().setSessions(sessions);
    }

    /**
     * APP加载群聊会话，需要返回最旧的未读消息
     *
     * @param child 小孩
     * @return 家庭群聊
     * @throws Exception error
     */
    private HistoryMessageSessionResponse.Session loadGroupSession(UserId userId, Child child) throws Exception {
        //  log.info("[加载群聊会话]入参：用户id：{}，儿童：{}", userId, child);
        // Query child contacts
        List<ContactModel> contacts = contactRepository.findByChildId(child.getId());
        //   log.info("[加载群聊会话]联系人：{}", JSONUtil.toJsonPrettyStr(contacts));

        // Query group
        Group group = groupAdapter.findByChildId(new ChildId(child.getId()));

        // 注册用户
        List<GroupMember> findMembers = groupMemberAdapter.findMembers(group.getId());

        List<String> refIdList = findMembers.stream().filter(m -> Objects.nonNull(m.getType()) && m.getType().getValue() == UserType.USER.getValue().intValue()).map(GroupMember::getRefId).toList();
        List<User> users = userAdapter.findByUserIdIn(refIdList);
        List<String> userIdList = users.stream().filter(u -> u.getIsRegistered()).map(User::getId).map(UserId::getId).toList();
        // 儿童
        List<String> childRefIdList = findMembers.stream().filter(m -> Objects.nonNull(m.getType()) && m.getType().getValue() == UserType.CHILD.getValue().intValue()).map(GroupMember::getRefId).toList();
        List<String> childIdList = childAdapter.findByChildIdIn(childRefIdList).stream().map(Child::getId).toList();
        List<String> allList = new ArrayList<>();
        allList.addAll(userIdList);
        allList.addAll(childIdList);

        group.setMembers(findMembers.stream().filter(m -> allList.contains(m.getRefId())).toList());
        //  log.info("[加载群聊会话]群组：{}", group);

        HistoryMessageSessionResponse.Session groupSession = new HistoryMessageSessionResponse.Session().setIsGroup(true).setName(String.format("%s 家庭群聊", child.getName())).setCid(child.getId()).setSid(group.getId().getId());

        Integer unreadCount = messageAdapter.unreadCount(userId, ChatSessionFactory.createGroupSessionId(group.getId()));
        groupSession.setUnreadCount(unreadCount);

        // Query the ID of the most recent message
        List<Message> unreadMessages = messageAdapter.findUnreadMessages(userId, ChatSessionFactory.createGroupSessionId(group.getId()));
        if (!unreadMessages.isEmpty()) {
            //获取最旧的未读消息，因为这个列表未手动排序过，数据库是根据id排序所以应该取第一条
            Message message = unreadMessages.getFirst();
            groupSession.setUnreadOldMsgId(message.getId().getId());
        } else {
            groupSession.setUnreadOldMsgId(0L);
        }

        List<HistoryMessageSessionResponse.SessionMember> groupMembers = new ArrayList<>();
        for (GroupMember groupMember : group.getMembers()) {
            HistoryMessageSessionResponse.SessionMember sessionMember = new HistoryMessageSessionResponse.SessionMember().setRefId(groupMember.getRefId()).setRefType(groupMember.getType().getValue()).setRefRole(groupMember.getRole().getValue());

            if (groupMember.getRefId().equals(child.getId())) {
                sessionMember.setName(child.getName());
                sessionMember.setAvatar(child.getAvatar());
            } else {
                // Find oneself in contacts
                Optional<ContactModel> oneself = contacts.stream().filter(ct -> ct.getRefId().equals(groupMember.getRefId())).findFirst();
                if (oneself.isPresent()) {
                    ContactModel contactModel = oneself.get();
                    sessionMember.setName(contactModel.getRemarkName());
                    sessionMember.setAvatar(contactModel.getRemarkAvatar());
                }

            }

            groupMembers.add(sessionMember);
        }
        groupSession.setMembers(groupMembers);

        // 最旧的消息内容
        Message message = messageAdapter.find(new MessageId(groupSession.getUnreadOldMsgId()));
        if(Objects.nonNull(message)) {
            groupSession.setContent(message.getContent());
            if(Objects.nonNull(message.getType())) {
                groupSession.setMessageType(message.getType().getValue());
            }
        }

        return groupSession;
    }

    /**
     * 手表端加载群聊会话，需要返回最新的未读消息
     *
     * @param child 小孩
     * @return 家庭群聊
     * @throws Exception error
     */
    private HistoryMessageSessionResponse.Session loadWristwatchGroupSession(UserId userId, Child child) throws Exception {
        //  log.info("[加载群聊会话]入参：用户id：{}，儿童：{}", userId, child);
        // Query child contacts
        List<ContactModel> contacts = contactRepository.findByChildId(child.getId());
        //   log.info("[加载群聊会话]联系人：{}", JSONUtil.toJsonPrettyStr(contacts));

        // Query group
        Group group = groupAdapter.findByChildId(new ChildId(child.getId()));

        // 注册用户
        List<GroupMember> findMembers = groupMemberAdapter.findMembers(group.getId());

        List<String> refIdList = findMembers.stream().filter(m -> Objects.nonNull(m.getType()) && m.getType().getValue() == UserType.USER.getValue().intValue()).map(GroupMember::getRefId).toList();
        List<User> users = userAdapter.findByUserIdIn(refIdList);
        List<String> userIdList = users.stream().filter(u -> u.getIsRegistered()).map(User::getId).map(UserId::getId).toList();
        // 儿童
        List<String> childRefIdList = findMembers.stream().filter(m -> Objects.nonNull(m.getType()) && m.getType().getValue() == UserType.CHILD.getValue().intValue()).map(GroupMember::getRefId).toList();
        List<String> childIdList = childAdapter.findByChildIdIn(childRefIdList).stream().map(Child::getId).toList();
        List<String> allList = new ArrayList<>();
        allList.addAll(userIdList);
        allList.addAll(childIdList);

        group.setMembers(findMembers.stream().filter(m -> allList.contains(m.getRefId())).toList());
        //  log.info("[加载群聊会话]群组：{}", group);

        HistoryMessageSessionResponse.Session groupSession = new HistoryMessageSessionResponse.Session().setIsGroup(true).setName(String.format("%s 家庭群聊", child.getName())).setCid(child.getId()).setSid(group.getId().getId());

        Integer unreadCount = messageAdapter.unreadCount(userId, ChatSessionFactory.createGroupSessionId(group.getId()));
        groupSession.setUnreadCount(unreadCount);

        // Query the ID of the most recent message
        List<Message> unreadMessages = messageAdapter.findUnreadMessages(userId, ChatSessionFactory.createGroupSessionId(group.getId()));
        if (!unreadMessages.isEmpty()) {
            //获取最新的未读消息，因为这个列表未手动排序过，数据库是根据id排序，所以应该取最后一条
            Message message = unreadMessages.getLast();
            groupSession.setUnreadOldMsgId(message.getId().getId());
        } else {
            groupSession.setUnreadOldMsgId(0L);
        }

        List<HistoryMessageSessionResponse.SessionMember> groupMembers = new ArrayList<>();
        for (GroupMember groupMember : group.getMembers()) {
            HistoryMessageSessionResponse.SessionMember sessionMember = new HistoryMessageSessionResponse.SessionMember().setRefId(groupMember.getRefId()).setRefType(groupMember.getType().getValue()).setRefRole(groupMember.getRole().getValue());

            if (groupMember.getRefId().equals(child.getId())) {
                sessionMember.setName(child.getName());
                sessionMember.setAvatar(child.getAvatar());
            } else {
                // Find oneself in contacts
                Optional<ContactModel> oneself = contacts.stream().filter(ct -> ct.getRefId().equals(groupMember.getRefId())).findFirst();
                if (oneself.isPresent()) {
                    ContactModel contactModel = oneself.get();
                    sessionMember.setName(contactModel.getRemarkName());
                    sessionMember.setAvatar(contactModel.getRemarkAvatar());
                }

            }

            groupMembers.add(sessionMember);
        }
        groupSession.setMembers(groupMembers);

        // 最新的消息内容
        Message message = messageAdapter.find(new MessageId(groupSession.getUnreadOldMsgId()));
        if(Objects.nonNull(message)) {
            groupSession.setContent(message.getContent());
            if(Objects.nonNull(message.getType())) {
                groupSession.setMessageType(message.getType().getValue());
            }
        }

        return groupSession;
    }

    /**
     * APP端加载未读消息
     *
     * @param request 请求
     * @return 响应
     * @throws Exception 异常
     */
    @Transactional
    public HistoryUnreadMessageResponse appLoadUnread(HistoryUnreadMessageRequest request) {
        HistoryUnreadMessageResponse resp =  loadUnreadMessage(request,false);
        // 按 msgId 消息Id字段升序排序（从小到大）
        resp.getMsgs().sort(Comparator.comparing(HistoryUnreadMessageResponse.HistoryUnreadMessageResult::getMsgId));
        log.info("[APP端加载未读消息]请求参数：{}，用户id：{}，results消息：{}", JSONUtil.toJsonPrettyStr(request), CurrentRequestUser.get().getId(), JSONUtil.toJsonPrettyStr(resp));
        return resp;
    }

    /**
     * 加载未读消息
     *
     * @param request        请求
     * @param isOneClickRead 是否一键读取
     * @return
     */
    private HistoryUnreadMessageResponse loadUnreadMessage(HistoryUnreadMessageRequest request, Boolean isOneClickRead) {
        UserId userId = new UserId(CurrentRequestUser.get().getId());
        //会话ID=发送人 如果是群聊则是群聊ID
        List<Message> messages = messageAdapter.findUnreadMessages(userId, ChatSessionFactory.createSessionId(request.getSid(), request.getIsGroup()));
        //reversed() 降序
        messages = messages.stream().filter(message -> message.getId().greaterThan(request.getMsgId())).sorted(Comparator.comparing(Message::getId).reversed()).toList();
        int unreadMsgCount = messages.size();

        log.info("[加载未读消息]请求参数：{}，用户id：{}，消息：{}", JSONUtil.toJsonPrettyStr(request), userId, JSONUtil.toJsonPrettyStr(messages));

        List<HistoryUnreadMessageResponse.HistoryUnreadMessageResult> results = new ArrayList<>();
        for (int i = 0; i < Math.min(messages.size(), request.getMaxMsgSize()); i++) {
            Message unread = messages.get(i);
            unread.setReceivedLogs(messageAdapter.findReceivedLogs(unread.getId()));
            unread.setReceiverId(unread.getReceivedLogs().stream().map(MessageReceivedLog::getReceiverId).toList());

            // 群聊组
            boolean isGroup = request.getIsGroup();
            String groupId = StringUtils.EMPTY;
            String recvId;
            if (isGroup) {
                recvId = request.getSid();
                groupId = request.getSid();
            } else {
                recvId = unread.getReceiverId().getFirst();
            }

            HistoryUnreadMessageResponse.HistoryUnreadMessageResult result = new HistoryUnreadMessageResponse.HistoryUnreadMessageResult().setMsgId(unread.getId().getId()).setMsgType(unread.getType().getValue()).setSendTime(unread.getSendTime().toEpochMilli()).setSendId(unread.getSenderId()).setIsGroup(isGroup).setGroupId(groupId).setRecvId(recvId);

            Map<String, Object> content = new ObjectMapper().convertValue(unread.getContent(), ObjectMapperUtil.getValueTypeRef());
            result.setContent(content);

            //  log.info("loadUnread result: {} ，用户id：{}", JSONUtil.toJsonPrettyStr(unread.getReceivedLogs()),userId.getId());
            // Modify the message status to read status, and query again so that it will not be retrieved repeatedly.
            MessageReceivedLog messageReceivedLog = unread.getReceivedLogs().stream().filter(r -> r.getReceiverId().equals(userId.getId())).findFirst().orElseThrow(() -> new RuntimeException("The message does not need to be received by the user"));
            messageAdapter.markAsRead(messageReceivedLog);
            // log.info("loadUnread result: 更新已读成功");
            unreadMsgCount--;
            results.add(result);
        }

        log.info("[加载未读消息]请求参数：{}，用户id：{}，results消息：{}", JSONUtil.toJsonPrettyStr(request), userId, JSONUtil.toJsonPrettyStr(results));

        // 一键读取未读消息
       if(Objects.nonNull(isOneClickRead) && isOneClickRead) {
           myTaskExecutor.execute(() -> {
               List<Long> ackIdList = messageAdapter.findUnreadMessagesAckId(userId, ChatSessionFactory.createSessionId(request.getSid(), request.getIsGroup()));
               messageAdapter.markAsRead(ackIdList);
           });
       }


        return new HistoryUnreadMessageResponse().setUnreadMsgCount(unreadMsgCount).setMsgs(results);
    }

    /**
     * 手表端读取未读消息
     *
     * @param readUnreadMessageRequest  读取未读消息
     * @param isOneClickRead            是否一键读取
     * @param genericManufacturerHeader header
     * @return
     */
    @Transactional(rollbackOn = Exception.class)
    public HistoryUnreadMessageResponse wacthReadUnreadMessage(ReadUnreadMessageRequest readUnreadMessageRequest, Boolean isOneClickRead, GenericManufacturerHeader genericManufacturerHeader) {
        HistoryUnreadMessageRequest request = new HistoryUnreadMessageRequest();
        request.setSid(readUnreadMessageRequest.getSid());
        request.setIsGroup(readUnreadMessageRequest.getIsGroup());
        request.setMsgId(readUnreadMessageRequest.getMsgId());
        request.setMaxMsgSize(readUnreadMessageRequest.getMaxMsgSize());
        HistoryUnreadMessageResponse resp =  loadUnreadMessage(request, isOneClickRead);
        // 按 msgId 消息Id字段降序排序（从小大到小）
        resp.getMsgs().sort(Comparator.comparing(HistoryUnreadMessageResponse.HistoryUnreadMessageResult::getMsgId).reversed());
        log.info("[手表端读取未读消息]请求参数：{}，用户id：{}，results消息：{}", JSONUtil.toJsonPrettyStr(request), CurrentRequestUser.get().getId(), JSONUtil.toJsonPrettyStr(resp));
        return resp;

    }

}
