package main

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

//修复产品分类表
func repairProductClass() {
	sess := save_mgo.GetMgoConn()
	defer save_mgo.DestoryMongoConn(sess)
	q := map[string]interface{}{}
	it := sess.DB(save_mgo.DbName).C("zktest_mysql_product_info").Find(&q).Select(map[string]interface{}{
		"product_code": 1,
	}).Sort("_id").Iter()
	total := 0
	for tmp := make(map[string]interface{}); it.Next(&tmp); total++ {
		if total%10000 == 0 {
			log.Debug("cur index ", total)
		}
		product_code := qu.ObjToString(tmp["product_code"])
		if utf8.RuneCountInString(product_code) == 8 || utf8.RuneCountInString(product_code) == 14 {
			new_code := updatecode(product_code)
			if new_code == "" {
				log.Debug("异常~~~~", tmp["_id"])
			}
			save_mgo.UpdateById("zktest_mysql_product_info", BsonTOStringId(tmp["_id"]), map[string]interface{}{
				"$set": map[string]interface{}{
					"product_code": new_code,
				},
			})
		}

		tmp = make(map[string]interface{})
	}

	log.Debug("is over ", total)
}

//修复医疗器械v表
func repairYlqxClass() {
	sess := save_mgo.GetMgoConn()
	defer save_mgo.DestoryMongoConn(sess)
	q := map[string]interface{}{}
	it := sess.DB(save_mgo.DbName).C("zktest_mysql_ylqxclass").Find(&q).Sort("_id").Iter()
	total := 0

	for tmp := make(map[string]interface{}); it.Next(&tmp); total++ {
		if total%1000 == 0 {
			log.Debug("cur index ", total)
		}
		code := qu.ObjToString(tmp["code"])
		pcode := qu.ObjToString(tmp["pcode"])
		level := qu.ObjToString(tmp["level"])
		if level == "3" { //调整code
			new_code := updatecode(code)
			save_mgo.UpdateById("zktest_mysql_ylqxclass", BsonTOStringId(tmp["_id"]), map[string]interface{}{
				"$set": map[string]interface{}{
					"code": new_code,
				},
			})
		} else if level == "4" { //调整code pcode
			new_code := updatecode(code)
			new_pcode := updatecode(pcode)
			save_mgo.UpdateById("zktest_mysql_ylqxclass", BsonTOStringId(tmp["_id"]), map[string]interface{}{
				"$set": map[string]interface{}{
					"code":  new_code,
					"pcode": new_pcode,
				},
			})
		} else {

		}

		tmp = make(map[string]interface{})
	}

	log.Debug("is over ", total)

}

func updatecode(code string) string {
	rc := []rune(code)
	new_code := code
	if len(rc) == 8 {
		new_code = string(rc[:4]) + string(rc[5:8])
	}
	if len(code) == 14 {
		new_code = string(rc[:4]) + string(rc[5:8]) + string(rc[10:14])
	}

	return new_code
}
