package main

import (
	"bytes"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"sync"
	"time"
)

var (
	WarningList     = make(map[string]string) // 存储 IP 和位置的映射
	WarningListLock = sync.RWMutex{}

	dingtalkWebhook = "https://oapi.dingtalk.com/robot/send?access_token=7f069c672cb878987aa6772cca336740eece4ce36bde12b51b45e9f440e0565a" // 替换为你的 token
)

// 发送钉钉 Markdown 消息
func sendDingTalkMessage(title, text string) {
	if len(text) > 1900 {
		text = text[:1900] + "\n...(内容过长，已截断)"
	}

	msg := map[string]interface{}{
		"msgtype": "markdown",
		"markdown": map[string]string{
			"title": title,
			"text":  "### Warning " + title + "\n" + text,
		},
	}

	jsonData, err := json.Marshal(msg)
	if err != nil {
		log.Println("JSON 编码失败:", err)
		return
	}

	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Post(dingtalkWebhook, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Println("发送钉钉消息失败:", err)
		return
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	var result map[string]interface{}
	if err := json.Unmarshal(body, &result); err != nil {
		log.Println("解析钉钉响应失败:", err)
		return
	}

	if result["errcode"].(float64) != 0 {
		log.Println("钉钉返回错误:", result["errmsg"])
	} else {
		log.Println("钉钉告警已发送成功")
	}
}

func warning_ding(ipStr string, position string) {
	WarningListLock.Lock()
	defer WarningListLock.Unlock()

	WarningList[ipStr] = position

	if len(WarningList) == 1000 {
		var content string
		for ip, pos := range WarningList {
			line := "- " + ip + ", " + pos + "\n"
			content += line
			log.Println(ip, pos)
		}

		log.Println("警告列表已满，发送钉钉告警并清空 map")

		//go sendDingTalkMessage("⚠️ 告警列表达到上限"+local_ipv4_addr, content)

		// 清空 map
		WarningList = make(map[string]string)
	}
}
