package post

import (
	"fmt"
	"mini_server/internal/dao"
	"mini_server/internal/server/help"
	"mini_server/internal/server/httpreply"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// 帖子评论处理逻辑

type UploadCommentRequest struct {
	Content string `json:"content" bingding:"min=1"`
}

// 发布帖子
func UploadComment(c *gin.Context) {
	reply := httpreply.NewDefaultReplyData()
	defer httpreply.Reply(c, reply)

	userId, ok := help.GetUserId(c)
	if !ok {
		reply.Status = http.StatusNotFound
		reply.Message = "无法获取用户信息"
		return
	}

	var param QueryURI
	if err := c.ShouldBindUri(&param); err != nil {
		reply.Status = http.StatusBadRequest
		reply.Message = fmt.Sprintf("invalid uri path,err:%v", err)
		return
	}

	var request UploadCommentRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		reply.Status = http.StatusBadRequest
		reply.Message = fmt.Sprintf("bad request, err:%v", err)
		return
	}

	data := dao.PostComment{
		UserId:  userId,
		PostId:  param.PostId,
		Content: request.Content,
	}
	if _, err := dao.PostComment_Insert(&data); err != nil {
		logrus.Errorf("评论上传失败，request:%v", request)
		reply.Status = http.StatusInternalServerError
		reply.Message = "评论上传失败"
		return
	}
}

type QueryCommentURI struct {
	PostId uint64 `uri:"post_id" binding:"min=1"`
}

type CommentInfo struct {
	CommentId uint64 `json:"comment_id"`
	Content   string `json:"content"`
	Time      string `json:"time"`
	UserId    int32  `json:"user_id"`
	Username  string `json:"username"`
	AvatarId  string `json:"avatar_id"`
}
type QueryCommentReply struct {
	CommentList []*CommentInfo `json:"comment_list"`
}

// 查询帖子所有评论
func QueryComment(c *gin.Context) {
	reply := httpreply.NewDefaultReplyData()
	defer httpreply.Reply(c, reply)

	var param QueryCommentURI
	if err := c.ShouldBindUri(&param); err != nil {
		reply.Status = http.StatusBadRequest
		reply.Message = fmt.Sprintf("invalid uri path,err:%v", err)
		return
	}

	list, err := dao.PostComment_QueryListByPostId(param.PostId)
	if err != nil {
		logrus.Errorf("查询评论列表失败,post_id:%v", param.PostId)
		reply.Status = http.StatusInternalServerError
		reply.Message = "查询评论列表失败"
		return
	}
	mapUserIdExists := make(map[int32]bool)
	listUserId := make([]int32, 0)
	commentList := make([]*CommentInfo, len(list))
	for i, data := range list {
		user_id := data.UserId
		commentList[i] = &CommentInfo{
			CommentId: data.ID,
			Content:   data.Content,
			Time:      data.CreatedAt.Format(time.DateTime),
			UserId:    data.UserId,
		}
		if !mapUserIdExists[user_id] {
			listUserId = append(listUserId, user_id)
		}
	}

	if len(listUserId) > 0 {
		// 批量查询评论用户的头像和名称
		mapBaseInfo, err := dao.User_Query_List_BaseInfo(listUserId)
		if err != nil {
			logrus.Errorf("查询评论用户基本信息失败,listUserId:%v,err:%v", listUserId, err)
			reply.Status = http.StatusInternalServerError
			reply.Message = "查询评论用户基本信息失败"
			return
		}
		for i, data := range list {
			user_id := data.UserId
			commentList[i].Username = mapBaseInfo[user_id].Username
			commentList[i].AvatarId = mapBaseInfo[user_id].AvatarId
		}
	}

	reply.Data = QueryCommentReply{CommentList: commentList}
}

type DeleteCommentURI struct {
	PostId    uint64 `uri:"post_id" binding:"min=1"`
	CommentId uint64 `uri:"comment_id" binding:"min=1"`
}

// 删除评论
func DeleteComment(c *gin.Context) {
	reply := httpreply.NewDefaultReplyData()
	defer httpreply.Reply(c, reply)

	userId, ok := help.GetUserId(c)
	if !ok {
		reply.Status = http.StatusNotFound
		reply.Message = "无法获取用户信息"
		return
	}

	var param DeleteCommentURI
	if err := c.ShouldBindUri(&param); err != nil {
		reply.Status = http.StatusBadRequest
		reply.Message = fmt.Sprintf("invalid uri path,err:%v", err)
		return
	}

	if err := dao.PostComment_Delete(param.CommentId); err != nil {
		logrus.Errorf("删除评论失败，userId:%d,param:%v,err:%v", userId, param, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "删除评论失败"
		return
	}
}
