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 SubmitExeamLog(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	db := c.Param("scope")
	exeamLog := &model.ExeamLog{}
	err := c.ShouldBindJSON(exeamLog)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	cid, _ := primitive.ObjectIDFromHex(exeamLog.Cid)
	if cid.IsZero() {
		return nil, errors.New("cid错误")
	}
	exeamLog.Uid = apictx.User.ID
	exeamLog.CreateTime = time.Now()
	exeamLog.UpdateTime = time.Now()
	return repo.RepoAddDbDoc(apictx.CreateRepoCtx(), db, repo.CollectionExeamLog, exeamLog)
}

// 考核记录列表
// /exeamLog/list/:scope?page=1&size=10&query={"uid":"xxx","type":"理论"}
func ExeamLogList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	db := c.Param("scope")
	if len(db) == 0 {
		return nil, errors.New("scope不能为空")
	}
	page, size, query := UtilQueryPageSize(c)
	if _, ok := query["uid"]; !ok {
		query["uid"] = apictx.User.ID
	}
	return repo.RepoDbPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
		Db:          db,
		CollectName: repo.CollectionExeamLog,
		Page:        page,
		Size:        size,
		Query:       query,
		Sort:        bson.M{"createTime": 1},
	})
}
