package com.dd.admin.business.webSocket.handler;

import cn.hutool.core.bean.BeanUtil;
import com.dd.admin.business.chat.domain.ChatVo;
import com.dd.admin.business.chat.domain.MessageBean;
import com.dd.admin.business.chat.entity.Chat;
import com.dd.admin.business.chat.service.ChatService;
import com.dd.admin.business.webSocket.MsgHandlerInterface;
import com.dd.admin.business.webSocket.util.TioUtil;
import com.dd.admin.common.utils.AddressUtils;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.tio.core.ChannelContext;

import java.util.Map;

import static com.dd.admin.business.webSocket.WsConst.HANDLER_CHAT;


@Component
@Slf4j
@Service("6")
public class ServiceMessageHandler implements MsgHandlerInterface {

    public static ServiceMessageHandler handler;

    @Autowired
    ChatService chatService;


    @Override
    public Object handler(Map map, ChannelContext context ){
        System.out.println(map);
        MessageBean messageBean = BeanUtil.toBean(map, MessageBean.class);

        //xx发送人
        MessageBean.FromUser fromUser = messageBean.getFromUser();
        Chat chat = new Chat();
        chat.setFromId(fromUser.getId());
        chat.setFromName(fromUser.getDisplayName());
        chat.setToId(messageBean.getToContactId());
        chat.setContent(messageBean.getContent());
        chat.setIpAddress(context.getClientNode().getIp());
        chat.setIpRealAddress(AddressUtils.getRealAddress(chat.getIpAddress())); //ip真实地址
        chatService.save(chat);
        ChatVo chatVo = chatService.selectChat(chat.getChatId());
        //如果对方是移动端则按照移动端消息格式推送
        TioUtil.sendChatMessageToUser(context.getGroupContext(),chat.getToId(),HANDLER_CHAT,chatVo);

        //还需要推送给客服自己
//        TioUtil.sendChatMessageToUser(context.getGroupContext(),chat.getFromId(),"6",messageBean);

        return null;
    }}
