package com.quantgroup.asset.distribution.service.alarm.impl;

import java.util.HashMap;
import java.util.Map;

import cn.quantgroup.tech.util.TechEnvironment;
import com.quantgroup.asset.distribution.service.alarm.DingTalkMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.quantgroup.asset.distribution.service.alarm.IAlarmService;
import com.quantgroup.asset.distribution.service.httpclient.IHttpService;

import lombok.extern.slf4j.Slf4j;

/**
 * 报警接口
 * @author liwenbin
 *
 */
@Slf4j
@Service
public class AlarmServiceImpl implements IAlarmService{
	
	private static final String ALARM_HTTP_URL = "http://alertserv-dataservice.quantgroup.cn/common/alert/dingtalk";
	private static final String ROBOT_WEB_HOOK = "https://oapi.dingtalk.com/robot/send?access_token=f616b4f0892a98a20e8d989ec4f49b59075c3097143daa23eb54b6bb19337969";

	private static final String NEW_ALARM_URL = "https://oapi.dingtalk.com/robot/send?access_token=4af8824959a9f949b977ec67026d0404aa8152241c8c9722cc611726d6d33443";
	
	@Value("${alarmOpen}")
    private Boolean alarmOpen;
	@Autowired
	private IHttpService httpService;
	
	@Async
	@Override
	public void dingtalkAlarm(String alarmLevel, String msgTitle, String msgContent) {
		try {
			if (!alarmOpen) { return; }
			Map<String, String> params = new HashMap<>();
			params.put("webhook", ROBOT_WEB_HOOK);
			params.put("alarmLevel", alarmLevel);
			params.put("msgTitle", msgTitle);
			params.put("msgContent", msgContent);
			httpService.postNoResponse(ALARM_HTTP_URL, params);
		} catch (Exception e) {
			log.error("钉钉机器人报警异常, msg : {}", msgContent, e);
		}
	}


	@Async
	@Override
	public void sendMsgWithAlert(DingTalkMessage dingTalkMessage) {
		try {
			if (!TechEnvironment.isPro()){
				log.info("测试环境就别发送钉钉报警通知了，挺烦的，消息内容是: {}",dingTalkMessage.toJsonString());
				return;
			}
			if (dingTalkMessage instanceof MarkdownMessage){
				MarkdownMessage talkMessage = (MarkdownMessage) dingTalkMessage;
				talkMessage.addFirst("assert\n");
			}
			Map<String, String> params = new HashMap<>();
			String postJson = httpService.postJson(NEW_ALARM_URL, params);
			log.info("报警返回结果是 {}", postJson);
		} catch (Exception e) {
			log.error("[警告] 向钉钉发送消息异常.", e);
		}
	}
}
