package main

import (
	"encoding/json"
	log "github.com/donnie4w/go-logger/logger"
	mu "mfw/util"
	"net"
	qu "qfw/util"
	"sync"
	"time"
)

var (
	udpclient    		mu.UdpClient
	udplock 			sync.Mutex
	data_mgo     		*MongodbSim
)
func initMgo()  {
	data_mgo = &MongodbSim{
		MongodbAddr: "172.17.145.163:27083,172.17.4.187:27082",
		DbName:      "qfw",
		Size:        3,
		UserName: "zhengkun",
		Password: "zk@123123",
	}
	data_mgo.InitPool()
}
func init() {
	udpclient = mu.UdpClient{Local: ":6500", BufSize: 1024}
	udpclient.Listen(processUdpMsg)
	log.Debug("Udp服务监听", ":6500")
	initMgo()
}

func main()  {
	sendUdp()//模拟第一次先发一次

	lock := make(chan bool)
	<-lock
}

func getSidAndEid()(string,string)  {
	//ocr_goods_over
	sess := data_mgo.GetMgoConn()
	defer data_mgo.DestoryMongoConn(sess)
	q:=map[string]interface{}{
		"is_repeat_status":1,
	}
	sid,eid := "",""
	it := sess.DB(data_mgo.DbName).C("ocr_goods_over").Find(&q).Sort("-_id").Iter()
	for tmp := make(map[string]interface{}); it.Next(&tmp); {
		sid = qu.ObjToString(tmp["gtid"])
		eid = qu.ObjToString(tmp["lteid"])
		tmp = make(map[string]interface{})
		break
	}
	return sid,eid
}

func sendUdp()  {
	sid,eid := getSidAndEid()
	if sid!=""&&eid!=""{
		log.Debug("获取当前有效：",sid,"~",eid)
		by, _ := json.Marshal(map[string]interface{}{
			"gtid":  sid,
			"lteid": eid,
			"stype": "simulate_udp_start",
		})
		udpclient.WriteUdp(by, mu.OP_TYPE_DATA, &net.UDPAddr{
			IP:   net.ParseIP("172.17.4.238"),
			Port: 6600,
		})
	}else {
		log.Debug("获取当前无效")
	}
}

//udp接收
func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
	switch act {
	case mu.OP_TYPE_DATA:
		var mapInfo map[string]interface{}
		err := json.Unmarshal(data, &mapInfo)
		if err != nil {
			udpclient.WriteUdp([]byte("err:"+err.Error()), mu.OP_NOOP, ra)
		} else if mapInfo != nil {
			stype, _ := mapInfo["stype"].(string)
			log.Debug(stype,"重新获取段落~~~")
			log.Debug("休息~5分钟")
			time.Sleep(time.Second*300)
			sendUdp()
		}
	case mu.OP_NOOP: //下个节点回应
		str := string(data)
		log.Debug("接收成功回应：",str)
	}
}




