package chatrecord

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 ChatRecordInfo struct {
	ChatRecordId uint64 `json:"chat_record_id"`
	UserId       int32  `json:"user_id"`
	RoleId       int32  `json:"role_id"`
	Direction    int8   `json:"direction"`
	Message      string `json:"message"`
	CreatedAt    string `json:"create_at"` // 使用string保存，在设置时，不带时区
}

type HistoryRequest struct {
	RoleId    int32     `form:"role_id" binding:"required,gt=0"`
	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"`
}

type HistoryReply struct {
	List []*ChatRecordInfo `json:"list"`
}

// 聊天记录历史查询，支持分页查询
func History(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 request HistoryRequest
	if err := c.ShouldBind(&request); err != nil {
		reply.Status = http.StatusBadRequest
		reply.Message = fmt.Sprintf("invalid query args, err:%v", err)
		return
	}

	list, err := dao.ChatRecord_Query(userId, request.RoleId, request.StartTime, request.StopTime)
	if err != nil {
		logrus.Errorf("聊天记录查询失败，request:%v,err:%v", request, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "聊天记录查询失败"
		return
	}

	chatRecordList := make([]*ChatRecordInfo, len(list))
	for i, data := range list {
		var info ChatRecordInfo
		copy_from_mysql(data, &info)
		chatRecordList[i] = &info
	}
	reply.Data = &HistoryReply{List: chatRecordList}
}

func copy_from_mysql(data *dao.ChatRecord, info *ChatRecordInfo) {
	info.ChatRecordId = data.ID
	info.UserId = data.UserId
	info.RoleId = data.CharacterId
	info.Direction = data.Direction
	info.Message = data.Message
	info.CreatedAt = data.CreatedAt.Format(time.DateTime)
}
