package main

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

//导出经销商注册备案信息
func exportDealerRegisterInfo() {
	sess := Save_Mgo.GetMgoConn()
	defer Save_Mgo.DestoryMongoConn(sess)
	q, total := map[string]interface{}{}, 0
	it := sess.DB(Save_Mgo.DbName).C("nmpa_company_dealer").Find(&q).Select(map[string]interface{}{
		"name_id":        1,
		"dealer_name":    1,
		"business_model": 1,
	}).Iter()
	for tmp := make(map[string]interface{}); it.Next(&tmp); {
		if total%10000 == 0 {
			log.Debug("curent index ", total)
		}
		num := createDealerRegisterInfo(tmp)
		total += num
		tmp = make(map[string]interface{})
	}
	log.Debug("经销商信息~~~", total)
}

//构建注册备案基本信息
func createDealerRegisterInfo(tmp map[string]interface{}) int {
	company_name := qu.ObjToString(tmp["dealer_name"])
	dealer_id := qu.ObjToString(tmp["name_id"])
	business_model := qu.IntAll(tmp["business_model"])
	infoArr, _ := Save_Mgo.Find("nmpa_company_new", bson.M{"company": company_name}, bson.M{"_id": 1}, nil)
	num := 0
	for _, v := range infoArr {
		num++
		info := map[string]interface{}{}
		info["dealer_id"] = dealer_id
		info["company_name"] = company_name
		reg_no := qu.ObjToString(v["reg_no"])
		classify := qu.ObjToString(v["classify"])
		info["regnum"] = reg_no
		if strings.Contains(classify, "许可") {
			info["type"] = 1
		} else if strings.Contains(classify, "备案") {
			info["type"] = 2
		}
		info["address"] = qu.ObjToString(v["address"])
		info["business_type"] = business_model
		info["validity_date"] = qu.ObjToString(v["yxqx"])

		info["scope"] = pickfirst(qu.ObjToString(v["product_range"]), qu.ObjToString(v["business_range"]))
		info["approve_depart"] = pickfirst(qu.ObjToString(v["fzbm"]), qu.ObjToString(v["badw"]))
		info["approve_date"] = pickfirst(qu.ObjToString(v["fzrq"]), qu.ObjToString(v["barq"]))
		info["type_address"] = pickfirst(qu.ObjToString(v["product_address"]), qu.ObjToString(v["business_address"]))
		info["responsible_person"] = qu.ObjToString(v["responsible_persons"])
		info["legal_person"] = qu.ObjToString(v["legal_person"])
		Save_Mgo.Save("nmpa_company_register", info)
	}
	return num
}

func pickfirst(s1 string, s2 string) string {
	if s1 != "" {
		return s1
	}
	return s2
}
