package backend

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

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

	status := com.StrTo(c.DefaultQuery("status", "0")).MustUint8()

	infoService := live_info_service.LiveInfo{
		Status:     status,
		PlatformId: int64(platform_id),
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

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

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

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

	handler.SendResponse(c, nil, data)
}

func AddLiveInfo(c *gin.Context) {
	info := validate_service.LiveInfo{}
	c.ShouldBindJSON(&info)

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

	infoService := live_info_service.LiveInfo{
		Title:      info.Title,
		Cover:      info.Cover,
		CategoryId: info.CategoryId,
		Duration:   info.Duration,
		Attendance: info.Attendance,
		Mode:       info.Mode,
		ApplyId:    info.ApplyId,
		Sort:       info.Sort,
	}

	if err := infoService.Add(); err != nil {
		handler.SendResponse(c, errno.ErrAddLiveBanner, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}

func VerifyLiveInfo(c *gin.Context) {
	info := validate_service.VerifyLiveInfo{}
	c.ShouldBindJSON(&info)

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

	infoService := live_info_service.LiveInfo{
		Id:     info.Id,
		Status: info.Status,
	}

	if err := infoService.Verify(); err != nil {
		handler.SendResponse(c, errno.ErrUpdateLiveInfo, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}
