package router

import (
	"exam_system/dao"
	"exam_system/entity"
	"exam_system/result"
	"exam_system/utils"
	"github.com/gin-gonic/gin"
	"strings"
)

func Exam(router *RouterPlus) {

	// 查看个人考试列表
	router.GET("/exam/list",ExamInfoList)

	r := router.Group("/admin")
	{

		// 添加考试
		r.POST("/exam", AdminAddExam)

		// 获取考试
		r.GET("/exam/:id", AdminGetExam)

		// 获取考试列表
		r.GET("/exam/list", AdminExamList)

		// 修改考试
		r.PUT("/exam", AdminUpdateExam)

		// 删除考试
		r.DELETE("/exam/:ids", AdminDeleteExam)
	}

}


func ExamInfoList(c *gin.Context)*result.Result{
	page, size, sort, query, err := utils.Page(c)
	if err!=nil{
		return result.PARAM_ERROR
	}
	uid, exists := c.Get("id")
	if !exists{
		return result.UNAUTHORIZED
	}
	return dao.ExamInfoList(page,size,sort,query,uid.(int))
}

func AdminAddExam(c *gin.Context) *result.Result {
	var exam entity.Exam
	err := c.ShouldBindJSON(&exam)
	if err != nil || exam.StartAt.IsZero() || exam.EndAt.IsZero() || exam.PublishAt.IsZero() || exam.Duration == 0 || exam.ClassIds == "" || exam.TpId == 0 {
		return result.PARAM_ERROR
	}

	return dao.AddExam(&exam)
}

func AdminGetExam(c *gin.Context) *result.Result {
	id := c.Param("id")
	if id == "" {
		return result.UNKNOW_ERROR
	}
	return dao.ExamDetail(id)
}

func AdminExamList(c *gin.Context) *result.Result {
	page, size, sort, query, err := utils.Page(c)
	if err != nil {
		return result.PARAM_ERROR
	}
	return dao.ExamList(page, size, sort, query)
}

func AdminUpdateExam(c *gin.Context) *result.Result {
	var exam entity.Exam
	err := c.ShouldBindJSON(&exam)
	if err != nil || exam.Id == 0 || exam.StartAt.IsZero() || exam.PublishAt.IsZero() || exam.EndAt.IsZero() || exam.Duration == 0 || exam.ClassIds == "" || exam.TpId == 0 {
		return result.PARAM_ERROR
	}
	return dao.UpdateExam(&exam)
}

func AdminDeleteExam(c *gin.Context) *result.Result {
	idStr := c.Param("ids")
	if idStr == "" {
		return result.PARAM_ERROR
	}

	ids := strings.Split(idStr, ",")

	return dao.DeleteExams(ids)
}
