package udptask

import (
	"fmt"
	"io/ioutil"
	"log"
	mu "mfw/util"
	"net/http"
	"sync"
	"time"
	. "tools"
)

var udptaskmap = &sync.Map{}
var tomail string
var api string

func checkMapJob() {
	//阿里云内网无法发送邮件
	jkmail, _ := Config["jkmail"].(map[string]interface{})
	if jkmail != nil {
		tomail, _ = jkmail["to"].(string)
		api, _ = jkmail["api"].(string)
	}
	log.Println("start checkMapJob", tomail, jkmail)
	for {
		udptaskmap.Range(func(k, v interface{}) bool {
			now := time.Now().Unix()
			node, _ := v.(*UdpNode)
			if now-node.Timestamp > 120 {
				node.Retry++
				if node.Retry > 5 {
					log.Println("udp重试失败", k)
					udptaskmap.Delete(k)
					res, err := http.Get(fmt.Sprintf("%s?to=%s&title=%s&body=%s", api, tomail, "classification-send-fail", k.(string)))
					if err == nil {
						defer res.Body.Close()
						read, err := ioutil.ReadAll(res.Body)
						log.Println("邮件发发送：", string(read), err)
					}
				} else {
					log.Println("udp重发", k)
					Udpclient.WriteUdp(node.Data, mu.OP_TYPE_DATA, node.Addr)
				}
			} else if now-node.Timestamp > 10 {
				log.Println("udp任务超时中..", k)
			}
			return true
		})
		time.Sleep(60 * time.Second)
	}
}
