/**
数据按小时划段入库
**/
package distribution

import (
	"encoding/json"
	"jy/extract"
	db "jy/mongodbutil"
	ju "jy/util"
	mu "mfw/util"
	"net"
	qu "qfw/util"
	"time"

	log "github.com/donnie4w/go-logger/logger"
	"gopkg.in/mgo.v2/bson"
)

//按小时id划段
func IdsRange(table, sdate, edate string) int {
	start, _ := time.ParseInLocation(qu.Date_Short_Layout, sdate, time.Local)
	end, _ := time.ParseInLocation(qu.Date_Short_Layout, edate, time.Local)
	nums := 0
	for start.Unix() <= end.Unix() {
		nums++
		timestr := start.Format("2006-01-02 15:04:05")
		sid := bson.NewObjectIdWithTime(start)
		start = start.Add(1 * time.Hour)
		eid := bson.NewObjectIdWithTime(start)
		db.Mgo.Save("esctask", map[string]interface{}{
			"timestr": timestr,
			"sid":     qu.BsonIdToSId(sid),
			"eid":     qu.BsonIdToSId(eid),
			"state":   0, //0待执行，1执行中，2完成
		})
	}
	return nums
}

//启动任务
func RunEcsTask() int {
	list, _ := db.Mgo.Find("ecs", `{"extstatus":"deploy"}`, nil, nil, false, -1, -1)
	num := 0
	for _, v := range *list {
		ip := qu.ObjToString(v["ip_nw"])
		by, _ := json.Marshal(map[string]interface{}{
			"ip":         ip,
			"InstanceId": v["InstanceId"],
			"stype":      "distributed",
		})
		err := extract.Udpclient.WriteUdp(by, mu.OP_TYPE_DATA, &net.UDPAddr{
			IP:   net.ParseIP(ip),
			Port: qu.IntAll(ju.Config["udpport"]),
		})
		if err != nil {
			log.Debug(err)
		} else {
			num++
			time.Sleep(2 * time.Second)
			log.Debug("分发任务", string(by))
		}
	}
	return num
}
