package api

import (
	"baishuihu/db/model"
	"baishuihu/db/repo"
	"baishuihu/log"
	"errors"
	"time"

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

func Category(r *GinRouter) {
	r.POSTJWT("/category/create", CreateCategory)
	r.POSTJWT("/category/delete/:id", DeleteCategory)
	r.GET("/category/list", CategoryList)
	r.GET("/category/detail/:id", CategoryDetail)
	r.POSTJWT("/category/update", UpdateCategory)

}

func CreateCategory(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var category model.Category
	err := c.ShouldBindJSON(&category)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	if len(category.Pid) == 0 {
		category.Pid = "top"
	}
	category.CreateTime = time.Now()
	category.UpdateTime = time.Now()
	return repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionCategory, &category)
}

func DeleteCategory(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	_id := c.Param("id")
	id, _ := primitive.ObjectIDFromHex(_id)
	if id.IsZero() {
		return nil, errors.New("id错误")
	}
	return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionCategory, _id)
}

func CategoryList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	page, size, query := UtilQueryPageSize(c)
	return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
		CollectName: repo.CollectionCategory,
		Page:        page,
		Size:        size,
		Query:       query,
		Sort:        bson.D{bson.E{Key: "sort", Value: 1}, bson.E{Key: "createTime", Value: 1}},
	})
}

func CategoryDetail(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	_id := c.Param("id")
	id, _ := primitive.ObjectIDFromHex(_id)
	if id.IsZero() {
		return nil, errors.New("id错误")
	}
	cate := &model.Category{}
	found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
		CollectName: repo.CollectionCategory,
		Query:       repo.Map{"_id": id},
	}, cate)
	if err != nil {
		log.Error(err)
		return nil, err
	}

	if !found {
		return nil, errors.New("未找到该数据")
	}
	return cate, nil
}

func UpdateCategory(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var cate model.Category
	err := c.ShouldBindJSON(&cate)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	if cate.Id.IsZero() {
		return nil, errors.New("id错误")
	}
	return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionCategory, cate.Id.Hex(), &cate)
}
