package front

import (
	"log"
	qu "qfw/util"
	"qua"
	"time"
	u "util"
)

func QuaFieldScore(field_tag []string, coll_name string) bool {
	if coll_name == "" || len(field_tag) <= 0 {
		return false
	}
	//查询标注表-临时测试-指定表
	start := int(time.Now().Unix())
	q := map[string]interface{}{}
	sess := u.Mgo.GetMgoConn()
	defer u.Mgo.DestoryMongoConn(sess)
	it := sess.DB(u.Mgo.DbName).C(coll_name).Find(&q).Iter()
	updateFieldScore, total := [][]map[string]interface{}{}, 0
	for tmp := make(map[string]interface{}); it.Next(&tmp); total++ {
		if total%1000 == 0 {
			log.Println("当前数量:", total)
		}
		update_dict := calculateFieldScore(tmp, field_tag)
		updateFieldScore = append(updateFieldScore, []map[string]interface{}{
			map[string]interface{}{"_id": tmp["_id"]},
			update_dict,
		})
		if len(updateFieldScore) >= 200 {
			u.Mgo.UpSertBulk(coll_name, updateFieldScore...)
			updateFieldScore = [][]map[string]interface{}{}
		}
		tmp = make(map[string]interface{})
	}
	if len(updateFieldScore) > 0 {
		u.Mgo.UpSertBulk(coll_name, updateFieldScore...)
	}
	log.Printf("处理耗时：%d秒~数量：%d个\n", int(time.Now().Unix())-start, total)

	if total <= 0 {
		return false
	}
	return true
}

//计算字段分
func calculateFieldScore(tmp map[string]interface{}, field_tag []string) map[string]interface{} {
	source := *qu.ObjToMap(tmp["field_source"])
	f_s := qua.FieldSourceScore(source) //打初始分
	update_dict := make(map[string]interface{}, 0)
	buyer_s := qua.BuyerFieldScore(tmp, f_s["buyer"])
	budget_s := qua.BudgetFieldScore(tmp, f_s["budget"])
	projectname_s := qua.ProjectnameFieldScore(tmp, f_s["projectname"])
	projectcode_s := qua.ProjectcodeFieldScore(tmp, f_s["projectcode"])

	update_dict["buyer"] = buyer_s
	update_dict["budget"] = budget_s
	update_dict["projectname"] = projectname_s
	update_dict["projectcode"] = projectcode_s

	subtype := qu.ObjToString(tmp["subtype"])
	if subtype == "中标" || subtype == "成交" || subtype == "合同" {
		s_winner_s := qua.WinnerFieldScore(tmp, f_s["s_winner"])
		update_dict["s_winner"] = s_winner_s
		bidamount_s := qua.BidamountFieldScore(tmp, f_s["bidamount"])
		update_dict["bidamount"] = bidamount_s
	}

	//综合比对是否正确 field_tag
	isUse, v_taginfo := true, make(map[string]interface{}, 0)
	for _, key := range field_tag {
		v_taginfo[key] = int64(1)
		value := *qu.ObjToMap(update_dict[key])
		score := qu.Int64All(value["score"])
		if score < 98 {
			isUse = false //需要标注
			break
		}
	}
	b_istagging := !isUse

	return map[string]interface{}{
		"$set": map[string]interface{}{
			"v_fieldscore": update_dict,
			"b_istagging":  b_istagging,
			"v_taginfo":    v_taginfo,
		},
	}
}
