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 ListParam struct {
	StartTime time.Time `form:"start_time" binding:"required" time_format:"2006-01-02 15:04:05"`
	StopTime  time.Time `form:"stop_time" binding:"required,gtfield=StartTime" time_format:"2006-01-02 15:04:05"`
	RoleId    *int32    `form:"role_id" binding:"min=0"`
}

type ListReply struct {
	PostList []*PostInfo `json:"post_list"`
}

func List(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 ListParam
	if err := c.ShouldBindQuery(&param); err != nil {
		reply.Status = http.StatusBadRequest
		reply.Message = fmt.Sprintf("invalid query args,err:%v", err)
		return
	}

	list, err := dao.Post_Page_Query(param.StartTime, param.StopTime, *param.RoleId)
	if err != nil {
		logrus.Errorf("帖子列表查询失败，param:%v,error:%v", param, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "帖子列表查询失败"
		return
	}

	// 批量查询帖子点赞信息
	postIds := make([]uint64, len(list))
	for i, data := range list {
		postIds[i] = uint64(data.ID)
	}
	userIds := make([]int32, len(list))
	for i, data := range list {
		userIds[i] = data.UserId
	}
	like_count_map, err := dao.PostLike_Count_Batch(postIds)
	if err != nil {
		logrus.Errorf("帖子列表点赞数查询失败，userId:%d,postIds:%v,err:%v", userId, postIds, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "帖子列表点赞数查询失败"
		return
	}

	// 批量查询用户是否点赞
	user_like_map, err := dao.PostLike_Exists_Batch(userId, postIds)
	if err != nil {
		logrus.Errorf("帖子列表用户点赞信息查询失败，userId:%d,postId:%v,err:%v", userId, postIds, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "帖子列表用户点赞信息查询失败"
		return
	}

	// 批量查询用户名和用户头像
	user_info_map, err := dao.User_Query_List(userIds)
	if err != nil {
		logrus.Errorf("批量查询帖子发布者信息失败，postIds:%v,userIds:%v,err:%v", postIds, userId, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "批量查询帖子发布者信息失败"
		return
	}

	postList := make([]*PostInfo, len(list))
	for i, data := range list {
		var info PostInfo
		current_post_id := uint64(data.ID)
		current_user_id := data.UserId
		copy_from_mysql(data, like_count_map[current_post_id], user_like_map[current_post_id], user_info_map[current_user_id], &info)
		postList[i] = &info
	}

	reply.Data = &ListReply{PostList: postList}
}
