package backend

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

func GetOneNews(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
	newsService := news_service.News{}

	if ("administrator" == group) {
		newsService = news_service.News{
			Id:       id,
			PageNum:  util.GetPage(c),
			PageSize: util.GetLimit(c),
		}
	} else {
		newsService = news_service.News{
			Id:         id,
			PlatformId: platform_id,
			PageNum:    util.GetPage(c),
			PageSize:   util.GetLimit(c),
		}
	}

	news, err := newsService.GetAll()
	if err != nil {
		handler.SendResponse(c, errno.ErrNewsNotFound, nil)
		return
	}

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

func GetNews(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()
		}
	}

	newsService := news_service.News{
		PlatformId: platform_id,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

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

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

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

	handler.SendResponse(c, nil, data)
}

func AddNews(c *gin.Context) {
	news := validate_service.News{}
	c.ShouldBindJSON(&news)

	//方法一
	if ok, errors := validate_service.ValidateInputs(news); !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 news.PlatformId != 0 {
			platform_id = news.PlatformId
		}
	}

	newsService := news_service.News{
		Title:      news.Title,
		Content:    news.Content,
		Top:        news.Top,
		Highlight:  news.Highlight,
		PlatformId: platform_id,
	}

	newsService.Add()

	handler.SendResponse(c, nil, nil)
}

func EditNews(c *gin.Context) {
	news := validate_service.EditNews{}
	c.ShouldBindJSON(&news)

	//方法一
	if ok, errors := validate_service.ValidateInputs(news); !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 news.PlatformId != 0 {
			platform_id = news.PlatformId
		}
	}

	newsService := news_service.News{
		Id:         news.Id,
		Title:      news.Title,
		Content:    news.Content,
		Top:        news.Top,
		Highlight:  news.Highlight,
		PlatformId: platform_id,
	}

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

	handler.SendResponse(c, nil, nil)
}

func DeleteNews(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
	}

	newsService := news_service.News{Id: id}
	exists, err := newsService.ExistById()
	if err != nil {
		handler.SendResponse(c, errno.ErrNewsNotFound, nil)
		return
	}

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

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

	handler.SendResponse(c, nil, nil)
}
