package cn.axzo.msg.center.api.response.v3;

import com.alibaba.fastjson.JSON;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author yanglin
 */
@Data
public class TemplateSendResultV3 implements Serializable {
    /**
     * 模版编码
     */
    private String templateCode;

    /**
     * 渠道
     * <p>NOTIFICATION: 通知, PENDING: 待办
     */
    private String channel;

    /**
     * 接收者personId -> 接收人发送结果
     * key: string, 兼容json的key必须为string类型
     */
    private Map<String, MessageSendResultV3> receiverPersonId2SendResult;

    @SuppressWarnings("unused")
    public TemplateSendResultV3() {
    }

    public TemplateSendResultV3(String templateCode, String channel) {
        this.templateCode = templateCode;
        this.channel = channel;
        this.receiverPersonId2SendResult = new HashMap<>();
    }

    public void addResult(MessageSendResultV3 result) {
        if (receiverPersonId2SendResult == null)
            // 序列化问题
            throw new RuntimeException("需要通过构造函数初始化receiverPersonId2SendResult");
        String receiverPersonId = String.valueOf(result.getReceiverPersonId());
        receiverPersonId2SendResult.put(receiverPersonId, result);
    }

    public Optional<MessageSendResultV3> findResultByReceiver(Long receiverPersonId) {
        if (receiverPersonId2SendResult == null)
            return Optional.empty();
        if (receiverPersonId == null)
            return Optional.empty();
        String strReceiverPersonId = String.valueOf(receiverPersonId);
        return Optional.ofNullable(receiverPersonId2SendResult.get(strReceiverPersonId));
    }

    /**
     * 返回的数量不一定和发送请求中的receivers数量一致, 发送的时候根据receiver的personId去了重
     * <p>推荐使用 {@link #findResultByReceiver}, 根据接收者获取发送结果
     *
     * @return 所有的发送结果
     */
    public Collection<MessageSendResultV3> messageSendResults() {
        if (receiverPersonId2SendResult == null)
            return Collections.emptyList();
        return new ArrayList<>(receiverPersonId2SendResult.values());
    }

    @Override
    public String toString() {
        return JSON.toJSONString(receiverPersonId2SendResult);
    }
}