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"
	"gorm.io/datatypes"
)

type PostInfo struct {
	PostId       uint64         `json:"post_id"`
	UserId       int32          `json:"user_id"`        // 发帖者
	UserAvatarId string         `json:"user_avatar_id"` // 用户头像
	Username     string         `json:"username"`       // 用户名称
	CreatedAt    string         `json:"created_at"`     // 发帖时间
	Title        string         `json:"title"`
	Content      string         `json:"content"`
	LikeCount    int            `json:"like_count"` // 点赞数
	IsLike       bool           `json:"is_like"`    // 当前用户是否点赞了
	RoleIds      datatypes.JSON `json:"role_ids"`   // 帖子关联的角色id列表
}

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

type QueryReply struct {
	PostInfo *PostInfo `json:"post_info"`
}

// 帖子查询接口

func Query(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
	}

	data, err := dao.Post_Query(param.PostId)
	if err != nil {
		logrus.Errorf("帖子数据库查询失败，post_id:%d,err:%v", param.PostId, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "帖子查询异常"
		return
	}

	// 从数据库中查询贴子的点赞情况。
	count, err := dao.PostLike_Count(param.PostId)
	if err != nil {
		logrus.Errorf("贴子点赞数查询失败，post_id:%d,err:%v", param.PostId, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "贴子点赞数查询异常"
		return
	}
	/// 查询当前用户，是否点赞了。
	is_like, err := dao.PostLike_Exists(userId, param.PostId)
	if err != nil {
		logrus.Errorf("贴子用户是否点赞查询失败，user_id:%d,post_id:%d,err:%v", userId, param.PostId, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "贴子用户是否点赞查询失败"
		return
	}

	// 查询用户名和头像id
	user_info, err := dao.User_Query(data.UserId)
	if err != nil {
		logrus.Errorf("查询帖子发布者信息失败，user_id:%d,post_id:%d,err:%v", userId, param.PostId, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "查询帖子发布者信息失败"
		return
	}

	var info PostInfo
	copy_from_mysql(data, count, is_like, user_info, &info)
	reply.Data = &QueryReply{PostInfo: &info}
}

func copy_from_mysql(data *dao.Post, like_count int64, is_like bool, user_info *dao.User, detail *PostInfo) {
	detail.PostId = uint64(data.ID)
	detail.UserId = data.UserId
	detail.Title = data.Title
	detail.Content = data.Content
	detail.RoleIds = data.RoleIds
	detail.LikeCount = int(like_count)
	detail.IsLike = is_like
	detail.CreatedAt = data.CreatedAt.Format(time.DateTime)
	if user_info != nil {
		detail.UserAvatarId = user_info.AvatarId
		detail.Username = user_info.Username
	}
}
