package main

import (
	"encoding/json"
	"log"
	mu "mfw/util"
	"net"
	"qfw/util"
	. "qfw/util/mongodb"
	"time"
)

var (
	Sysconfig   map[string]interface{} //配置文件
	brandMgo    *MongodbSim            //mongodb操作对象
	appendixMgo *MongodbSim            //mongodb操作对象
	udpclient   mu.UdpClient           //udp对象
	udpport     string                 //udp端口
	pool        int                    //并发数
	savesize    int
	//品牌库信息
	brandMgodb    string
	brandDbname   string
	brandDbsize   int
	brandCollname string
	//附件库信息
	appendixMgodb    string
	appendixDbname   string
	appendixDbsize   int
	appendixCollname string
)

func init() {
	util.ReadConfig("config.json", &Sysconfig)
	udpport, _ = Sysconfig["udpport"].(string)
	pool = util.IntAllDef(Sysconfig["pool"], 5)
	savesize = util.IntAllDef(Sysconfig["savesize"], 200)
	//品牌库
	brand := Sysconfig["brand"].(map[string]interface{})
	brandMgodb, _ = brand["mgodb"].(string)
	brandDbname, _ = brand["dbname"].(string)
	brandDbsize = util.IntAllDef(brand["dbsize"], 5)
	brandCollname, _ = brand["collname"].(string)
	brandMgo = &MongodbSim{
		MongodbAddr: brandMgodb,
		Size:        brandDbsize,
		DbName:      brandDbname,
	}
	brandMgo.InitPool()
	//附件库
	appendix := Sysconfig["appendix"].(map[string]interface{})
	appendixMgodb, _ = appendix["mgodb"].(string)
	appendixDbname, _ = appendix["dbname"].(string)
	appendixDbsize = util.IntAllDef(appendix["dbsize"], 5)
	appendixCollname, _ = appendix["collname"].(string)
	appendixMgo = &MongodbSim{
		MongodbAddr: appendixMgodb,
		Size:        appendixDbsize,
		DbName:      appendixDbname,
	}

	appendixMgo.InitPool()
	//初始化品牌库
	InitBrand()

}
func main() {
	log.Println("udpport", udpport)
	udpclient = mu.UdpClient{Local: ":" + udpport, BufSize: 1024}
	udpclient.Listen(processUdpMsg)
	log.Println("Udp服务监听", udpport)
	time.Sleep(99999 * time.Hour)
}

func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
	defer util.Catch()
	switch act {
	case mu.OP_TYPE_DATA: //上个节点的数据
		var mapInfo map[string]interface{}
		err := json.Unmarshal(data, &mapInfo)
		log.Println("err:", err, "mapInfo:", mapInfo)
		if err != nil {
			udpclient.WriteUdp([]byte("err:"+err.Error()), mu.OP_NOOP, ra)
		} else if mapInfo != nil {
			sid, _ := mapInfo["gtid"].(string)
			eid, _ := mapInfo["lteid"].(string)
			udpclient.WriteUdp([]byte("udpok"), mu.OP_NOOP, ra)
			UdpTask(sid, eid)
		}
	case mu.OP_NOOP: //下个节点回应
		ok := string(data)
		if ok != "" {
			log.Println("ok:", ok)
		}
	}
}
