// track
package track

import (
	db "jy/mongodbutil"
	qu "qfw/util"
	"strings"
)

//获取抽取路径
func GetTrackPath(_id, field, table, resultcoll string) map[string]interface{} {
	tracks := map[string]interface{}{}      //返回对象
	fieldvals := []map[string]interface{}{} //抽取结果数组
	info, _ := db.Mgo.FindById(resultcoll, _id, `{"result":1}`)
	if result, ok := (*info)["result"].(map[string]interface{}); ok {
		for k, v := range result {
			if k == field {
				if tmps, ok := v.([]interface{}); ok {
					for _, tmp := range tmps {
						if t, ok := tmp.(map[string]interface{}); ok {
							fieldvals = append(fieldvals, t)
						}
					}
				}
				break
			}
		}
	}
	//获取路径
	for _, val := range fieldvals {
		code := qu.ObjToString(val["code"])
		paths := []map[string]interface{}{}
		list, _ := db.Mgo.Find(table, `{"sid":"`+_id+`"}`, nil, `{"name":1,"code":1,"type":1,"ruletext":1,"extinfo":1}`, false, -1, -1)
		for _, info := range *list {
			fieldobject, _ := info["extinfo"].(map[string]interface{})
			if fieldvs, ok := fieldobject[field].([]interface{}); ok {
				for _, v := range fieldvs {
					if tmp, ok := v.(map[string]interface{}); ok {
						if code == tmp["code"] {
							path := map[string]interface{}{
								"type": info["type"],
								"code": info["code"],
								"name": info["name"],
								//"ruletext":  info["ruletext"],
								"value":     tmp["value"],
								"extfrom":   tmp["extfrom"],
								"matchtype": tmp["matchtype"],
								"kvtype":    tmp["type"],
							}
							paths = append(paths, path)
						}
					}
				}
			}
		}
		tracks[code] = paths
	}
	//针对lua抽取kv路径拆分
	luatracks := map[string][]map[string]interface{}{}
	for k, v := range tracks {
		if strings.Contains(k, "CL") ||strings.Contains(k, "JsonData"){
			track, _ := v.([]map[string]interface{})
			for _, val := range track { //按code，kvtype，matchtype分组
				code := k + "_" + qu.ObjToString(val["kvtype"]) + "_" + qu.ObjToString(val["matchtype"])
				tmps := luatracks[code]
				if tmps == nil {
					tmps = []map[string]interface{}{}
				}
				tmps = append(tmps, val)
				luatracks[code] = tmps
			}
			delete(tracks, k)
		}
	}
	for k, v := range luatracks {
		tracks[k] = v
	}
	return tracks
}
