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.jutil.jdk.thread.ThreadPoolWrapper;
import cn.reghao.tnb.message.app.service.notifier.Notify;
import cn.reghao.tnb.message.app.service.notifier.ding.DingMsg;
import cn.reghao.tnb.message.app.service.notifier.ding.DingNotify;
import cn.reghao.tnb.message.app.service.notifier.email.EmailMsg;
import cn.reghao.tnb.message.app.service.notifier.email.EmailNotify;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;

/**
 * 通知服务
 *
 * @author reghao
 * @date 2021-02-25 00:10:17
 */
@Slf4j
@Service
public class NotifyService {
    @DubboReference(check = false, retries = 0)
    private AdminService adminService;

    private final ExecutorService threadPool = ThreadPoolWrapper.threadPool("notify-service");
    private final DingNotify dingNotify;
    private final EmailNotify emailNotify;

    public NotifyService(DingNotify dingNotify, EmailNotify emailNotify) {
        this.dingNotify = dingNotify;
        this.emailNotify = emailNotify;
    }

    public <T> void notify(String receiver, T msg) {
        if (msg instanceof DingMsg) {
            DingMsg dingMsg = (DingMsg) msg;
            threadPool.execute(new NotifyTask<>(dingNotify, receiver, dingMsg, adminService));
        } else if (msg instanceof EmailMsg) {
            EmailMsg emailMsg = (EmailMsg) msg;
            threadPool.execute(new NotifyTask<>(emailNotify, receiver, emailMsg, adminService));
        }
    }
    /**
     * @param
     * @return
     * @date 2021-06-23 上午9:29
     */
    static class NotifyTask<T> implements Runnable {
        private final Notify<T> notify;
        private final String receiver;
        private final T msg;
        private final AdminService adminService;

        public NotifyTask(Notify<T> notify, String receiver, T msg, AdminService adminService) {
            this.notify = notify;
            this.receiver = receiver;
            this.msg = msg;
            this.adminService = adminService;
        }

        @Override
        public void run() {
            try {
                notify.send(receiver, msg);
            } catch (Exception e) {
                String errMsg = String.format("发送给 %s 的通知失败 -> %s", receiver, e.getMessage());
                AdminMessage adminMessage = new AdminMessage(2, errMsg);
                adminService.sendAdminMessage(adminMessage);
            }
        }
    }
}
