// main
package config

import (
	"fmt"
	"gopkg.in/mgo.v2/bson"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"qfw/util"
	"qfw/util/mongodb"
	"time"
)

func SendEmail() {
	sleeptime := 10
	for {
		b := check()
		if b {
			sleeptime = 60
		} else {
			sleeptime = 10
		}
		time.Sleep(time.Duration(sleeptime) * time.Minute)
	}
	lock := make(chan bool)
	<-lock
}

func check() bool {
	send := false
	mongodb.Count("qfw", "")
	taskArr := mongodb.Find("ocr_task", bson.M{"isrun": bson.M{
		"$ne": "stop",
	}}, `{_id:1}`, nil, false, -1, -1)
	taskNum := len(*taskArr)
	if taskNum == 0 {
		return false
	}
	var sumNum int = 0
	for _, v := range *taskArr {
		sumNum += mongodb.Count("bidding", bson.M{"_id": bson.M{
			"$gte": bson.ObjectIdHex(util.ObjToString(v["gtid"])),
			"$lte": bson.ObjectIdHex(util.ObjToString(v[util.ObjToString(EidField)])),
		}})
	}
	var content = ""
	if sumNum > 10000 {
		content = "附件识别积累任务超过1W条,当前积累"+fmt.Sprint(sumNum)
	}

	if len(content) > 0 {
		sendMail(content)
		send = true
	}
	return send
}

func sendMail(content string) {
	res, err := http.Get(fmt.Sprintf("%s?to=%s&title=%s&body=%s", api, tomail, "udp_ocr_conter", "附件识别检测异常："+content))
	defer res.Body.Close()
	if err == nil {
		read, err := ioutil.ReadAll(res.Body)
		log.Println("邮件发送：", string(read), err)
	}
}

func netStatus(addr string) bool {
	_, err := net.DialTimeout("tcp", addr, time.Second*3)
	if err != nil {
		return false
	}
	return true
}
