package com.wecloud.im.post;

import io.geekidea.springbootplus.framework.common.api.ApiCode;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import lombok.AllArgsConstructor;

import java.util.Date;

import org.springframework.stereotype.Service;

import com.wecloud.im.entity.ImClient;
import com.wecloud.im.entity.ImMessage;
import com.wecloud.im.entity.ImMessageOnlineSend;
import com.wecloud.im.ws.enums.WsResponseCmdEnum;
import com.wecloud.im.ws.model.WsResponse;
import com.wecloud.im.ws.sender.ChannelSender;

/**
 * 投递员 负责投送消息
 * @Author luozh
 * @Date 2022年05月13日 14:19
 * @Version 1.0
 */
@AllArgsConstructor
@Service
public class Couriers {

    private final ChannelSender channelSender;

    /**
     * 投递消息
     * @Author luozh
     * @Date 2022年05月13日 02:34:29
     * @param message 消息实体
     * @param sender 发件人
     * @param receiver 收件人
     * @param cmd ws命令类型
     * @Return
     */
    public void deliver(ImMessage message, Object content, ImClient sender, ImClient receiver, WsResponseCmdEnum cmd) {
        // 封装响应的实体
        ImMessageOnlineSend imMessageOnlineSend = new ImMessageOnlineSend();

        imMessageOnlineSend.setMsgId(message.getId());
        imMessageOnlineSend.setCreateTime(new Date());
        imMessageOnlineSend.setType(message.getMsgType());
        imMessageOnlineSend.setSender(sender.getClientId());
        imMessageOnlineSend.setContent(content);
        imMessageOnlineSend.setConversationId(message.getFkConversationId());
        imMessageOnlineSend.setWithdraw(message.getWithdraw());
        imMessageOnlineSend.setEvent(message.getEvent());

        //  向接收方推送
        WsResponse<ImMessageOnlineSend> responseModel = new WsResponse<>();
        responseModel.setCmd(cmd.getCmdCode());
        ApiResult<Boolean> result = ApiResult.result(ApiCode.SUCCESS);
        responseModel.setCode(result.getCode());
        responseModel.setMsg(result.getMessage());
        responseModel.setData(imMessageOnlineSend);
        responseModel.setReqId(null);
        channelSender.sendMsg(responseModel, receiver.getId());
    }
}
