package task

import (
	"qfw/util"
	"regexp"
	"sync"
	"time"
	"tools"
)

/**
增加数据监控服务，每15分钟保存一次抽取情况
**/
var IS = &InfoStatus{time.Now().Unix(), 0, map[string]map[string]int{}, &sync.Mutex{}, 0}

func StartMonitor() {
	go IS.Save()
}

type InfoStatus struct {
	Starttime int64
	Endtime   int64
	Val       map[string]map[string]int
	Lock      *sync.Mutex
	All       int
}

var mapinfo = map[string]map[string]string{}
var fieldkeys = []string{}
var repl = regexp.MustCompile("[tdp]$")

func init() {
	datamonitor := tools.Config["datamonitor"].([]interface{})
	for _, v := range datamonitor {
		if m1, ok := v.(map[string]interface{}); ok {
			class, _ := m1["class"].(string)
			fieldkeys = append(fieldkeys, class)
			mapinfo[class] = map[string]string{}
			if field, ok1 := m1["field"].([]interface{}); ok1 {
				for _, v2 := range field {
					if m2, ok2 := v2.(map[string]interface{}); ok2 {
						for _k, _v := range m2 {
							mapinfo[class][_k], _ = _v.(string)
						}
					}
				}
			}
		}
	}
}
func (is *InfoStatus) NewAdd(tt *TTask, info map[string]interface{}) {
	defer util.Catch()
	is.Lock.Lock()
	is.All++
	for _, k := range fieldkeys {
		v := info[k]
		if v != nil {
			if sv, ok := v.(string); ok {
				fcode := mapinfo[k][sv]
				if is.Val[k] == nil {
					is.Val[k] = map[string]int{}
				}
				if fcode == "" {
					fcode = "qt"
				}
				is.Val[k][fcode]++
			} else if sv, ok := v.([]string); ok {
				for _, sv1 := range sv {
					sv1 = repl.ReplaceAllString(sv1, "")
					fcode := mapinfo[k][sv1]
					if is.Val[k] == nil {
						is.Val[k] = map[string]int{}
					}
					if fcode == "" {
						fcode = "qt"
					}
					is.Val[k][fcode]++
				}
			}
			break
		}
	}
	is.Lock.Unlock()
}

func (is *InfoStatus) Save() {
	defer util.Catch()
	is.Lock.Lock()
	is.Endtime = time.Now().Unix()
	for k, v := range is.Val {
		save := map[string]interface{}{}
		all := is.All
		for k1, v1 := range v {
			save[k1] = v1
		}
		if all > 0 {
			save["receive"] = all
			save["starttime"] = is.Starttime
			save["endtime"] = is.Endtime
			save["flag"] = "class" + k
			go tools.MgoClass.Save("datamonitor", save)
		}
	}
	is.All = 0
	is.Val = map[string]map[string]int{}
	is.Starttime = is.Endtime
	is.Lock.Unlock()
	time.AfterFunc(15*time.Minute, is.Save)
}
