package api

import (
	"mesh/db/repo"
	"time"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"infish.cn/comm"
)

// 创建数据库分类api
func CreateDatabaseCategoryRouter(router *GinRouter) {

	//创建分类定义
	router.POSTJWT("/user/category/:scope", func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
		scope := c.Param("scope")
		if len(scope) < 1 || !primitive.IsValidObjectID(apictx.User.Parent) {
			return nil, NewError("Id参数非法!")
		}

		body := &comm.DbCategory{}
		c.ShouldBindJSON(body)
		body.UserId, _ = primitive.ObjectIDFromHex(apictx.User.Parent)
		body.Scope = scope

		body.CreateTime = time.Now()
		if body.Id.IsZero() {
			body.CreateTime = time.Now()
		} else {
			body.UpdateTime = time.Now()
		}

		curr := &comm.DbCategory{}
		ok, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
			CollectName: repo.CollectionCategories,
			Project:     []string{"_id"},
			Query:       repo.Map{"userId": body.UserId, "scope": body.Scope},
		}, curr)
		if err != nil {
			return nil, err
		}

		if !ok { //没有查询到新增
			id, err := repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionCategories, body)
			if err != nil {
				return nil, err
			}
			body.Id, _ = primitive.ObjectIDFromHex(id)
			return body, nil
		}

		body.Id = primitive.NilObjectID
		return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionCategories, curr.Id.Hex(), body)
	})

	// //更新
	// router.POSTJWT("/dbcategory/update/:id", func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	// 	id := c.Param("id")
	// 	if len(id) < 1 {
	// 		return nil, NewError("数据库Id不能为空")
	// 	}
	// 	body := &model.DbCategory{}
	// 	c.ShouldBindJSON(body)
	// 	if len(body.Id) < 1 {
	// 		return nil, NewError("id不能为空")
	// 	}

	// 	optSet := repo.Map{}
	// 	if len(body.Name) > 0 {
	// 		optSet["categories.$.name"] = body.Name
	// 	}
	// 	if len(body.Value) > 0 {
	// 		optSet["categories.$.value"] = body.Value
	// 	}

	// 	option := &repo.ArrayOneUpdateOption{
	// 		CollectName: repo.CollectionDatabase,
	// 		Id:          id,
	// 		Query:       repo.Map{"categories.id": body.Id},
	// 		Set:         optSet,
	// 	}
	// 	return repo.RepoDocArrayOneUpdate(
	// 		apictx.CreateRepoCtx(),
	// 		option,
	// 	)
	// })

	//获取用户的所有分类定义和 资产分类定义
	router.GETJWT("/user/category/:scope", func(c *gin.Context, apictx *ApiSession) (interface{}, error) {

		scope := c.Param("scope")
		if len(scope) < 1 || !primitive.IsValidObjectID(apictx.User.Parent) {
			return nil, NewError("Id参数非法!")
		}

		uidObj, _ := primitive.ObjectIDFromHex(apictx.User.Parent)

		ok, ret := repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
			CollectName: repo.CollectionCategories,
			Query:       repo.Map{"userId": uidObj, "scope": scope},
		})
		if !ok {
			return nil, NewError("no find!")
		}
		return ret, nil
	})

	//创建资产分类
	router.POSTJWT("/user/assetcategory/:scope", func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
		scope := c.Param("scope")
		if len(scope) < 1 || !primitive.IsValidObjectID(apictx.User.Parent) {
			return nil, NewError("Id参数非法!")
		}

		body := &comm.DbAssetUserCategory{}
		c.ShouldBindJSON(body)
		body.UserId, _ = primitive.ObjectIDFromHex(apictx.User.Parent)
		body.Scope = scope

		body.CreateTime = time.Now()

		curr := &comm.DbAssetUserCategory{}
		ok, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
			CollectName: repo.CollectionDbAssetCategory,
			Project:     []string{"_id"},
			Query:       repo.Map{"userId": body.UserId, "scope": body.Scope},
		}, curr)
		if err != nil {
			return nil, err
		}

		if !ok { //没有查询到新增

			body.CreateTime = time.Now()
			id, err := repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionDbAssetCategory, body)
			if err != nil {
				return nil, err
			}
			body.Id, _ = primitive.ObjectIDFromHex(id)
			return body, nil
		}

		body.Id = primitive.NilObjectID
		body.UpdateTime = time.Now()

		return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionDbAssetCategory, curr.Id.Hex(), body)
	})

	router.GETJWT("/user/assetcategory/:scope", func(c *gin.Context, apictx *ApiSession) (interface{}, error) {

		scope := c.Param("scope")
		if len(scope) < 1 || !primitive.IsValidObjectID(apictx.User.Parent) {
			return nil, NewError("Id参数非法!")
		}
		uidObj, _ := primitive.ObjectIDFromHex(apictx.User.Parent)

		ok, ret := repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
			CollectName: repo.CollectionDbAssetCategory,
			Query:       repo.Map{"userId": uidObj, "scope": scope},
		})
		if !ok {
			return nil, NewError("no find!")
		}
		return ret, nil
	})

	router.GETJWT("/user/categoryconf/:scope", func(c *gin.Context, apictx *ApiSession) (interface{}, error) {

		scope := c.Param("scope")
		if len(scope) < 1 || !primitive.IsValidObjectID(apictx.User.Parent) {
			return nil, NewError("Id参数非法!")
		}
		uidObj, _ := primitive.ObjectIDFromHex(apictx.User.Parent)

		_, ret1 := repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
			CollectName: repo.CollectionCategories,
			Query:       repo.Map{"userId": uidObj, "scope": scope},
		})

		_, ret2 := repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
			CollectName: repo.CollectionDbAssetCategory,
			Query:       repo.Map{"userId": uidObj, "scope": scope},
		})

		return map[string]interface{}{
			"categories":      ret1,
			"assetCategories": ret2,
		}, nil
	})

	router.GET("/public/category/:cateId/:assetCateConfId", func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
		cateId := c.Param("cateId")
		assetCateConfId := c.Param("assetCateConfId")

		if !primitive.IsValidObjectID(cateId) || !primitive.IsValidObjectID(assetCateConfId) {
			return nil, NewError("Id参数非法!")
		}

		cateIdObj, _ := primitive.ObjectIDFromHex(cateId)
		ok, ret := repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
			CollectName: repo.CollectionCategories,
			Query:       repo.Map{"_id": cateIdObj},
		})
		if !ok {
			return nil, NewError("no find!")
		}

		assetCateIdObj, _ := primitive.ObjectIDFromHex(assetCateConfId)
		_, assetConf := repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
			CollectName: repo.CollectionDbAssetCategory,
			Query:       repo.Map{"_id": assetCateIdObj},
		})

		return map[string]interface{}{
			"categories":      ret,
			"assetCategories": assetConf,
		}, nil
	})
}
