package ext

import (
	"fmt"
	qu "qfw/util"
	"regexp"
	"strings"
	ul "util"
)

var cityEndReg *regexp.Regexp = regexp.MustCompile("(区|县|市)$")
var ErrBuyerReg *regexp.Regexp = regexp.MustCompile("^(成都东部新区)")

// 标准化校验后存值
func (e *ExtractTask) ExtractRegionClean(tmp *map[string]interface{}) {
	//标准化校验
	update_check := make(map[string]interface{}, 0)
	e.GetCheckFinallyRegionInfo(*tmp, &update_check)
	for k, v := range update_check {
		if k == "area" || k == "city" || k == "district" {
			(*tmp)[k] = v
		}
		if k == "modifycheck" && v != nil {
			(*tmp)[k] = v
		}
	}
}

// 企业表校验
func cityMarshal(data map[string]interface{}) map[string]string {
	buyer := qu.ObjToString(data["buyer"])
	bidarea := qu.ObjToString(data["area"])
	bidcity := qu.ObjToString(data["city"])
	biddistrict := qu.ObjToString(data["district"])
	rdata := make(map[string]string)
	query_name := map[string]interface{}{
		"company_name": buyer,
	}
	tmp := ul.QyxyMgo.FindOne("qyxy_std", query_name)
	if tmp == nil || len(tmp) < 2 {
		return rdata
	}
	company_code := fmt.Sprint(tmp["company_code"])
	if len(company_code) > 5 {
		province_city_district := ul.QyxyMgo.FindOne("address", map[string]interface{}{
			"code": company_code[:6],
		})
		remarks := fmt.Sprint((province_city_district)["Remarks"])
		if remarks == "" || remarks == "废除" || remarks == "已作废" {

		} else if province_city_district != nil {
			codeprovince := qu.ObjToString((province_city_district)["province"])
			codecity := qu.ObjToString((province_city_district)["city"])
			codedistrict := qu.ObjToString((province_city_district)["district"])
			if bidarea == "" || bidarea == "全国" {
				if codeprovince != "" {
					rdata["area"] = codeprovince
					if codecity != "" && codecity != codeprovince {
						rdata["city"] = codecity
						if codedistrict != "" && codedistrict != codecity {
							rdata["district"] = codedistrict
						}
					}
				}
			} else if bidcity == "" && codecity != "" && bidarea == codeprovince {
				if codecity != bidarea {
					rdata["city"] = codecity
					if codedistrict != "" && codecity != codedistrict {
						rdata["district"] = codedistrict
					}
				}
			} else if biddistrict == "" && codedistrict != "" && bidarea == codeprovince && codecity == bidcity {
				rdata["district"] = codedistrict
			}

			if rdata["city"] != "" || rdata["district"] != "" {
				return rdata
			}
		}
	}

	entprovince := qu.ObjToString(tmp["company_area"])
	entcity := qu.ObjToString(tmp["company_city"])
	entdistrict := qu.ObjToString(tmp["company_district"])

	//新增特殊处理-港澳台数据
	if bidarea == "" || bidarea == "香港" || bidarea == "澳门" || bidarea == "台湾" || bidarea == "全国" {
		if entprovince != "" {
			rdata["area"] = entprovince
			if entcity != "" && entcity != entprovince {
				rdata["city"] = entcity
				if entdistrict != "" && entdistrict != entcity {
					rdata["district"] = entdistrict
				}
			}
		}
	} else if bidcity == "" && entcity != "" && entprovince == bidarea {
		rdata["city"] = entcity
		if entdistrict != "" && entcity != entdistrict {
			rdata["district"] = entdistrict
		}
	} else if biddistrict == "" && entdistrict != "" && entprovince == bidarea && bidcity == entcity {
		rdata["district"] = entdistrict
	}

	return rdata
}

func (e *ExtractTask) GetCheckFinallyRegionInfo(tmp map[string]interface{}, update_check *map[string]interface{}) {
	area := qu.ObjToString(tmp["area"])
	city := qu.ObjToString(tmp["city"])
	district := qu.ObjToString(tmp["district"])
	buyer := qu.ObjToString(tmp["buyer"])

	if buyer != "" && ErrBuyerReg.MatchString(buyer) && area == "浙江" {
		(*update_check)["area"] = "四川"
		(*update_check)["city"] = "成都市"
		(*update_check)["district"] = ""
		return
	}

	if (district != "" && city != "" && area != "" && area != "全国") || buyer == "" {
		//标准城市-校验
		rdata := e.StandardCheckCity(area, city, district)
		if len(rdata) > 0 {
			umap := updateLogging(tmp, rdata, "标准信息")
			copyUpdateData(umap, update_check)
		}
		return
	}
	rdata := cityMarshal(tmp) //企业表-补城市
	if len(rdata) > 0 {
		new_area, new_city, new_district := area, city, district
		if rdata["area"] != "" {
			new_area = qu.ObjToString(rdata["area"])
		}
		if rdata["city"] != "" {
			new_city = qu.ObjToString(rdata["city"])
		}
		if rdata["district"] != "" {
			new_district = qu.ObjToString(rdata["district"])
		}
		umap := updateLogging(tmp, rdata, "企业信息")
		n_rdata := e.StandardCheckCity(new_area, new_city, new_district)
		if len(n_rdata) > 0 {
			for rk, rv := range n_rdata {
				umap[rk] = rv
				umap["modifycheck"].(map[string]interface{})[rk] = fmt.Sprintf("企业标准信息~%s~%s", qu.ObjToString(tmp[rk]), rv)
			}
		}
		copyUpdateData(umap, update_check)
	} else {
		n_rdata := e.StandardCheckCity(area, city, district)
		if len(n_rdata) > 0 {
			umap := updateLogging(tmp, n_rdata, "标准信息")
			copyUpdateData(umap, update_check)
		}
	}
}

// 标准校验
func (e *ExtractTask) 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 := e.S_DistrictDict[district]
		if districtArr == nil { //涉及了 个别别名相关的数据
			trim_arr := aliasDataDistrict(district) //拆分后缀
			if len(trim_arr) > 0 {
				for _, alias_district := range trim_arr {
					alias_districtArr := e.S_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 { //未完全匹配-错误地域的时候问题？清河区
				rdata["district"] = ""
				//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 := e.S_CityDict[city]
		if cityArr == nil {
			//把市当成区，匹配三级   - 存在优化空间- city:郑州  别名
			districtArr := e.S_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 { //未完全匹配
				rdata["city"] = ""
				//if len(cityArr) == 1 {
				//	rdata["area"] = cityArr[0].P_Name
				//	rdata["city"] = cityArr[0].C_Name
				//	rdata["district"] = ""
				//	return rdata
				//} else {
				//	rdata["city"] = ""
				//}
			}
		}
	}

	//第三步：省份校验
	if e.S_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
}
