package message

import (
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	message2 "hongze/hongze_yb/models/request/message"
	"hongze/hongze_yb/services/message"
	userService "hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"strconv"
	"strings"
)

func List(c *gin.Context)  {
	reqType := c.DefaultQuery("type", "0")
	reqPageIndex := c.DefaultQuery("current_index", "1")
	reqPageSize := c.DefaultQuery("page_size", strconv.Itoa(utils.PageSize20))

	if !strings.Contains("0,1,2", reqType) {
		response.Fail("请输入正确的消息类型", c)
		return
	}
	msgtype, err := strconv.Atoi(reqType)
	if err != nil {
		response.Fail("请输入正确的消息类型", c)
		return
	}

	pageIndex, err := strconv.Atoi(reqPageIndex)
	if err != nil {
		response.Fail("请输入正确的条数限制", c)
		return
	}
	pageSize, err := strconv.Atoi(reqPageSize)
	if err != nil {
		response.Fail("请输入正确的页码", c)
		return
	}
	userInfo := userService.GetInfoByClaims(c)
	data, err := message.GetList(userInfo, msgtype, pageIndex, pageSize)
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	response.OkData("查询成功", data, c)
	return
}

// BatchRead 一键已读
func BatchRead(c *gin.Context)  {
	var req message2.ReqMessageBatch
	if c.ShouldBind(&req) !=nil {
		response.Fail("参数异常", c)
		return
	}
	if !strings.Contains("0,1,2", strconv.Itoa(req.Type)) {
		response.Fail("请输入正确的消息类型", c)
		return
	}

	userInfo := userService.GetInfoByClaims(c)
    err := message.BatchRead(userInfo, req)
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	response.Ok("操作成功", c)
	return
}

// SingleRead 设置单条消息已读
func SingleRead(c *gin.Context)  {
	var req message2.ReqMessage
	if c.ShouldBind(&req) !=nil {
		response.Fail("参数异常", c)
		return
	}
	if req.MsgId <=0 {
		response.Fail("请输入正确的消息Id", c)
		return
	}

	userInfo := userService.GetInfoByClaims(c)
	err := message.SingleRead(userInfo, req)
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	response.Ok("操作成功", c)
	return
}

// SingleDelete 删除单条消息
func SingleDelete(c *gin.Context)  {
	var req message2.ReqMessage
	if c.ShouldBind(&req) !=nil {
		response.Fail("参数异常", c)
		return
	}
	if req.MsgId <=0 {
		response.Fail("请输入正确的消息Id", c)
		return
	}

	userInfo := userService.GetInfoByClaims(c)
	err := message.SingleDelete(userInfo, req)
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	response.Ok("操作成功", c)
	return
}