package router

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

func Term(router *RouterPlus) {

	r := router.Group("/admin")
	{
		// 添加学期
		r.POST("/term", AdminAddTerm)

		// 获取学期
		r.GET("/term/:id", AdminGetTerm)

		// 获取学期列表
		r.GET("/term/list", AdminTermList)

		// 修改学期
		r.PUT("/term", AdminUpdateTerm)

		// 删除学期
		r.DELETE("/term/:ids", AdminDeleteTerm)
	}

}

func AdminAddTerm(c *gin.Context) *result.Result {
	var term entity.Term
	err := c.ShouldBindJSON(&term)
	if err != nil || term.Name == "" {
		return result.PARAM_ERROR
	}

	return dao.AddTerm(&term)
}

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

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

func AdminUpdateTerm(c *gin.Context) *result.Result {
	var term entity.Term
	err := c.ShouldBindJSON(&term)
	if err != nil || term.Id == 0 {
		return result.PARAM_ERROR
	}
	return dao.UpdateTerm(&term)
}

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

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

	return dao.DeleteTerms(ids)
}
