package main

import (
	"bytes"
	"encoding/json"
	"ext"
	log "github.com/donnie4w/go-logger/logger"
	"gopkg.in/mgo.v2/bson"
	"io"
	"net/http"
	qu "qfw/util"
	"service"
	"time"
	ul "util"
)

func init() {
	ul.InitExt()
	ext.Ext = &ext.ExtractTask{}
	ext.Ext.InitCityInfo() //初始化-抽取城市
	qu.ReadConfig("./res/regions.json", &ext.RegionsConfig)
	ext.DefaultRegions = ext.ConvertInterface(ext.RegionsConfig["default_regions"])
	ext.AdjustmentRegions = ext.ConvertInterface(ext.RegionsConfig["adjustment_regions"])
	log.Debug("地域模型数据加载完毕~~~")
	service.InitRegionsService()
	log.Debug("开始监听~", ul.Port)
	go http.ListenAndServe(ul.Port, nil)
}
func main() {
	testRegionInfo()
	lock := make(chan bool)
	<-lock
	/*
		extcity.spdata.jianyu360.com
		172.17.4.238:9996
	*/
}

func testRegionInfo() {
	return
	dataArr, _ := ul.TestMgo.Find("site", bson.M{"area": "全国"}, nil, map[string]interface{}{"site": 1})
	isok := 0
	for k, v := range dataArr {
		if k%100 == 0 {
			log.Debug("cur index ", k, "~", isok)
		}
		tmpid := ul.BsonTOStringId(v["_id"])
		site := qu.ObjToString(v["site"])
		info := test(site)
		area := qu.ObjToString(info["area"])
		if area != "" && area != "全国" {
			isok++
			//ul.SiteMgo.Save("123123", map[string]interface{}{
			//	"site": site,
			//	"area": area,
			//})
			log.Debug(tmpid, "~", area)
			//ul.TestMgo.UpdateById("site", tmpid, map[string]interface{}{
			//	"$set": map[string]interface{}{
			//		"area": area,
			//	},
			//})
		}
	}
	log.Debug("is over ", isok)
}

func test(detail string) map[string]interface{} {
	info := map[string]interface{}{}
	client := &http.Client{Timeout: 2 * time.Second}
	data := map[string]interface{}{"detail": detail}
	jsonStr, _ := json.Marshal(data)
	resp, err := client.Post("http://127.0.0.1:9996/service/region", "application/json", bytes.NewBuffer(jsonStr))
	if err != nil {
		return info
	}
	res, err := io.ReadAll(resp.Body)
	if err != nil {
		return info
	}
	err = json.Unmarshal(res, &info)
	if err != nil {
		return info
	}
	return info
}
