package backend

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

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, errno.ErrValidation, nil)
		return
	}

	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group
	var platform_id int
	platform_id = user.UserInfo.PlatformId
	articleService := article_service.Article{}

	if ("administrator" == group) {
		articleService = article_service.Article{
			Id:       id,
			PageNum:  util.GetPage(c),
			PageSize: util.GetLimit(c),
		}
	} else {
		articleService = article_service.Article{
			Id:         id,
			PlatformId: platform_id,
			PageNum:    util.GetPage(c),
			PageSize:   util.GetLimit(c),
		}
	}

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

	handler.SendResponse(c, nil, article)
	return
}

func GetArticle(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group

	var platform_id int
	platform_id = user.UserInfo.PlatformId
	if ("administrator" == group) {
		if arg := c.Query("platform_id"); arg != "" {
			platform_id = com.StrTo(c.Query("platform_id")).MustInt()
		}
	}

	articleService := article_service.Article{
		PlatformId: platform_id,
		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)
}

func AddArticle(c *gin.Context) {
	article := validate_service.Article{}
	c.ShouldBindJSON(&article)

	//方法一
	if ok, errors := validate_service.ValidateInputs(article); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group

	var platform_id int
	platform_id = user.UserInfo.PlatformId
	if ("administrator" == group) {
		if article.PlatformId != 0 {
			platform_id = article.PlatformId
		}
	}

	articleService := article_service.Article{
		Title:      article.Title,
		Source:     article.Source,
		LogoPic:    article.LogoPic,
		ImgUrl:     article.ImgUrl,
		Content:    article.Content,
		Top:        article.Top,
		Highlight:  article.Highlight,
		PlatformId: platform_id,
	}

	articleService.Add()

	handler.SendResponse(c, nil, nil)
}

func EditArticle(c *gin.Context) {
	article := validate_service.EditArticle{}
	c.ShouldBindJSON(&article)

	//方法一
	if ok, errors := validate_service.ValidateInputs(article); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group
	platform_id := user.UserInfo.PlatformId
	if ("administrator" == group) {
		if article.PlatformId != 0 {
			platform_id = article.PlatformId
		}
	}

	articleService := article_service.Article{
		Id:         article.Id,
		Title:      article.Title,
		Content:    article.Content,
		Source:     article.Source,
		LogoPic:    article.LogoPic,
		ImgUrl:     article.ImgUrl,
		Top:        article.Top,
		Highlight:  article.Highlight,
		PlatformId: platform_id,
	}

	if err := articleService.Edit(); err != nil {
		handler.SendResponse(c, errno.ErrUpdateArticle, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}

func DeleteArticle(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 {
		handler.SendResponse(c, errno.ErrArticleNotFound, nil)
		return
	}

	if !exists {
		handler.SendResponse(c, errno.ErrArticleNotFound, nil)
		return
	}

	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group
	if ("administrator" != group) {
		article, _ := articleService.Get()
		if article.PlatformId != user.UserInfo.PlatformId {
			handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
			return
		}
	}
	err = articleService.Delete()
	if err != nil {
		handler.SendResponse(c, errno.ErrDeleteArticle, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}
