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 Banner(r *GinRouter) {
	r.POSTJWT("/banner/create", CreateBanner)
	r.POSTJWT("/banner/delete/:id", DeleteBanner)
	r.GET("/banner/list", BannerList)
	r.GET("/banner/detail/:id", BannerDetail)
	r.POSTJWT("/banner/update", UpdateBanner)

}

func CreateBanner(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var banner model.Banner
	err := c.ShouldBindJSON(&banner)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	banner.CreateTime = time.Now()
	banner.UpdateTime = time.Now()
	return repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionBanner, &banner)
}

func DeleteBanner(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.CollectionBanner, _id)
}

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

func BannerDetail(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.Banner{}
	found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
		CollectName: repo.CollectionBanner,
		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 UpdateBanner(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var cate model.Banner
	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.CollectionBanner, cate.Id.Hex(), &cate)
}
