package app

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

func GetLiveBanners(c *gin.Context) {
	valid := validation.Validation{}
	platform_id, _ := strconv.Atoi(c.Request.Header.Get("FZM-PLATFORM-ID"))
	valid.Min(platform_id, 1, "platform_id").Message("平台Id不能为空")

	if valid.HasErrors() {
		handler.SendResponse(c, valid.Errors[0], nil)
		return
	}

	bannerService := live_banner_service.LiveBanner{
		PlatformId: platform_id,
		Status:     1,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

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

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

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

	handler.SendResponse(c, nil, data)
}

func GetLiveBanner(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 = id
	if ("administrator" != group && id != user.UserInfo.PlatformId) {
		handler.SendResponse(c, errno.ErrUserTokenIncorrect, nil)
		return
	}

	bannerService := live_banner_service.LiveBanner{Id: platform_id}
	exists, err := bannerService.ExistById()

	if err != nil {
		handler.SendResponse(c, errno.ErrLiveBannerNotFound, nil)
		return
	}

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

	banner, err := bannerService.Get()
	if err != nil {
		handler.SendResponse(c, errno.ErrLiveBannerNotFound, nil)
		return
	}

	handler.SendResponse(c, nil, banner)
}
