package app

import (
	"bwallet/pkg/errno"
	"bwallet/pkg/handler"
	"bwallet/pkg/util"
	"bwallet/service/article_service"
	"github.com/Unknwon/com"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"strconv"
)

func GetOneArticle(c *gin.Context) {
	id := com.StrTo(c.DefaultQuery("id", "0")).MustInt()
	valid := validation.Validation{}
	valid.Min(id, 1, "id").Message("Id必须大于0")
	if valid.HasErrors() {
		handler.SendResponse(c, valid.Errors[0], nil)
		return
	}

	articleService := article_service.Article{Id: id}
	exists, err := articleService.ExistById()
	if err != nil || !exists {
		handler.SendResponse(c, errno.ErrArticleNotFound, nil)
		return
	}

	article, err := articleService.Get()
	if err != nil {
		handler.SendResponse(c, errno.ErrArticleNotFound, nil)
		return
	}

	handler.SendResponse(c, nil, article)
}

func GetArticle(c *gin.Context) {
	platform_id, _ := strconv.Atoi(c.Request.Header.Get("FZM-PLATFORM-ID"))
	valid := validation.Validation{}
	valid.Min(platform_id, 1, "platform_id").Message("平台Id不能为空")
	if valid.HasErrors() {
		handler.SendResponse(c, valid.Errors[0], nil)
		return
	}
	articleService := article_service.Article{
		PlatformId: platform_id,
		SearchType: -1,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

	total, err := articleService.Count()
	if err != nil {
		handler.SendResponse(c, errno.ErrCountArticle, nil)
		return
	}

	article, err := articleService.GetAll()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	data := make(map[string]interface{})
	data["items"] = article
	data["total"] = total

	handler.SendResponse(c, nil, data)
}
