package org.tio.sitexxx.im.server.handler.wx.friend;

import org.tio.core.ChannelContext;
import org.tio.sitexxx.service.Command;
import org.tio.sitexxx.im.common.CommandHandler;
import org.tio.sitexxx.im.common.ImPacket;
import org.tio.sitexxx.im.common.bs.wx.friend.FriendMsgSyncReq;
import org.tio.sitexxx.im.common.bs.wx.friend.FriendMsgSyncResp;
import org.tio.sitexxx.im.server.Ims;
import org.tio.sitexxx.im.server.handler.AbsImServerHandler;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.model.main.WxFriendMsg;
import org.tio.sitexxx.service.service.chat.ChatMsgService;
import org.tio.sitexxx.service.service.chat.FriendService;
import org.tio.sitexxx.service.service.ConfService;
import org.tio.sitexxx.service.vo.SimpleUser;
import org.tio.utils.json.Json;

import java.util.List;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2025-04-08 09:53
 *    desc   : 好友消息同步请求
 * </pre>
 */
@CommandHandler(Command.FriendMsgSyncReq)
public class FriendMsgSyncReqHandler extends AbsImServerHandler {
    @Override
    public void handler(ImPacket packet, ChannelContext channelContext, boolean isWebsocket, User curr, SimpleUser currSimpleUser) throws Exception {
        FriendMsgSyncReq msgReq = Json.toBean(packet.getBodyStr(), FriendMsgSyncReq.class);
        Long chatLinkId = msgReq.getChatLinkId();
        Long syncMid = msgReq.getSyncMid();
        List<WxFriendMsg> data = ChatMsgService.me.p2pMsgSyncList(chatLinkId, curr.getId(), syncMid, msgReq.getStartMid());
        FriendMsgSyncResp friendMsgSyncResp = new FriendMsgSyncResp();
        friendMsgSyncResp.setData(data);
        friendMsgSyncResp.setChatLinkId(chatLinkId);
        if (data.size() < ConfService.getInt("im.history.chat.count.p2p", FriendService.WX_FRIEND_MSG_LIMIT)) {
            friendMsgSyncResp.setLastPage(true);
        }
        ImPacket imPacket = new ImPacket(Command.FriendMsgSyncResp, friendMsgSyncResp);
        Ims.send(channelContext, imPacket);
    }
}
