package cn.reghao.tnb.message.app.service;

import cn.reghao.bnt.admin.api.dto.AdminMessage;
import cn.reghao.bnt.admin.api.iface.AdminService;
import cn.reghao.tnb.message.api.constant.NotifyType;
import cn.reghao.tnb.message.api.dto.msg.BaseMessage;
import cn.reghao.tnb.message.api.dto.msg.LoginMessage;
import cn.reghao.tnb.message.api.dto.msg.VerifyMessage;
import cn.reghao.tnb.message.app.service.notifier.email.EmailMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

/**
 * @author reghao
 * @date 2023-08-28 13:55:03
 */
@Slf4j
@Service
public class MessageConsumer {
    @DubboReference(check = false, retries = 0)
    private AdminService adminService;
    private final NotifyService notifyService;

    public MessageConsumer(NotifyService notifyService) {
        this.notifyService = notifyService;
    }

    public void sendMessage(BaseMessage baseMessage) {
        if (baseMessage instanceof LoginMessage) {
            LoginMessage loginMessage = (LoginMessage) baseMessage;
            int notifyType = loginMessage.getNotifyType();
            String receiver = loginMessage.getReceiver();
            if (notifyType == NotifyType.email.getValue()) {
                String subject = loginMessage.getTitle();
                String content = String.format("您的帐号在 %s 通过客户端 %s 登录, 登录 IP 为 %s", loginMessage.getLoginAt(), loginMessage.getUserAgent(), loginMessage.getPublicIp());
                EmailMsg emailMsg = new EmailMsg(subject, content);
                notifyService.notify(receiver, emailMsg);
            } else if (notifyType == NotifyType.mobile.getValue()) {
                String errMsg = "短信消息尚未实现";
                AdminMessage adminMessage = new AdminMessage(2, errMsg);
                adminService.sendAdminMessage(adminMessage);
            }
        } else if (baseMessage instanceof VerifyMessage) {
            VerifyMessage verifyMessage = (VerifyMessage) baseMessage;
            int notifyType = verifyMessage.getNotifyType();
            if (notifyType == NotifyType.email.getValue()) {
                String receiver = verifyMessage.getReceiver();
                EmailMsg emailMsg = new EmailMsg(verifyMessage.getTitle(), verifyMessage.getContent());
                notifyService.notify(receiver, emailMsg);
            } else if (notifyType == NotifyType.mobile.getValue()) {
                String errMsg = "短信验证码尚未实现";
                AdminMessage adminMessage = new AdminMessage(2, errMsg);
                adminService.sendAdminMessage(adminMessage);
            }
        }
    }
}
