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 Report(r *GinRouter) {
	r.POST("/report/create", CreateReport)
	r.POST("/report/delete/:id", DeleteReport)
	r.GET("/report/list", ReportList)
	r.GET("/report/detail/:id", ReportDetail)
	r.POST("/report/update", UpdateReport)

}

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

func DeleteReport(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.CollectionReport, _id)
}

func ReportList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	page, size, query := UtilQueryPageSize(c)
	return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
		CollectName: repo.CollectionReport,
		Page:        page,
		Size:        size,
		Query:       query,
		Sort:        bson.M{"createTime": -1},
	})
}

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