package bullet_chat

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/models/request"
	responseModel "hongze/hongze_yb/models/response"
	"hongze/hongze_yb/services/bullet_chat"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/services/wx_app"
	"strconv"
)

// Add
// @Description 新增弹幕
// @Success 200 {string} string "操作成功"
// @Router /bullet_chat/add [post]
func Add(c *gin.Context) {
	userInfo := user.GetInfoByClaims(c)
	if userInfo.UserID <= 0 {
		response.Fail("请登录后操作", c)
		return
	}
	// 是否为备用小程序
	copyYb := c.Request.Header.Get("CopyYb")

	var req request.BulletChatAddReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.PrimaryId <= 0 {
		response.Fail("参数有误", c)
		return
	}
	if req.Content == "" {
		response.Fail("内容不可为空", c)
		return
	}
	if len([]rune(req.Content)) > 50 {
		response.Fail("内容不可超过50个字", c)
		return
	}
	// 敏感词校验
	// TODO:如果备用小程序提上master的话，此处要有调整(2022/11/08)
	if userInfo.RecordInfo.OpenID != "" && userInfo.RecordInfo.CreatePlatform == 6 {
		checkResult, e := wx_app.MsgSecCheck(userInfo.RecordInfo.OpenID, req.Content, copyYb)
		if e == nil {
			if checkResult.Result != nil && checkResult.Result.Suggest != "pass" {
				errMsg := "含有违禁词, 不允许发布: " + checkResult.Result.Suggest + ", 命中标签: " + strconv.Itoa(checkResult.Result.Label)
				response.FailMsg("内容含有违禁词, 不允许发布", errMsg, c)
				return
			}
		}
	}

	bc, e := bullet_chat.CreateBulletChat(int(userInfo.UserID), req.PrimaryId, req.Source, req.SourceAgent, req.Seconds, req.Content)
	if e != nil {
		response.FailMsg("发布失败", "新增弹幕失败, Err: "+e.Error(), c)
		return
	}
	resp := new(responseModel.BulletChatItem)
	resp.Id = bc.ID
	resp.UserId = bc.UserID
	resp.Content = bc.Content
	resp.Seconds = fmt.Sprint(bc.Seconds)
	resp.Color = bc.Color
	response.OkData("操作成功", resp, c)
}
