package pretreated

import (
	u "jy/util"
	qutil "qfw/util"
	"strings"
)

// 对td中的值，进行再处理
func (tn *Table) TdContactFormat(contactFormat *u.ContactFormat, isSite bool, codeSite string) {
	//处理表格中的联系人信息
	indexMap := contactFormat.IndexMap
	matchMap := contactFormat.MatchMap
	//qutil.Debug("==============================td=======================", indexMap, matchMap)
	weightMap := map[string]map[string]interface{}{} //权重
	mustMatchFirst := len(indexMap) > 0              //第一个必须匹配上
	reCreate := false
	matchCount := 0
	contactTypeTagMap := map[string]map[string][]interface{}{}
	//qutil.Debug("============================", mustMatchFirst, indexMap, matchMap)
	notMatchTrCount := 0
	allAscFind := true //开启正序查询
	//涉及变量allAscFind，indexMap
	if len(indexMap) == 0 {
		isCanAddToIndexMap := false
		matchPrevFlag := false
		prevCanAddToIndexMap := false
	LS:
		for _, tr := range tn.TRs {
			for td_index, td := range tr.TDs {
				thisTdKvs := tn.tdkv(td) //获取td冒号kv
				//qutil.Debug(td.Val, len(thisTdKvs))
				//				for _, v := range thisTdKvs {
				//					qutil.Debug(v.Key, v.Value)
				//				}
				if len(thisTdKvs) != 1 {
					preTdIndex := td_index - 1
					if preTdIndex >= 0 {
						preTdVal := tr.TDs[td_index-1].Val
						tdType := "" //前一个td中是否是采购、代理、中标
						for k, v := range ContactType {
							if v.MatchString(preTdVal) {
								tdType = k
								break
							}
						}
						if tdType != "" {
							for _, this := range thisTdKvs {
								if str := ContactInfoVagueReg.FindString(this.Key); str != "" {
									td.SortKV.AddKey(tdType+str, this.Value)
								}
							}
						}
					}

					continue
				}
				//1.处理带括号的()[]【】采购单位，代理机构；2.识别采购单位联系人、联系电话、代理机构联系人、联系电话
				goOnFunc, isContinue, td_k := tn.tdKV(thisTdKvs[0].Key, &matchPrevFlag, &isCanAddToIndexMap, &indexMap, "LS")
				//qutil.Debug("goOnFunc---", goOnFunc, "isContinue---", isContinue, "indexMap---", indexMap, "isCanAddToIndexMap---", isCanAddToIndexMap)
				if !goOnFunc {
					break LS
				}
				if isContinue {
					continue
				}
				//采购单位，代理机构，中标单位
				//fmt.Println("td_k---", td_k, HasOrderContactType(td_k))
				//针对名称特殊类-采用临边查询方式-左临
				if td.Val == "名称" {
					near := tn.FindNear(td, 1)
					if near != nil {
						if ContactHeadReg.MatchString(near.Val) {
							td_k = near.Val + td.Val
						}
					}
				}
				for _, k := range HasOrderContactType(td_k) {
					if !ContactType[k].MatchString(td_k) { //不是采购单位，代理机构,中标单位跳过
						continue
					}
					if len(indexMap) == 0 {
						//qutil.Debug("isCanAddToIndexMap---", isCanAddToIndexMap, "prevCanAddToIndexMap---", prevCanAddToIndexMap, len(tr.TDs))
						if isCanAddToIndexMap || (prevCanAddToIndexMap && len(tr.TDs) == 1) {
							myPrevTdVal := ""
							if td_index-2 >= 0 {
								myPrevTdVal = tr.TDs[td_index-2].Val
								if myPrevTdVal != "" && len([]rune(myPrevTdVal)) < 10 && ContactInfoMustReg.MatchString(myPrevTdVal) {
									matchPrevFlag = true
								}
							}
							indexMap[0] = k
							break
						}
					} else {
						indexMap = map[int]string{}
						break LS
					}
				}
			}
			prevCanAddToIndexMap = isCanAddToIndexMap
			isCanAddToIndexMap = false
		}
		if len(indexMap) > 0 {
			allAscFind = false
		}
	}
	//////
L:
	for tr_index, tr := range tn.TRs {
		thisTrHasMatch := false
		jumpNextTd := false
		for td_index, td := range tr.TDs {
			//和|以?及|与|、多个词和在一起
			jumpNextTd, thisTrHasMatch = tn.tdsMultipleWords(jumpNextTd, td, td_index, tr, thisTrHasMatch, indexMap)
			//分块之后的kv
			thisTdKvs := kvAfterDivideBlock("", td.Text, 3, tn.TableResult.RuleBlock, isSite, codeSite)
			if len(thisTdKvs) == 0 {
				thisTdKvs = tn.tdkv(td) //获取冒号kv
			}
			tdAscFind := true //开启td正序查询
			//qutil.Debug("---", td.Val, len(thisTdKvs), len(indexMap))
			if len(thisTdKvs) == 0 {
				continue
			} else if allAscFind && len(thisTdKvs) >= 3 && len(indexMap) == 0 {
				//采购人在联系人、电话后面的处理
				tdAscFind = tn.hasIndexMap(thisTdKvs, &indexMap, tdAscFind)
			}

			prevKey := ""
			oldIndexMapLength := len(indexMap)
			thidTdIndex := td_index
			//notmatchCount := 0
			kvTitle := ""
			//qutil.Debug("indexMap++++++++++++++++++", indexMap, "len(thisTdKvs)", len(thisTdKvs), oldIndexMapLength)
			if len(thisTdKvs) >= 2 { //td中有多个kv重置indexMap
				indexMap = map[int]string{}
				allAscFind = true
			}
			for _, td_kv := range thisTdKvs {
				iscontinue := false
				td_v := td_kv.Value
				td_k := FilterContactKey(td_kv.Key) //带括号()[]的采购单位，代理机构处理
				td_k_length := len([]rune(td_k))
				if td_k_length < 2 || td_k_length > 15 {
					continue
				}
				//都为正序查询
				//qutil.Debug("td_k+++", td_k, "td_v+++", td_v, "allAscFind+++", allAscFind, "tdAscFind+++", tdAscFind)
				if allAscFind && tdAscFind {
					//都为正序查询处理
					matchCount, weightMap, matchMap, thisTrHasMatch, indexMap, iscontinue, reCreate, thidTdIndex = tn.asdFind(td_k, matchCount, weightMap, matchMap, td, thisTrHasMatch, td_kv, indexMap, iscontinue, reCreate, thidTdIndex, isSite, codeSite)
				}
				//qutil.Debug("indexMap++++++", indexMap, len(indexMap), "iscontinue+++", iscontinue)
				if iscontinue {
					continue
				}
				//不在同一块中
				//qutil.Debug(td_kv.Title, kvTitle, !ContactInfoMustReg.MatchString(td_kv.Key))
				if td_kv.Title != "" && kvTitle != td_kv.Title && len(indexMap) > 0 && !ContactInfoMustReg.MatchString(td_kv.Key) {
					thidTdIndex = 0
					matchMap = map[string]map[string]bool{}
					indexMap = map[int]string{}
				}
				kvTitle = td_kv.Title
				//qutil.Debug(td_k_length, td_k_length, len(indexMap))
				if td_k_length < 2 || td_k_length > 10 {
					continue
				}
				if len(indexMap) > 0 {
					//没有识别到采购单位联系人、联系电话、代理机构联系人、联系电话
					if !ContactInfoMustReg.MatchString(td_k) {
						//notmatchCount++
						//if notmatchCount < len(indexMap)*2 && false {//false???????
						//	notmatchCount = 0
						//	thidTdIndex = 0
						//	indexMap = map[int]string{}
						//	matchMap = map[string]map[string]bool{}
						//}
						if mustMatchFirst { //indexMap初始值大于0
							break L
						}
						continue
					}
					reCreate = true
					index := td_index
					//oldIndexMapLength原来的indexMap等于0 ，现在的indexMap大于1
					if oldIndexMapLength == 0 && len(indexMap) > 1 {
						if prevKey != td_k {
							prevKey = td_k
							index = td_index
						} else if prevKey == td_k {
							index++
						}
					}
					//kv.value为空
					if filterValue.MatchString(td_v) {
						thisTrHasMatch = true
						continue
					}
					//u.Debug(indexMap, td_k, td_v, matchMap, index, modle)
					//myContactType

					myContactType := indexMap[index]
					if td_kv.Key == "地址" && strings.Contains(td_kv.PrevLine, "采购代理机构") {
						myContactType = "代理机构"
					}
					//qutil.Debug(indexMap, index, myContactType)
					if myContactType == "" && len(indexMap) == 1 {
						_, onlyContactType := u.FirstKeyValueInMap(indexMap)
						myContactType, _ = onlyContactType.(string)
					}
					//qutil.Debug("indexMap+++", indexMap, "index+++", index, "myContactType+++", myContactType)
					if myContactType == "" {
						continue
					}
					matchCount++
					if matchMap[myContactType] == nil {
						matchMap[myContactType] = map[string]bool{}
					}
					if IsContactKvHandle(ContactInfoMustReg.FindString(td_k), matchMap[myContactType]) {
						continue
					}
					matchMap[myContactType][ContactInfoMustReg.FindString(td_k)] = true
					if ContactType[myContactType].MatchString(td_k) {
						continue
					}
					thisTrHasMatch = true
					//modle
					modle(thisTdKvs, td, myContactType, td_k, td_v, &contactTypeTagMap, tn, &weightMap, tr_index, td_index, isSite, codeSite)
				}
			}
			//qutil.Debug("map===", td.SortKV.Map)
		}
		if allAscFind && !thisTrHasMatch {
			notMatchTrCount++
			if notMatchTrCount >= 2 {
				notMatchTrCount = 0
				indexMap = map[int]string{}
			}
		}
	}
	//u.Debug("end", matchCount, indexMap, matchMap)
	if matchCount == 0 {
		indexMap = map[int]string{}
		matchMap = map[string]map[string]bool{}
	}
	(*contactFormat).IndexMap = indexMap
	(*contactFormat).MatchMap = matchMap
	// for _, tr := range tn.TRs {
	// 	for _, td := range tr.TDs {
	// 		qutil.Debug("td.sort.map---", td.SortKV.Map)
	// 	}
	// }
}

// modle
func modle(thisTdKvs []*u.Kv, td *TD, myContactType, td_k, td_v string, contactTypeTagMap *map[string]map[string][]interface{}, tn *Table, weightMap *map[string]map[string]interface{}, tr_index, td_index int, isSite bool, codeSite string) {
	modle := 0
	if len(thisTdKvs) == 1 {
		if regReplAllSpace.ReplaceAllString(thisTdKvs[0].Value, "") == "" {
			modle = 1
		} else {
			modle = 2
		}
	}
	if modle == 1 {
		td.Text = myContactType + td_k
		td.Val = td.Text
	} else {
		//
		if !strings.HasSuffix(td_k, "方式") {
			kvTags := GetKvTags([]*u.Kv{&u.Kv{Key: myContactType + td_k, Value: td_v}}, "", BuyerContacts, isSite, codeSite)
			if len(kvTags) == 1 {
				tagVal, _ := u.FirstKeyValueInMap(kvTags)
				if tagVal == "采购单位联系人" && ContactBuyerPersonFilterReg.MatchString(td_v) {
					return
				}
				if (*contactTypeTagMap)[myContactType] == nil {
					(*contactTypeTagMap)[myContactType] = map[string][]interface{}{}
				}
				myOldKeyArray := (*contactTypeTagMap)[myContactType][tagVal]
				if myOldKeyArray != nil {
					tn.TRs[myOldKeyArray[0].(int)].TDs[myOldKeyArray[1].(int)].SortKV.RemoveKey(myContactType + myOldKeyArray[2].(string))
				} else {
					(*contactTypeTagMap)[myContactType][tagVal] = make([]interface{}, 3)
				}
				if (*weightMap)[myContactType] == nil {
					(*weightMap)[myContactType] = map[string]interface{}{}
				}
				(*weightMap)[myContactType][tagVal] = 1
				(*contactTypeTagMap)[myContactType][tagVal] = []interface{}{tr_index, td_index, td_k}
			}
		}
		td.SortKV.AddKey(myContactType+td_k, td_v)
	}
}

// 都为正序查询
func (tn *Table) asdFind(td_k string, matchCount int, weightMap map[string]map[string]interface{}, matchMap map[string]map[string]bool, td *TD, thisTrHasMatch bool, td_kv *u.Kv, indexMap map[int]string, iscontinue bool, reCreate bool, thidTdIndex int, isSite bool, codeSite string) (int, map[string]map[string]interface{}, map[string]map[string]bool, bool, map[int]string, bool, bool, int) {
	for _, k := range HasOrderContactType(td_k) { //采购单位，代理机构,中标单位
		if !ContactType[k].MatchString(td_k) { //没有匹配到采购单位，代理机构，中标单位
			continue
		}
		if k == "采购单位" && td_k == "招标机构" {
			continue
		}
		matchCount++
		if weightMap[k] == nil {
			weightMap[k] = map[string]interface{}{}
		}
		//匹配到进行处理
		if ContactInfoVagueReg.MatchString(td_k) {
			thisTrHasMatch = tn.matchContactType(&matchMap, k, td_k, td_kv.Value, td, &weightMap, thisTrHasMatch, isSite, codeSite)
		} else if k == "采购单位" { //打标签，权重高的重新覆盖
			kvTags := GetKvTags([]*u.Kv{td_kv}, "", []string{"采购单位"}, isSite, codeSite)
			tagVal, weightVal := u.FirstKeyValueInMap(kvTags)
			if tagVal == k {
				if weightMap[k][k] == nil || (weightVal != nil && weightVal.(int) >= weightMap[k][k].(int)) || len(matchMap[k]) == 0 {
					weightMap[k][k] = weightVal.(int)
					matchMap[k] = map[string]bool{}
					indexMap = map[int]string{}
				}
			}
		}
		if u.IsMapHasValue(k, indexMap) { //map中是否存在value
			thisTrHasMatch = true
			iscontinue = true
			continue
		}
		if reCreate {
			indexMap = map[int]string{}
			reCreate = false
		}
		indexMap[thidTdIndex] = k
		iscontinue = true
		thisTrHasMatch = true
		thidTdIndex++
		break
	}
	if len(indexMap) == 0 && td_kv.PrevLine != "" {
		//td_kv.PrevLine
		prevLine := FilterSerial.ReplaceAllString(td_kv.PrevLine, "")
		for k, v := range ContactType { //采购单位，代理机构正则
			if u.IsArrayHasValue(prevLine, v.FindAllString(prevLine, -1)) {
				indexMap[thidTdIndex] = k
				thisTrHasMatch = true
				thidTdIndex++
			}
		}
	}
	if len(indexMap) == 0 && td_kv.Title != "" {
		//td_kv.Title
		if titleMatchType := ContactTypeTitleMatch(td_kv.Title); titleMatchType != "" {
			thidTdIndex = 0
			matchMap = map[string]map[string]bool{}
			indexMap = map[int]string{1: titleMatchType}
			//			for i, t := range titleMatchType {
			//				indexMap[i+1] = t
			//			}
		}
	}
	return matchCount, weightMap, matchMap, thisTrHasMatch, indexMap, iscontinue, reCreate, thidTdIndex
}

// 匹配到进行处理
func (tn *Table) matchContactType(matchMap *map[string]map[string]bool, k string, td_k string, td_v string, td *TD, weightMap *map[string]map[string]interface{}, thisTrHasMatch bool, isSite bool, codeSite string) bool {
	if (*matchMap)[k] == nil {
		(*matchMap)[k] = map[string]bool{}
	}
	isAddToMatchMap := true
	if !strings.HasSuffix(td_k, "方式") {
		kvTags := GetKvTags([]*u.Kv{&u.Kv{Key: td_k, Value: td_v}}, "", BuyerContacts, isSite, codeSite)
		if len(kvTags) == 1 {
			tagVal, weightVal := u.FirstKeyValueInMap(kvTags)
			if tagVal == "采购单位联系人" && ContactBuyerPersonFilterReg.MatchString(td_v) {
				isAddToMatchMap = false
			}
			if td.SortKV.Map[tagVal] != nil {
				if (*weightMap)[k][tagVal] == nil || (weightVal != nil && weightVal.(int) >= (*weightMap)[k][tagVal].(int)) {
					(*weightMap)[k][tagVal] = weightVal.(int)
					td.SortKV.AddKey(tagVal, td_v)
					thisTrHasMatch = true
				}
			} else {
				(*weightMap)[k][tagVal] = weightVal.(int)
			}
		}
	}
	if isAddToMatchMap && !filterValue.MatchString(td_v) && td_v != "" {
		(*matchMap)[k][ContactInfoVagueReg.FindString(td_k)] = true
	}
	return thisTrHasMatch
}

// 采购人在联系人、电话后面的处理
func (tn *Table) hasIndexMap(thisTdKvs []*u.Kv, indexMap *map[int]string, tdAscFind bool) bool {
	//采购人在联系人、电话后面的处理
	isCanAddToIndexMap := false
LL:
	for _, td_kv := range thisTdKvs {
		//1.处理带括号的()[]【】采购单位，代理机构；2.识别采购单位联系人、联系电话、代理机构联系人、联系电话
		goOnFunc, isContinue, td_k := tn.tdKV(td_kv.Key, nil, &isCanAddToIndexMap, indexMap, "LL")
		if !goOnFunc {
			break LL
		}
		if isContinue {
			continue
		}
		if len(*indexMap) == 0 {
			for _, k := range HasOrderContactType(td_k) { //采购单位，代理机构
				if !ContactType[k].MatchString(td_k) {
					continue
				}
				if isCanAddToIndexMap && len(*indexMap) == 0 {
					(*indexMap)[0] = k
					break
				}
			}
		}
	}
	if len(*indexMap) > 0 {
		tdAscFind = false
	}
	return tdAscFind
}

// 和|以?及|与|、多个词和在一起
func (tn *Table) tdsMultipleWords(jumpNextTd bool, td *TD, td_index int, tr *TR, thisTrHasMatch bool, indexMap map[int]string) (jump, thisTr bool) {
	if !jumpNextTd && len([]rune(td.Text)) >= 5 && len([]rune(td.Text)) <= 15 && regSplit.MatchString(td.Text) && td_index+1 < len(tr.TDs) {
		thisTdVals := regSplit.Split(td.Text, -1)
		nextTdVals := MultipleValueSplitReg.Split(tr.TDs[td_index+1].Val, -1)
		if len(thisTdVals) == len(nextTdVals) { //本次和下个长度相等
			for _, k := range HasOrderContactType(td.Text) { //采购单位，代理机构
				if ContactType[k].MatchString(td.Text) { //采购单位，代理机构
					for thisTdVals_k, thisTdVals_v := range thisTdVals {
						thisTdVals_v = strings.TrimSpace(thisTdVals_v)
						if ContactType[k].MatchString(thisTdVals_v) { //采购单位，代理机构
							thisTrHasMatch = true
							tr.TDs[td_index+1].SortKV.AddKey(thisTdVals_v, nextTdVals[thisTdVals_k])
							continue
						}
						if !ContactInfoMustReg.MatchString(thisTdVals_v) {
							continue
						}
						jumpNextTd = true
						thisTrHasMatch = true
						tr.TDs[td_index+1].SortKV.AddKey(k+thisTdVals_v, nextTdVals[thisTdVals_k])
					}
					break
				}
			}
			if len(indexMap) > 0 {
				_, onlyContactType := u.FirstKeyValueInMap(indexMap)
				if myContactType, _ := onlyContactType.(string); myContactType != "" {
					for thisTdVals_k, thisTdVals_v := range thisTdVals {
						thisTdVals_v = strings.TrimSpace(thisTdVals_v)
						if ContactInfoMustReg.MatchString(thisTdVals_v) {
							jumpNextTd = true
							thisTrHasMatch = true
							tr.TDs[td_index+1].SortKV.AddKey(myContactType+thisTdVals_v, nextTdVals[thisTdVals_k])
						}
					}
				}
			}
		}
	} else {
		jumpNextTd = false
	}
	return jumpNextTd, thisTrHasMatch
}

// 采购单位，代理机构
func (tn *Table) tdHasOrderContactType(td_k string, indexMap *map[int]string, tr *TR, prevCanAddToIndexMap, isCanAddToIndexMap, matchPrevFlag *bool, td_index int) (gotoFunc bool) {
	for _, k := range HasOrderContactType(td_k) { //采购单位，代理机构
		if !ContactType[k].MatchString(td_k) {
			continue
		}
		if len(*indexMap) == 0 {
			if (*isCanAddToIndexMap) || (*prevCanAddToIndexMap && len(tr.TDs) == 1) {
				myPrevTdVal := ""
				if td_index-2 >= 0 {
					myPrevTdVal = tr.TDs[td_index-2].Val
				}
				if myPrevTdVal != "" && len([]rune(myPrevTdVal)) < 10 && ContactInfoMustReg.MatchString(myPrevTdVal) {
					(*matchPrevFlag) = true
				}
				(*indexMap)[0] = k
				break
			}
		} else {
			(*indexMap) = map[int]string{}
			return false
		}
	}
	return true
}

// 1.处理带括号的()[]【】采购单位，代理机构；2.识别采购单位联系人、联系电话、代理机构联系人、联系电话
func (tn *Table) tdKV(key string, matchPrevFlag, isCanAddToIndexMap *bool, indexMap *map[int]string, gotoName string) (goOnFunc, isContinue bool, td_k string) {
	td_k = FilterContactKey(key) //带括号的()[]【】采购单位，代理机构处理
	td_k_length := len([]rune(td_k))
	if td_k_length < 2 || td_k_length > 15 {
		return true, true, "" //继续执行，跳过当前循环
	}
	isContinue = ContactInfoMustReg.MatchString(td_k) //识别采购单位联系人、联系电话、代理机构联系人、联系电话
	if isContinue || (ContactInfoVagueReg.MatchString(td_k) && !ContactInfoExcluReg.MatchString(td_k) && u.IsMapHasValue(td_k, ContactType)) {
		if gotoName == "LS" && !(*matchPrevFlag) && len(*indexMap) > 0 {
			(*indexMap) = map[int]string{}
			return false, false, "" //中断外层循环
		}
		if gotoName == "LL" && len(*indexMap) > 0 {
			(*indexMap) = map[int]string{}
			return false, false, ""
		}
		(*isCanAddToIndexMap) = true
	}
	return true, false, td_k //继续执行，不结束当前循环，返回处理后的值
}

// 获取td冒号kv
func (tn *Table) tdkv(td *TD) []*u.Kv {
	thisTdKvs := colonkvEntity.GetKvs(td.Text, tn.Desc, 2) //获取冒号kv
	//获取冒号
	if len(thisTdKvs) == 0 {
		tdValue := regReplAllSpace.ReplaceAllString(td.Text, "") //去除空格换行
		if tdValue != "" && len([]rune(tdValue)) < 10 {
			thisTdKvs = append(thisTdKvs, &u.Kv{
				Key:   tdValue,
				Value: "",
			})
		}
	}
	return thisTdKvs
}

func (table *Table) extractPriceNumber() {
	lineMapArr := make(map[string]*SortMap)
	lineMap := make(map[string]*SortMap)
	lineMapArr, lineMap = initLineMapLineMapArr(table) //不同数据类型的数据组合
	//qutil.Debug("lineMapArr----", lineMapArr)
	if len(lineMapArr) > 0 {
		for _, arrMap := range lineMapArr {
			resultArrMap := table.matchMapArrPrinceNumber(arrMap) //最终数据
			//qutil.Debug("resultArrMap-------------------", resultArrMap)
			//处理数组长度不一致情况
			if len(resultArrMap) > 0 {
				numLen := len(resultArrMap["number"])
				priceLen := len(resultArrMap["price"])
				itemLen := len(resultArrMap["item"])
				maxNum := numLen //获取最大长度
				if numLen == 0 { //没有
					maxNum = priceLen
				}
				//取个数数据的长度为基准(数据长度可能不一致)
				if numLen != priceLen && numLen > 0 && priceLen > 0 { //有number和price数据且长度不同，进行数据增减补齐
					if priceLen > numLen { //price多，删
						tmpArr := resultArrMap["price"]
						resultArrMap["price"] = tmpArr[:numLen]
					} else if priceLen < numLen { //price少，补空
						for {
							resultArrMap["price"] = append(resultArrMap["price"], "")
							//qutil.Debug("=============price==============")
							if len(resultArrMap["price"]) == numLen {
								break
							}
						}
					}
				}
				if maxNum > 0 && itemLen > 0 && maxNum != itemLen { //有price或者number,item长度保持一致
					if itemLen > maxNum {
						tmpArr := resultArrMap["item"]
						resultArrMap["item"] = tmpArr[:maxNum]
					} else if itemLen < maxNum {
						for {
							resultArrMap["item"] = append(resultArrMap["item"], "")
							//qutil.Debug("=============item==============")
							if len(resultArrMap["item"]) == maxNum {
								break
							}
						}
					}
				}
				//封装成一一对应数据
				/*
					{
						"price"	:["123","125"],
						"number" :["1","12"]
					}
					转换为：
					[
						{"price":"123","number":"1"},
						{"price":"125","number":"12"}
					]
				*/
				finishData := []map[string]interface{}{}
				//qutil.Debug("maxNum--------------------", maxNum)
				for t := 0; t < maxNum; t++ {
					tmpMap := make(map[string]interface{})
					if len(resultArrMap["number"]) > 0 {
						number := resultArrMap["number"][t]
						tmpMap["number"] = number
					}
					if len(resultArrMap["price"]) > 0 {
						price := resultArrMap["price"][t]
						tmpMap["price"] = price
					}
					if len(resultArrMap["item"]) > 0 {
						item := resultArrMap["item"][t]
						runeItem := []rune(qutil.ObjToString(item))
						if len(runeItem) > 50 {
							tmpMap["item"] = string(runeItem[:50])
						} else {
							tmpMap["item"] = item
						}
					}
					finishData = append(finishData, tmpMap)
				}
				//qutil.Debug(finishData)
				if len(finishData) > 0 {
					table.PriceNumberData = append(table.PriceNumberData, finishData)
				}
			}
		}
	}
	if len(lineMap) > 0 {
		for _, strMap := range lineMap {
			resultStrMap := table.matchMapPrinceNumber(strMap)
			//qutil.Debug("resultStrMap---", resultStrMap)
			if len(resultStrMap) > 0 {
				if resultStrMap["price"] != nil || resultStrMap["number"] != nil { //有price或者number在保存
					if item := qutil.ObjToString(resultStrMap["item"]); item != "" { //item过长截取
						runeItem := []rune(item)
						if len(runeItem) > 50 {
							resultStrMap["item"] = string(runeItem[:50])
						}
					}
					finishData := []map[string]interface{}{}
					finishData = append(finishData, resultStrMap)
					//qutil.Debug("finishData---", finishData)
					if len(finishData) > 0 {
						table.PriceNumberData = append(table.PriceNumberData, finishData)
					}
				}
			}
		}
	}
	//qutil.Debug("table.PriceNumberData---------", table.PriceNumberData)
}

// 数组数据抽取price和number
func (table *Table) matchMapArrPrinceNumber(arrMap *SortMap) map[string][]interface{} {
	result := make(map[string][]interface{}) //最终存储数据
	for _, key := range arrMap.Keys {
		val := arrMap.Map[key].([]string)
		for f, reg := range u.PriceNumberReg {
			key = tabletitleclear2.ReplaceAllString(key, "") //过滤
			if reg.MatchString(key) {                        //匹配成功
				//qutil.Debug("arr----key", key, val, f)
				tmp := []interface{}{}
				if f == "price" {
					tmp = dealPriceInterface(key, val...) //处理金额，单位转换
				} else if f == "number" {
					tmp = dealNumberInterface(val...) //处理数量
				} else {
					for _, v := range val {
						tmp = append(tmp, v)
					}
				}
				if len(tmp) > 0 {
					result[f] = tmp
				}

			}
		}
	}
	return result
}

// 字符串数据抽取price和number
func (table *Table) matchMapPrinceNumber(strMap *SortMap) map[string]interface{} {
	result := make(map[string]interface{})
	for _, key := range strMap.Keys {
		val := qutil.ObjToString(strMap.Map[key])
		for f, reg := range u.PriceNumberReg {
			key = tabletitleclear2.ReplaceAllString(key, "") //过滤
			if reg.MatchString(key) {                        //匹配成功
				//qutil.Debug("str----key", key, val)
				if f == "price" {
					if len(regHz.FindAllString(val, -1)) > 5 { //price中汉字过多视为内容错误
						continue
					}
					tmp := dealPriceInterface(key, val)[0] //处理金额，单位转换
					result[f] = tmp
				} else if f == "number" {
					tmp := dealNumberInterface(val)[0]
					result[f] = tmp
				} else {
					result[f] = val
				}
			}
		}
	}
	return result
}

// table中抽取品牌,table.BrandData
func (table *Table) analyBrand() {
	//5c2d8c05a5cb26b9b782572b
	//产品名称 品牌 规格 单价 单位 数量  小计 质保期
	lineMapArr := make(map[string]*SortMap)
	lineMap := make(map[string]*SortMap)
	brandRule := u.BrandRules
	//初始化lineMapArr,lineMap;
	lineMapArr, lineMap = initLineMapLineMapArr(table) //处理数组数据后,匹配必须title和替换要保存的title
	//qutil.Debug("lineMapArr----", len(lineMapArr))
	if len(lineMapArr) > 0 {
		for _, aMap := range lineMapArr {
			maxNum := 0    //记录最大长度
			arrcount1 := 0 //记录key是否存在必须title(数组数据)
			arrcount2 := 0
			ka := make(map[string][]string) //最终存储数据
			//qutil.Debug("aMap.Keys----", aMap.Keys)
			//匹配商品规则
			arrcount1, arrcount2, ka = table.matchMapArrBrandRule(aMap, brandRule, ka, arrcount1, arrcount2)
			//找最终存储数据的最小len(arr)
			//			for _, vf := range ka {
			//				//找最短的数组
			//				lenVal := len(vf)
			//				if minNum == 0 || minNum > lenVal { //maxNum = len(最短数组)
			//					minNum = lenVal
			//				}
			//			}
			//找最终存储数据的最大len(arr),小的补空
			for _, vf1 := range ka {
				lenVal := len(vf1)
				if lenVal > maxNum {
					maxNum = lenVal
				}
			}
			//table.BrandData商品存储
			finishKa := make(map[string][]string)
			for vf2K, vf2 := range ka {
				if len(vf2) < maxNum {
					if vf2K == "unitprice" { //价格的当前总数比最大的总数小就跳过，可能是总价格而不是单个的价格
						continue
					}
					lenMv := maxNum - len(vf2)
					for i := 0; i < lenMv; i++ {
						vf2 = append(vf2, "")
					}
				}
				finishKa[vf2K] = vf2
			}
			hasKey(table, arrcount1) //是否匹配到table中的标题
			//qutil.Debug("finishKa----", finishKa)
			if arrcount1 >= 1 {
				if arrcount1+arrcount2 == 1 { //删除只匹配到一个价钱(总价)
					delete(finishKa, "unitprice")
				}
				finishData := dealArrData(maxNum, finishKa)
				table.BrandData = append(table.BrandData, finishData) //存储table.BrandData
			}
		}
	}
	//处理string数据后,匹配必须title和替换要保存的title
	//qutil.Debug("lineMap----", len(lineMap))
	if len(lineMap) > 0 {
		for _, sMap := range lineMap {
			strcount1 := 0 //记录key是否存在必须title(字符串数据)
			strcount2 := 0
			endStrMap := make(map[string]string)
			//qutil.Debug(k, "aMap.Keys----", sMap.Keys)
			//匹配商品规则
			strcount1, strcount2, endStrMap = table.matchMapBrandRule(sMap, brandRule, endStrMap, strcount1, strcount2)
			//原始字符串数据处理
			hasKey(table, strcount1) //是否匹配到table中的标题
			//qutil.Debug("endStrMap----", endStrMap)
			if strcount1 >= 1 {
				if strcount1+strcount2 == 1 { //删除只匹配到一个价钱(总价)
					delete(endStrMap, "unitprice")
				}
				finishData := dealStrData(endStrMap) //处理数据
				if len(finishData) > 0 {
					table.BrandData = append(table.BrandData, finishData)
				}
			}
		}
	}
}

// 字符串匹配商品规则
func (table *Table) matchMapBrandRule(sMap *SortMap, brandRule map[string]map[string]string, endStrMap map[string]string, strcount1, strcount2 int) (int, int, map[string]string) {
	for _, k1 := range sMap.Keys {
		match := false //记录must是否匹配到
		v1 := qutil.ObjToString(sMap.Map[k1])
		//	for k1, v1 := range sMap {
		//qutil.Debug(k1, "++++++++++", v1)
		if v1 == "" {
			continue
		}
		//匹配必须title
		for nameM, r := range brandRule["must"] {
			if convert(k1, r) { //匹配成功
				v1tmp1 := v1
				match = true
				if nameM == "itemname" || nameM == "modal" { //特殊处理itemname
					hasGoods(table, v1)
					if nameM == "itemname" {
						v1tmp1 = filterItem(v1)[0] //过滤itemname
						if v1tmp1 == "" {
							break
						}
					}
				}
				if nameM == "brandname" || nameM == "modal" { //特殊处理brandname
					if endStrMap["brandname"] == "" {
						brand, allNull := hasBrand(table, v1)
						if !allNull {
							endStrMap["brandname"] = brand[0]
						}
					}
				}
				//unitprice
				if nameM == "unitprice" { //处理金额
					v1tmp1 = dealPrice(k1, v1)[0]
				}
				if nameM != "brandname" && endStrMap[nameM] == "" {
					endStrMap[nameM] = v1tmp1
				}
				strcount1++
			}
		}
		//替换其它要保存字段
		if !match {
			for nameR, r := range brandRule["replace"] {
				if convert(k1, r) { //匹配成功
					v1tmp2 := v1
					//totalprice
					if nameR == "totalprice" { //处理金额
						v1tmp2 = dealPrice(k1, v1)[0]
					}
					//number
					if nameR == "number" { //处理数量
						varr1, uname1 := dealNumber(v1)
						v1tmp2 = varr1[0]
						//从number中获取到的单位
						if endStrMap["unitname"] == "" && uname1[0] != "" {
							endStrMap["unitname"] = uname1[0]
						}
					}
					if v1tmp2 != "" {
						endStrMap[nameR] = v1tmp2
					}
					strcount2++
				}
			}
		}
		//}
	}
	return strcount1, strcount2, endStrMap
}

// 数组匹配商品规则
func (table *Table) matchMapArrBrandRule(aMap *SortMap, brandRule map[string]map[string]string, ka map[string][]string, arrcount1, arrcount2 int) (int, int, map[string][]string) {
	for _, k0 := range aMap.Keys {
		match := false //记录must是否匹配到
		v0 := aMap.Map[k0].([]string)
		//匹配必须title
		for nameM, r := range brandRule["must"] {
			if convert(k0, r) { //匹配成功
				v0tmp1 := v0
				match = true
				if len(ka[nameM]) != 0 && strings.Contains(k0, "描述") { //防止k0匹配到多次 和特殊情况 物料名称 物料描述同时出现
					continue
				}
				if nameM == "itemname" || nameM == "modal" {
					hasGoods(table, v0...) //判断itemname和modal中有没有商品
					if nameM == "itemname" {
						v0tmp1 = filterItem(v0...) //过滤itemname
					}
				}
				if nameM == "brandname" || nameM == "modal" {
					if len(ka["brandname"]) == 0 {
						brand, allNull := hasBrand(table, v0...)
						if !allNull {
							ka["brandname"] = brand
						}
					}
				}
				//unitprice
				if nameM == "unitprice" { //处理金额
					v0tmp1 = dealPrice(k0, v0...)
				}
				if nameM != "brandname" && len(ka[nameM]) == 0 {
					ka[nameM] = v0tmp1
				}
				arrcount1++
			}
		}
		//替换其它要保存字段
		if !match { //must未匹配，匹配replace
			for nameR, r := range brandRule["replace"] {
				if convert(k0, r) { //匹配成功
					v0tmp2 := v0
					//totalprice
					if nameR == "totalprice" { //处理金额
						v0tmp2 = dealPrice(k0, v0...)
					}
					//number
					if nameR == "number" { //处理数量
						uname0 := []string{}
						v0tmp2, uname0 = dealNumber(v0...)
						if len(ka["unitname"]) == 0 && len(uname0) != 0 {
							ka["unitname"] = uname0
						}
					}
					if len(v0tmp2) > 0 {
						ka[nameR] = v0tmp2
					}
					arrcount2++
				}
			}
		}
	}
	return arrcount1, arrcount2, ka
}
