package main

import (
	log "github.com/donnie4w/go-logger/logger"
	"github.com/uuid"
	"go.mongodb.org/mongo-driver/bson"
	qu "qfw/util"
	"strings"
)

//企业信息处理
func exportDealerBaseInfo() {
	//企业信息去重
	dataArr := repeatNameQyxyInfo()
	for index, tmp := range dataArr {
		if index%10000 == 0 {
			log.Debug("curent index ", index)
		}
		for k, v := range tmp {
			infoArr, _ := Qyxy_Mgo.Find("qyxy_std", map[string]interface{}{
				"company_name": k,
			}, nil, map[string]interface{}{
				"company_name":     1,
				"company_area":     1,
				"company_city":     1,
				"company_district": 1,
				"company_address":  1,
				"capital":          1,
			})
			if len(infoArr) > 0 { //选取最优-企业信息
				ind := getOneBaseCompany(infoArr)
				info := infoArr[ind]
				new_info := createDealerInfo(info, v)
				Save_Mgo.Save("nmpa_company_dealer", new_info)
			} else {
				Save_Mgo.Save("nmpa_company_dealer_err", map[string]interface{}{
					"dealer_name":    k,
					"business_model": v,
				})
			}
		}
	}
	log.Debug("经销商处理~~~", len(dataArr))
}

//构建更新数据
func createDealerInfo(tmp map[string]interface{}, business_model string) map[string]interface{} {
	info := map[string]interface{}{}
	//查询主题库
	dealer_name := qu.ObjToString(tmp["company_name"])
	company_id := qu.ObjToString(tmp["_id"])
	name_id := ""
	ent := MysqlGlobalTool.FindOne("dws_f_ent_baseinfo", map[string]interface{}{
		"name": dealer_name,
	}, "name_id", "-id")
	if ent != nil {
		name_id = qu.ObjToString((*ent)["name_id"])
		info["exists_id"] = 1
	} else {
		name_id = uuid.New().String()
		name_id = strings.ReplaceAll(name_id, "-", "")
		info["exists_id"] = 0
	}
	info["dealer_name"] = dealer_name
	info["company_id"] = company_id
	info["name_id"] = name_id
	area_code, city_code, district_code := dealWithRegionCode(qu.ObjToString(tmp["company_area"]), qu.ObjToString(tmp["company_city"]), qu.ObjToString(tmp["company_district"]))
	info["area_code"] = area_code
	info["city_code"] = city_code
	info["district_code"] = district_code
	info["business_model"] = qu.IntAll(business_model)
	info["company_address"] = qu.ObjToString(tmp["company_address"])
	data := Spi_Mgo.FindOne("company_base", bson.M{"company_id": company_id})
	new_capital := qu.ObjToString(data["capital"])
	capital, capital_code := qu.Float64All(tmp["capital"]), 1
	if capital >= float64(0) && capital < float64(100) {
		capital_code = 1
	} else if capital >= float64(100) && capital < float64(500) {
		capital_code = 2
	} else if capital >= float64(500) && capital < float64(1000) {
		capital_code = 3
	} else {
		capital_code = 4
	}
	info["capital"] = new_capital
	info["capital_code"] = capital_code
	return info
}

//获取最优企业
func getOneBaseCompany(arr []map[string]interface{}) int {
	index := 0
	flag := 100
	if len(arr) > 1 {
		for k, tmp := range arr {
			use_flag := qu.IntAll(tmp["use_flag"])
			if use_flag == 0 {
				index = k
				break
			} else {
				if use_flag < flag {
					flag = use_flag
					index = k
				}
			}
		}
	}
	return index
}

//重复企业-过滤
func repeatNameQyxyInfo() []map[string]string {
	sess := Save_Mgo.GetMgoConn()
	defer Save_Mgo.DestoryMongoConn(sess)
	q, total := map[string]interface{}{}, 0
	it := sess.DB(Save_Mgo.DbName).C("nmpa_company_new").Find(&q).Select(map[string]interface{}{
		"company":  1,
		"classify": 1,
	}).Iter()
	temp := map[string]string{}
	qyArr := []string{}
	for tmp := make(map[string]interface{}); it.Next(&tmp); total++ {
		if total%10000 == 0 {
			log.Debug("curent index ", total)
		}
		company := qu.ObjToString(tmp["company"])
		classify := qu.ObjToString(tmp["classify"])
		model := ""
		if strings.Contains(classify, "生产") {
			model = "生产"
		} else if strings.Contains(classify, "经营") {
			model = "经营"
		} else {
			log.Debug("类型异常~~~~~~")
		}
		if company != "" {
			if temp[company] == "" {
				temp[company] = model
				qyArr = append(qyArr, company)
			} else {
				pre_model := temp[company]
				if pre_model != model && model != "" && !strings.Contains(pre_model, "&&") {
					temp[company] = pre_model + "&&" + model
				}
			}
		}
		tmp = make(map[string]interface{})
	}
	newArr := []map[string]string{}
	for _, v := range qyArr {
		tag := ""
		if temp[v] == "生产" {
			tag = "1"
		} else if temp[v] == "经营" {
			tag = "2"
		} else if temp[v] == "" {
			tag = "4"
		} else {
			tag = "3"
		}
		newArr = append(newArr, map[string]string{
			v: tag,
		})
	}

	log.Debug("企业去重~", total, len(newArr))
	return newArr
}

//处理地域代码
func dealWithRegionCode(area string, city string, district string) (area_code string, city_code string, district_code string) {
	area_code, city_code, district_code = "000000", "", ""
	if district != "" {
		key := area + "~" + city + "~" + district + "~"
		code := RegionCodeData[key]
		if code != "" {
			district_code = code
			city_code = code[:4] + "00"
			area_code = code[:2] + "0000"
			return
		}
	}
	if city != "" {
		key := area + "~" + city + "~" + "" + "~"
		code := RegionCodeData[key]
		if code != "" {
			city_code = code
			area_code = city_code[:2] + "0000"
			return
		}
	}
	if area != "" {
		key := area + "~" + "" + "~" + "" + "~"
		code := RegionCodeData[key]
		if code != "" {
			area_code = code
			return
		}
	}
	return
}

func testDealerTag() {

}
