package info

import (
	"cluster"
	"config"
	"fmt"
	"gopkg.in/mgo.v2/bson"
	"qfw/util"
	"qfw/util/mongodb"
	"time"
)

func QueryInfo() map[string]interface{} {
	now := time.Now()
	data := make(map[string]interface{})
	//config.Sys.Lock()
	//data["isrun"] = config.IsRun
	//config.Sys.Unlock()
	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 data
	}
	data["taskNum"] = taskNum
	sumNum := 0
	nowSumNum := 0
	var stime time.Time
	resultInfos := make([]map[string]interface{}, 0)
	for i, v := range *taskArr {
		sid := bson.ObjectIdHex(util.ObjToString(v["start"]))
		eid := bson.ObjectIdHex(util.ObjToString(v[util.ObjToString(config.EidField)]))
		tmpSumNum := mongodb.Count("bidding", bson.M{"_id": bson.M{
			"$gte": sid,
			"$lte": eid,
		}})
		v["sub"] = tmpSumNum
		v["i_time"] = time.Unix(util.Int64All(v["import_time"]),0).String()
		resultInfos = append(resultInfos, v)
		sumNum += tmpSumNum
		if i == 0 {
			nowSumNum = sumNum
			tmptime := util.Int64All(v["import_time"])
			stime = time.Unix(tmptime,0)
		}
	}
	data["sumNum"] = sumNum
	data["nowSumNum"] = nowSumNum
	tmpsid := bson.ObjectIdHex(util.ObjToString((*taskArr)[0]["start"]))
	over := (*taskArr)[0][util.ObjToString(config.SidField)]
	overNum := mongodb.Count("bidding", bson.M{"_id": bson.M{
		"$gte": tmpsid,
		"$lt":  bson.ObjectIdHex(util.ObjToString(over)),
	}})
	data["overNum"] = overNum
	undoneNum := sumNum - overNum
	data["undoneNum"] = undoneNum
	nowUnDoneNum := nowSumNum - overNum
	data["nowUnDoneNum"] = nowUnDoneNum

	since := time.Since(stime)
	data["executionTime"] = since.String()
	//log.Println(now.Sub(stime).Seconds())
	cluster.DescribeInstances()
	cnum:=0
	cluster.CID.Range(func(key, value interface{}) bool {
		cnum+=1
		return true
	})
	mtmm := float64(overNum) / now.Sub(stime).Seconds() / float64(3+cnum)
	//log.Println(overNum ,now.Sub(stime).Seconds(),3+len(config.CID),mtmm)
	tmpf := float64(nowSumNum) / mtmm / float64(3+cnum)
	//log.Println(nowSumNum,mtmm,tmpf)
	data["estimatedFinishTime"] = now.Add(time.Second*time.Duration(tmpf)).String()
	data["esc"] = fmt.Sprint(3 ,"+", cnum)
	data["resultInfos"] = resultInfos
	//log.Println(resultInfos)
	return data
}
