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

import cn.axzo.framework.domain.web.result.ApiResult;
import cn.axzo.im.center.api.feign.MessageApi;
import cn.axzo.im.center.api.vo.req.SendTemplateMessageParam;
import cn.axzo.im.center.api.vo.resp.MessageTaskResp;
import cn.axzo.im.center.common.enums.AppTypeEnum;
import cn.axzo.msg.center.api.response.v3.MessageSendResultV3;
import cn.axzo.msg.center.api.response.v3.TemplateSendResultV3;
import cn.axzo.msg.center.common.utils.BizAssertions;
import cn.axzo.msg.center.dal.MessageRecordV3Dao;
import cn.axzo.msg.center.domain.entity.MessageRecordV3;
import cn.axzo.msg.center.inside.notices.service.impl.v3.EventMappingProcessor;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author yanglin
 */
@Slf4j
@Component
@Scope("prototype")
@RequiredArgsConstructor
public class MessageMappingProcessor implements EventMappingProcessor {

    private final MessageRecordV3Dao messageRecordV3Dao;
    private final TerminalAppMapping terminalAppMapping;
    private final MessageTemplateParser templateParser;
    private final MessageApi messageApi;

    /**
     * Scope("prototype") -> we're good
     */
    @Setter
    private TemplateMessage template;

    @Override
    public void saveRecords() {
        messageRecordV3Dao.saveBatch(template.getMessageRecords());
    }

    @Override
    public void maybeAsyncSend() {
        List<AppTypeEnum> appTypes = terminalAppMapping
                .toImTypes(template.getTemplate().getPushTerminals());
        BizAssertions.assertNotEmpty(appTypes, "发送IM消息, 消息模版没有配置IM发送终端, templateCode={}, templateName={}",
                template.getTemplate().getCode(), template.getTemplate().getName());
        SendTemplateMessageParam request = template.buildImRequest(templateParser, appTypes);
        ApiResult<MessageTaskResp> apiResult = messageApi.sendTemplateMessageAsync(request);
        log.info("sending im message result, req={}, resp={}",
                JSON.toJSONString(request), JSON.toJSONString(apiResult));
        if (apiResult.isSuccess()) {
            MessageTaskResp resp = apiResult.getData();
            messageRecordV3Dao.setSendSuccess(template.getMessageIds(), resp.getId() + "");
        } else {
            messageRecordV3Dao.batchSetSendFailed(template.getMessageIds(), apiResult.getMsg());
            log.warn("sending im message fail, req={}, resp={}",
                    JSON.toJSONString(request), JSON.toJSONString(apiResult));
        }
    }

    @Override
    public TemplateSendResultV3 buildTemplateSendResult() {
        TemplateSendResultV3 templateResult = new TemplateSendResultV3(
                template.getTemplateCode(), template.getConfig().getCategory());
        for (MessageRecordV3 message : template.getMessageRecords()) {
            templateResult.addResult(new MessageSendResultV3(
                    message.getReceiverPersonId(), message.getId()));
        }
        return templateResult;
    }

}