package main

import (
	"fmt"
	log "github.com/donnie4w/go-logger/logger"
	"github.com/tealeg/xlsx"
	qu "qfw/util"
	"regexp"
	"strings"
	"time"
	"unicode/utf8"
)

//保存mysql
func saveYlqxclassMysql() {
	sess := save_mgo.GetMgoConn()
	defer save_mgo.DestoryMongoConn(sess)
	q,total:=map[string]interface{}{},0
	it := sess.DB(save_mgo.DbName).C(o_class_coll).Sort("_id").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"])
		delete(tmp,"_id")
		insertMysqlData("v_ylqxclass",tmp,tmpid)
		tmp = make(map[string]interface{})
	}
	log.Debug("is over ",total)
}


//医疗分类-mgo
func exportMedicalClassMysql() {
	log.Debug("开始处理-医疗分类")
	ff,_ := xlsx.OpenFile(s_class_xlsx_name)
	spaceReg := regexp.MustCompile(`([ \n]+)`)
	proReg := regexp.MustCompile(`(^[0-9][0-9])`)
	for index, sheet := range ff.Sheets {
		v := sheet
		class := v.Name
		sort := 0
		num_sort :=0
		pre_str := ""
		code_1 := convertSerialNumber(index+1,2)
		dict_1 := map[string]interface{}{
			"code":code_1,
			"pcode":"",
			"level":"1",
			"name":class,
		}
		save_mgo.Save(o_class_coll,dict_1)

		for k, row := range sheet.Rows {
			if k==0 {
				continue
			}
			var str []string
			for _, cell := range row.Cells {
				str = append(str, cell.String())
			}
			class_2,class_3,class_example := str[1],str[2],str[5]
			class_2 = spaceReg.ReplaceAllString(class_2,"")
			class_3 = spaceReg.ReplaceAllString(class_3,"")
			new_class_2 := proReg.ReplaceAllString(class_2,"")
			new_class_3 := proReg.ReplaceAllString(class_3,"")
			sort_1 := qu.IntAll(str[0])
			if sort_1 > sort { //1-4
				sort = sort_1
				code_2 := code_1+convertSerialNumber(sort,2)
				dict_2 := map[string]interface{}{
					"code":code_2,
					"pcode":code_1,
					"level":"2",
					"name":new_class_2,
				}
				save_mgo.Save(o_class_coll,dict_2)

				code_3 := code_2+convertSerialNumber(qu.IntAll(proReg.FindString(class_3)),4)
				dict_3 := map[string]interface{}{
					"code":code_3,
					"pcode":code_2,
					"level":"3",
					"name":new_class_3,
				}
				save_mgo.Save(o_class_coll,dict_3)
				e_arr := strings.Split(class_example,"、")
				pre_str = proReg.FindString(class_3)//重置一下
				num_sort = 0 //重置一下
				for _,v := range e_arr {
					num_sort++
					code4 := code_3+convertSerialNumber(num_sort,6)
					dict_4 := map[string]interface{}{
						"code":code4,
						"pcode":code_3,
						"level":"4",
						"name":v,
					}
					save_mgo.Save(o_class_coll,dict_4)
				}

			}else { //3-4
				str_3 := proReg.FindString(class_3)
				code_2:=convertSerialNumber(index+1,2)+convertSerialNumber(sort,2)
				code_3 := code_2+convertSerialNumber(qu.IntAll(str_3),4)
				if str_3 != pre_str {
					pre_str = proReg.FindString(class_3)//重置一下
					num_sort = 0 //重置一下
					dict_3 := map[string]interface{}{
						"code":code_3,
						"pcode":code_2,
						"level":"3",
						"name":new_class_3,
					}
					save_mgo.Save(o_class_coll,dict_3)
				}
				e_arr := strings.Split(class_example,"、")
				for _,v := range e_arr {
					num_sort++
					code4 := code_3+convertSerialNumber(num_sort,6)
					dict_4 := map[string]interface{}{
						"code":code4,
						"pcode":code_3,
						"level":"4",
						"name":v,
					}
					save_mgo.Save(o_class_coll,dict_4)
				}
			}
		}
	}


	log.Debug("is table class over")
	time.Sleep(2*time.Second)
	log.Debug("修复-分类数据")
	repairYlqxClass1()
	repairYlqxClass2()
}
//删除重复冗余选项
func repairYlqxClass1() {
	data:= 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(o_class_coll).Find(&q).Iter()
	for tmp := make(map[string]interface{}); it.Next(&tmp);total++{
		tmpid:=BsonTOStringId(tmp["_id"])
		key:= qu.ObjToString(tmp["name"])+"~"+qu.ObjToString(tmp["level"])+"~"+qu.ObjToString(tmp["pcode"])
		if data[key]=="" {
			data[key] = tmpid
		}else {
			save_mgo.DeleteById(o_class_coll,tmpid)
		}
		tmp = make(map[string]interface{})
	}
	log.Debug("is repair1 over ")
}
//补充新的医疗器械
func repairYlqxClass2() {
	sess := save_mgo.GetMgoConn()
	defer save_mgo.DestoryMongoConn(sess)
	q,total:=map[string]interface{}{
		"product_class":"体外诊断试剂",
	},0
	it := sess.DB(save_mgo.DbName).C(s_product_coll).Find(&q).Select(map[string]interface{}{
		"product_class_1":1,
		"product_class_2":1,
	}).Iter()
	data := map[string]map[string]interface{}{}
	rankArr := []string{}
	infoData := map[string][]string{}
	for tmp := make(map[string]interface{}); it.Next(&tmp);total++{
		if total%10000==0 {
			log.Debug("curent index ",total)
		}
		product_class_1 :=qu.ObjToString(tmp["product_class_1"])
		product_class_2 :=qu.ObjToString(tmp["product_class_2"])
		if product_class_1!="" {
			if data[product_class_1]==nil {
				if product_class_2!=""{
					data[product_class_1] = map[string]interface{}{
						product_class_2:1,
					}
					rankArr = append(rankArr,product_class_1)
					infoData[product_class_1] = []string{product_class_2}
				}else {
					data[product_class_1] = map[string]interface{}{}
					rankArr = append(rankArr,product_class_1)
					infoData[product_class_1] = []string{}
				}

			}else {
				pro := data[product_class_1]
				infoArr := infoData[product_class_1]
				if product_class_2!="" && pro[product_class_2]==nil {
					pro[product_class_2] = 1
					data[product_class_1] = pro
					infoArr = append(infoArr,product_class_2)
					infoData[product_class_1] = infoArr
				}
			}
		}
		tmp = make(map[string]interface{})
	}
	log.Debug("is over ",total,len(rankArr),len(data),len(infoData))

	class := "体外诊断试剂"
	code_1 := convertSerialNumber(23,2)
	dict_1 := map[string]interface{}{"code":code_1,"pcode":"","level":"1","name":class}
	save_mgo.Save(o_class_coll,dict_1)
	for k,v :=range rankArr {
		code_2 := code_1+convertSerialNumber(k+1,2)
		dict_2 := map[string]interface{}{"code":code_2,"pcode":code_1,"level":"2","name":v}
		save_mgo.Save(o_class_coll,dict_2)
		infoArr := infoData[v]
		for k1,v1 := range infoArr{
			code_3 := code_2+convertSerialNumber(k1+1,4)
			dict_3 := map[string]interface{}{"code":code_3,"pcode":code_2,"level":"3","name":v1}
			save_mgo.Save(o_class_coll,dict_3)
		}
	}

	log.Debug("is repair2 over ")
}
//2246位编号
func convertSerialNumber(index int,position int) string {
	code :=""
	curLength := utf8.RuneCountInString(fmt.Sprintf("%d",index))
	diff := position-curLength
	if diff>0 {
		pre := ""
		for i:=0;i<diff;i++ {
			pre+="0"
		}
		code = fmt.Sprintf("%s%d",pre,index)
	}else {
		code = fmt.Sprintf("%d",index)
	}
	return code
}
