package bus

import (
	"context"
	"fmt"
	"queencount/db"
	"queencount/db/model"
	"queencount/db/repo"
	"time"

	"go.mongodb.org/mongo-driver/bson/primitive"
)

func AssetCountAction(actionName string, req *model.AssetEvent) {

	dbcxt := &repo.RepoSession{Client: db.MongoClient, Ctx: context.Background()}
	var in model.AssetCount

	var databaseDoc model.Database

	dbId, _ := primitive.ObjectIDFromHex(req.DbId)
	param := &repo.DocSearchOptions{
		// Db: "queentree",
		CollectName: repo.CollectionDatabase,
		Query:       map[string]interface{}{"_id": dbId},
		Project:     []string{"_id", "name", "assets"},
		// Sort: bson.M{},
	}

	// 获取对应资产库 - 数据库
	ok, err := repo.RepoSeachDoc(dbcxt, param, &databaseDoc)
	fmt.Printf("action database data =>\n%#v\n", databaseDoc)
	if err != nil || !ok {
		return
	}

	collection := ""
	for _, v := range databaseDoc.Assets {
		if v.Id == req.DefId {
			collection = v.Collection
		}
	}

	count, err := repo.RepoDbCountDoc(dbcxt, databaseDoc.Name, collection, repo.Map{})
	if err != nil {
		return
	}

	// 统计新增
	in.DefId = req.DefId
	if actionName == "add" {
		in.Count = int(count)

	}
	if actionName == "remove" {
		in.Count = int(count)
	}
	in.CreateTime = time.Now()
	id, _ := repo.RepoDbAddDoc(dbcxt, databaseDoc.Name, repo.CollectionAssetCount, &in)
	fmt.Printf("action add id =>\n%#v\n", id)
	fmt.Println("----------------------------------")
	fmt.Printf("action add data =>\n%#v\n", in)

}
