package ext

import (
	"fmt"
	log "github.com/donnie4w/go-logger/logger"
	qu "qfw/util"
	"regexp"
	"strings"
	ul "util"
)


type CP struct {
	P_Name    string
}
type CC struct {
	P_Name string
	C_Name string
}
type CD struct {
	P_Name string
	C_Name string
	D_Name string
}
var (
	ProvinceDict	map[string][]CP				//省份-map
	CityDict		map[string][]CC					//城市-map
	DistrictDict	map[string][]CD				//区县-map
)
var cityEndReg *regexp.Regexp = regexp.MustCompile("(区|县|市)$")

//核对城市
func GetCheckDataCity(tmp map[string]interface{},update_check *map[string]interface{}) {

	area := qu.ObjToString(tmp["area"])
	city := qu.ObjToString(tmp["city"])
	district := qu.ObjToString(tmp["district"])
	rdata := standardCheckCity(area,city,district)//标准城市-校验
	if len(rdata)>0 {
		umap:=updateLogging(tmp,rdata,"标准信息")
		copyUpdateData(umap,update_check)
	}
}


//标准校验
func standardCheckCity(area string,city string,district string) map[string]string{

	rdata := make(map[string]string,0)
	if area=="香港"||area=="澳门"||area=="台湾" || (area=="全国"&&(city==""&&district=="")) {
		return rdata
	}
	//第一步：区校验
	if district!="" {
		districtArr := DistrictDict[district]
		if districtArr==nil {//涉及了 个别别名相关的数据
			trim_arr := aliasDataDistrict(district)//拆分后缀
			if len(trim_arr)>0 {
				for _,alias_district := range trim_arr {
					alias_districtArr := DistrictDict[alias_district]
					for _,v:=range alias_districtArr{
						if  city == v.C_Name && area == v.P_Name {
							rdata["district"] = alias_district
							return rdata
						}
					}
				}
			}
			rdata["district"] = ""
		}else {
			isTrue := false
			for _,v:=range districtArr{
				if  city == v.C_Name && area == v.P_Name {
					isTrue = true
					break
				}
			}
			if isTrue { //完全匹配
				return rdata
			}else { //未完全匹配
				if len(districtArr)==1 {
					rdata["area"] = districtArr[0].P_Name
					rdata["city"] = districtArr[0].C_Name
					rdata["district"] = districtArr[0].D_Name
					return rdata
				}else {
					rdata["district"] = ""
				}
			}
		}
	}

	//第二步：区校验-失败   市-校验
	if city != "" {
		cityArr := CityDict[city]
		if cityArr==nil {
			//把市当成区，匹配三级   - 存在优化空间- city:郑州  别名
			districtArr := DistrictDict[city]
			for _,v:=range districtArr{
				if  city == v.C_Name && area == v.P_Name {
					rdata["area"] = districtArr[0].P_Name
					rdata["city"] = districtArr[0].C_Name
					rdata["district"] = districtArr[0].D_Name
					return rdata
				}
			}
			rdata["city"] = ""
		}else {
			isTrue := false
			for _,v:=range cityArr{
				if  area == v.P_Name {
					isTrue = true
					break
				}
			}
			if isTrue { //完全匹配
				return rdata
			}else { //未完全匹配
				if len(cityArr)==1 {
					rdata["area"] = cityArr[0].P_Name
					rdata["city"] = cityArr[0].C_Name
					rdata["district"] = ""
					return rdata
				}else {
					rdata["city"] = ""
				}
			}
		}
	}

	//第三步：省份校验
	if ProvinceDict[area]==nil {
		rdata["area"] = "全国"
		rdata["city"] = ""
		rdata["district"] = ""
	}

	return rdata
}

//更新日志
func updateLogging(tmp map[string]interface{},rdata map[string]string,desc string) map[string]interface{} {
	umap := make(map[string]interface{})
	if tmp["modifycheck"] == nil {
		umap["modifycheck"] = make(map[string]interface{})
	} else {
		umap["modifycheck"] = tmp["modifycheck"]
	}
	for rk, rv := range rdata {
		umap[rk] = rv
		umap["modifycheck"].(map[string]interface{})[rk] = fmt.Sprintf("%s~%s~%s",desc,qu.ObjToString(tmp[rk]),rv)
	}
	return umap
}

func copyUpdateData(tmp map[string]interface{},update_check *map[string]interface{}) {
	for k,v := range tmp {
		(*update_check)[k] = v
	}
}

//拆分三级县
func aliasDataDistrict(district string) []string {
	arr :=[]string{}
	if cityEndReg.MatchString(district) {
		str := cityEndReg.FindString(district)
		strings.TrimRight(district, str)
		if str=="县"{
			arr = append(arr,fmt.Sprintf("%s区",strings.TrimRight(district, str)))
			arr = append(arr,fmt.Sprintf("%s市",strings.TrimRight(district, str)))
		}else if str=="区"{
			arr = append(arr,fmt.Sprintf("%s县",strings.TrimRight(district, str)))
			arr = append(arr,fmt.Sprintf("%s市",strings.TrimRight(district, str)))
		} else if str=="市"{
			arr = append(arr,fmt.Sprintf("%s县",strings.TrimRight(district, str)))
			arr = append(arr,fmt.Sprintf("%s区",strings.TrimRight(district, str)))
		}else {

		}
	}else { //未找到 district- 区县市  例： district : 金水
		arr = append(arr,fmt.Sprintf("%s区",district))
		arr = append(arr,fmt.Sprintf("%s县",district))
		arr = append(arr,fmt.Sprintf("%s市",district))
	}
	return arr
}





//初始化
func InitCheckCity()  {
	//初始化-城市配置
	ProvinceDict = make(map[string][]CP,0)
	CityDict = make(map[string][]CC,0)
	DistrictDict = make(map[string][]CD,0)

	q := map[string]interface{}{
		"town_code":map[string]interface{}{
			"$exists":0,
		},
	}
	sess := ul.ExtMgo.GetMgoConn()
	defer ul.ExtMgo.DestoryMongoConn(sess)
	it := sess.DB(ul.ExtMgo.DbName).C(ul.CheckColl).Find(&q).Iter()
	total  := 0
	for tmp := make(map[string]interface{}); it.Next(&tmp); total++ {
		if total%1000 == 0 {
			log.Debug("当前数量:", total)
		}
		district_code := qu.IntAll(tmp["district_code"])
		city_code := qu.IntAll(tmp["city_code"])
		if district_code > 0 {
			province := qu.ObjToString(tmp["province"])
			city := qu.ObjToString(tmp["city"])
			district := qu.ObjToString(tmp["district"])
			data := CD{province,city,district}
			if DistrictDict[district]==nil {
				DistrictDict[district] = []CD{data}
			}else {
				arr := DistrictDict[district]
				arr = append(arr,data)
				DistrictDict[district] = arr
			}
		}else {
			if city_code>0 {
				province := qu.ObjToString(tmp["province"])
				city := qu.ObjToString(tmp["city"])
				data := CC{province,city}
				if CityDict[city]==nil {
					CityDict[city] = []CC{data}
				}else {
					arr := CityDict[city]
					arr = append(arr,data)
					CityDict[city] = arr
				}
			}else {
				province := qu.ObjToString(tmp["province"])
				data := CP{province}
				if ProvinceDict[province]==nil {
					ProvinceDict[province] = []CP{data}
				}else {
					arr := ProvinceDict[province]
					arr = append(arr,data)
					ProvinceDict[province] = arr
				}
			}
		}
		tmp = make(map[string]interface{})
	}
	log.Debug(fmt.Sprintf("城市配置加载完毕...省~%d 市~%d 区~%d",len(ProvinceDict),len(CityDict),len(DistrictDict)))
}