package main

import (
	"encoding/json"
	"flag"
	"log"
	mu "mfw/util"
	"net"
	"os"
	qutil "qfw/util"
	"qfw/util/mongodb"
	"time"
)

var startDate, endDate string

func main() {
	ip, p, tmptime, tmpkey, id1, id2, stype, q, bkey, param, ids := "", 0, 0, "", "", "", "", "", "", "", ""
	flag.StringVar(&startDate, "start", "", "开始日期2006-01-02")
	flag.StringVar(&endDate, "end", "", "结束日期2006-01-02")
	flag.StringVar(&ip, "ip", "127.0.0.1", "ip")
	flag.IntVar(&p, "p", 6601, "端口")
	flag.IntVar(&tmptime, "tmptime", 0, "时间查询")
	flag.StringVar(&tmpkey, "tmpkey", "", "时间字段")

	flag.StringVar(&id1, "gtid", "114168ea1a75b8f44678a39b", "gtid")
	flag.StringVar(&id2, "lteid", "9142e5741a75b8f4467b3276", "lteid")

	flag.StringVar(&ids, "ids", "", "id1,id2")
	flag.StringVar(&stype, "stype", "biddingall", "stype,传递类型")
	flag.StringVar(&bkey, "bkey", "", "bkey,加上此参数表示不生关键词和摘要")
	flag.StringVar(&q, "q", "", "q查询语句\"{'':''}\",有q就不要gtid,lteid")
	flag.StringVar(&param, "param", "", "param,生信息发布或其他索引时用双引号套单引号\"{'mgoaddr':'','d':'','c':'','index':'','type':''}\"")
	flag.Parse()
	//if startDate != "" || endDate != "" {
	//	start, _ := time.ParseInLocation(qutil.Date_Short_Layout, startDate, time.Local)
	//	end, _ := time.ParseInLocation(qutil.Date_Short_Layout, endDate, time.Local)
	//	id1 = qutil.BsonIdToSId(bson.NewObjectIdWithTime(start))
	//	id2 = qutil.BsonIdToSId(bson.NewObjectIdWithTime(end))
	log.Println(id1, id2, tmptime)
	//}
	if ip != "" && p > 0 && ((id1 != "" && id2 != "") || (q != "" || tmptime > 0)) {
		toadd := &net.UDPAddr{
			IP:   net.ParseIP(ip),
			Port: p,
		}
		udp := mu.UdpClient{Local: ":50010", BufSize: 1024}
		udp.Listen(func(b byte, data []byte, add *net.UDPAddr) {
			switch b {
			case mu.OP_NOOP:
				log.Println(string(data))
				os.Exit(0)
			}
		})
		m1 := map[string]interface{}{
			//"gtid":  id1,
			//"lteid": id2,
			"stype": stype,
		}
		if id1 != "" {
			m1["gtid"] = id1
		}
		if id2 != "" {
			m1["lteid"] = id2
		}
		if bkey != "" {
			m1["bkey"] = bkey
		}
		if ids != "" {
			m1["ids"] = ids
		}
		if q != "" {
			m1["query"] = mongodb.ObjToMQ(q, true) //qutil.ObjToMap(q)
		}
		if tmptime > 0 && tmpkey != "" {
			m1["query"] = map[string]interface{}{tmpkey: map[string]interface{}{"$gte": tmptime}}
		}
		if param != "" {
			pm := qutil.ObjToMap(param)
			for k, v := range *pm {
				m1[k] = v
			}
		}
		by, _ := json.Marshal(m1)
		udp.WriteUdp(by, mu.OP_TYPE_DATA, toadd)
		time.Sleep(30 * time.Second)
	} else {
		flag.PrintDefaults()
		log.Println("参数错误.")
	}
}
