package cn.axzo.msg.center.inside.notices.service.impl.v3;

import cn.axzo.msg.center.api.request.v3.MessageSendReqV3;
import cn.axzo.msg.center.api.request.v3.PendingSendInfo;
import cn.axzo.msg.center.api.response.v3.MessageSendRespV3;
import cn.axzo.msg.center.common.utils.BizAssertions;
import cn.axzo.msg.center.inside.notices.service.MessageServiceV3;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author yanglin
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MessageServiceV3Impl implements MessageServiceV3 {

    private final ActionClient actionClient;

    /**
     * 过渡期. 有一个逻辑上的循环依赖. 等业务方都切换到event-hub的接口后将这个接口下线
     */
    @Override
    public MessageSendRespV3 send(MessageSendReqV3 request) {
        // 1. 发送消息/待办的请求
        JSONObject messageSendRequest = new JSONObject();
        // 2. 设置基本的发送消息的属性
        messageSendRequest.put("sendBasicInfo", request);
        // 3. 设置发送待办的信息
        PendingSendInfo pendingInfo = request.getChannelParam(
                MessageSendReqV3.CHANNEL_PENDING, PendingSendInfo.class);
        messageSendRequest.put("pendingSendInfo", pendingInfo);
        // 4. 构建event-hub的请求
        JSONObject performActionRequest = new JSONObject();
        performActionRequest.put("eventCode", request.getBizEventMappingCode());
        performActionRequest.put("messageSendRequest", messageSendRequest);
        // 5. 调用event-hub的接口
        JSONObject response = actionClient.performAction(performActionRequest);
        log.info("actionClient.performAction, request={}, resp={}", performActionRequest, response);
        BizAssertions.assertTrue(response.getIntValue("code") == 200, response.getString("msg"));
        return response
                .getJSONObject("data")
                .getObject("messageSendResp", MessageSendRespV3.class);
    }

}