package cn.teammodel.manager.notification;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 钉钉告警服务
 * @author winter
 * @create 2023-11-14 10:11
 */
@Component
@Slf4j
public class DingAlertNotifier implements NotificationService{
    private final DingTalkClient client;
    @Autowired
    public DingAlertNotifier(@Value("${ding.server-url}") String dingServerUrl) {
        this.client = new DefaultDingTalkClient(dingServerUrl);
    }

    @Override
    public void send(String message) {
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        // 文本消息
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(message);
        request.setText(text);
        // at 管理员提醒异常
        OapiRobotSendRequest.At atAll = new OapiRobotSendRequest.At();
        atAll.setIsAtAll(true);
        request.setAt(atAll);
        try {
            client.execute(request);
        } catch (ApiException e) {
            log.error("钉钉 robot 推送消息渠道异常: {}", e.getMessage());
        }
    }
}
