package main

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

var hp_levelReg = regexp.MustCompile(`^[一二三]级[甲乙丙]等`)
var hp_containsReg = regexp.MustCompile(`(-|—|－| )`)

func saveHospitalMysql() {



	sess := save_mgo.GetMgoConn()
	defer save_mgo.DestoryMongoConn(sess)
	q,total:=map[string]interface{}{},0
	name_dict := map[string]string{}
	it := sess.DB(save_mgo.DbName).C(o_hospital_coll).Find(&q).Iter()
	for tmp := make(map[string]interface{}); it.Next(&tmp);total++{
		if total%1000==0 {
			log.Debug("curent index ",total)
		}
		tmpid := BsonTOStringId(tmp["_id"])
		hospital_name :=  qu.ObjToString(tmp["name"])
		arr_name := strings.Split(hospital_name,"医院")
		if len(arr_name)>2 {
			hospital_name = arr_name[0]+"医院"
		}
		if hp_containsReg.MatchString(hospital_name) {
			hospital_name = hp_containsReg.ReplaceAllString(hospital_name,"")
		}

		if name_dict[hospital_name]=="" {
			name_dict[hospital_name] = hospital_name
			data,alias_arr := updateHospitalData(tmp)
			data["name"] = hospital_name
			insertMysqlData("f_hospital",data,tmpid)
			for _,v := range alias_arr{
				if v=="" {
					continue
				}
				insertMysqlData("f_hospital_history", map[string]interface{}{
					"name":v,
					"hospital_name":hospital_name,
				},tmpid)
			}
		}else {
			//重复-过滤
		}
		tmp = make(map[string]interface{})
	}
	log.Debug("is hospital over ",total)
}
func updateHospitalData(tmp map[string]interface{})(map[string]interface{},[]string) {
	hospital := map[string]interface{}{}
	alias := qu.ObjToString(tmp["alias"])
	level := qu.ObjToString(tmp["level"])
	level_str := hp_levelReg.FindString(level)
	if level_str != "" {
		level = level_str
	}
	hospital["level"] = level

	hospital["name"] = qu.ObjToString(tmp["name"])
	hospital["type"] = qu.ObjToString(tmp["type"])
	hospital["address"] = qu.ObjToString(tmp["address"])
	hospital["main_depart"] = qu.ObjToString(tmp["main_depart"])
	hospital["business_type"] = qu.ObjToString(tmp["business_type"])
	hospital["tel"] = qu.ObjToString(tmp["tel"])
	hospital["fax_number"] = qu.ObjToString(tmp["fax_number"])
	hospital["website"] = qu.ObjToString(tmp["website"])
	hospital["area"] = qu.ObjToString(tmp["area"])
	hospital["city"] = qu.ObjToString(tmp["city"])
	hospital["district"] = qu.ObjToString(tmp["district"])
	hospital["alias"] = alias
	aliasArr := strings.Split(alias,",")
	return hospital,aliasArr
}


//包含非中文
func isUnHan(str string) bool {
	var count int
	for _, v := range str {
		if !unicode.Is(unicode.Han, v) {
			count++
			break
		}
	}
	return count > 0
}