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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.group.GroupMsgSyncReq;
import org.tio.sitexxx.im.common.bs.wx.group.GroupMsgSyncResp;
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.WxChatGroupItem;
import org.tio.sitexxx.service.model.main.WxGroupMsg;
import org.tio.sitexxx.service.service.chat.ChatIndexService;
import org.tio.sitexxx.service.service.chat.ChatMsgService;
import org.tio.sitexxx.service.service.chat.GroupService;
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-10 14:10
 *    desc   : 群聊消息同步
 * </pre>
 */
@CommandHandler(Command.GroupMsgSyncReq)
public class GroupMsgSyncReqHandler extends AbsImServerHandler {
    private static Logger log = LoggerFactory.getLogger(GroupMsgSyncReqHandler.class);
    @Override
    public void handler(ImPacket packet, ChannelContext channelContext, boolean isWebsocket, User curr, SimpleUser currSimpleUser) throws Exception {
        GroupMsgSyncReq msgReq = Json.toBean(packet.getBodyStr(), GroupMsgSyncReq.class);
        Long chatLinkId = Math.abs(msgReq.getChatLinkId());
        Long startMid = msgReq.getStartMid();
        Long syncMid = msgReq.getSyncMid();
        WxChatGroupItem groupItem = ChatIndexService.chatGroupIndex(curr.getId(), chatLinkId);
        if (groupItem == null || groupItem.getChatlinkid() == null) {
            return;
        }
        chatLinkId = groupItem.getChatlinkid();
        List<WxGroupMsg> list = ChatMsgService.me.groupMsgSyncList(chatLinkId, groupItem.getGroupid(), curr.getId(), syncMid, startMid);
        GroupMsgSyncResp msgResp = new GroupMsgSyncResp();
        msgResp.setData(list);
        if (list.size() < ConfService.getInt("im.history.chat.count.group", GroupService.GROUP_MSG_LIMIT)) {
            msgResp.setLastPage(true);
        }
        msgResp.setChatLinkId(-groupItem.getGroupid());
        ImPacket imPacket = new ImPacket(Command.GroupMsgSyncResp, msgResp);
        Ims.send(channelContext, imPacket);
    }
}

