package alarm

import (
	"encoding/json"
	"git.quantgroup.cn/DevOps/enoch/service/log"
	"git.quantgroup.cn/DevOps/enoch/service/util"
	"net/http"
	"strings"
	"sync"
	"time"
)

var SenderWatcher sync.Map

func Sender(target []string, title string, info string, notice Notice) {
	uniqueKey := buildUniqueKey(target)
	if !isExpired(uniqueKey, notice.Interval) { //小于报警周期
		return
	}
	info = uniqueKey + info
	switch notice.Sender {
	case DING_DING:
		senderDingDing(title, info, notice.Receiver)
		break
	case MAIL:
		senderMail(title, info, notice.Receiver)
	default:
		logger.Error.Println("策略配置错误，未匹配到对应的Sender")
	}
}

func senderMail(title string, info string, receiver []string) {
	for _, r := range receiver {
		util.SendEmail(title, info, r)
	}
}

func senderDingDing(title string, info string, receiver [] string) {
	bodyStr := buildDingDingMsg(title, info)

	for _, r := range receiver {
		data := strings.NewReader(string(bodyStr))
		_, err := http.Post(r, "application/json;charset=utf-8", data)
		if err != nil {
			logger.Error.Println(err)
		}
	}
}



func buildDingDingMsg(title string, info string) []byte {
	msg := DinDingMsg{
		MsgType: "link",
		Link: Link{
			Title:      title,
			Text:       info,
			MessageUrl: "http://172.20.6.33:3000/d/y1Ju2slik/apdexlist?refresh=1m&orgId=1",
		},
	}

	msgStr, err := json.Marshal(msg)
	if nil != err {
		logger.Error.Println("无法序列化ding ding msg", err)
	}
	return msgStr

}

/**
判断是否符合报警的时间间隔
 */
func isExpired(key string, interval int64) bool {
	now := time.Now().Unix()
	lastTime, hasValue := SenderWatcher.LoadOrStore(key, now)
	logger.Info.Println("---------时间间隔：old:", lastTime, ",new:", now)
	if hasValue { // 存在旧值，判断是否过期
		if now-lastTime.(int64) >= interval { //过期
			SenderWatcher.Store(key, now)
			return true
		}
		return false
	}
	return true
}

func buildUniqueKey(target []string) string {
	length := len(target)
	str := strings.Builder{}
	for i := length - 1; i >= 0; i-- {
		str.WriteString(target[i])
		str.WriteString(":")
	}
	return str.String()
}

/**
	持久化报警
 */
func persistence() {

}
