package api

import (
	"copter-train/db/model"
	"copter-train/db/repo"
	"copter-train/log"
	"errors"
	"time"

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

// 具体数据库中创建
func CreateLearnLog(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	db := c.Param("scope")
	if len(db) == 0 {
		return nil, errors.New("scope不能为空")
	}
	learnLog := &model.LearnLog{}
	err := c.ShouldBindJSON(learnLog)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	learnLog.Uid = apictx.User.ID
	zero := 0
	learnLog.LearnTime = &zero
	learnLog.CreateTime = time.Now()
	learnLog.UpdateTime = time.Now()
	return repo.RepoAddDbDoc(apictx.CreateRepoCtx(), db, repo.CollectionLearnLog, learnLog)
}

// 每分钟记录下学习时长
// sync/time/:id/:scope
func SyncLearnTime(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	id := c.Param("id")
	db := c.Param("scope")
	objId, _ := primitive.ObjectIDFromHex(id)
	if objId.IsZero() {
		return nil, errors.New("id错误")
	}
	update := bson.M{"$inc": bson.M{"learnTime": 1}, "updateTime": time.Now()}
	return repo.RepoUpdateDbSetDoc(apictx.CreateRepoCtx(), db, repo.CollectionLearnLog, id, update)
}

// func DeleteCategory(c *gin.Context, apictx *ApiSession) (interface{}, error) {
// 	// 验证是否为管理员
// 	isAdmin, err := IsAdmin(c, apictx)
// 	if err != nil {
// 		return nil, err
// 	}
// 	if !isAdmin {
// 		return nil, errors.New("没有权限")
// 	}
// 	_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
// }
