package chatrecord

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

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

type HistoryAllRequest 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"`
}

type HistoryAllItem struct {
	RoleInfo *role.RoleInfo    `json:"role_info"`
	List     []*ChatRecordInfo `json:"list"`
}

type HistoryAllReply struct {
	RoleList []*HistoryAllItem `json:"role_list"`
}

// 查询用户和全部角色的聊天记录。
func HistoryAll(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 HistoryAllRequest
	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_ByUserId(userId, request.StartTime, request.StopTime)
	if err != nil {
		logrus.Errorf("聊天记录查询失败，request:%v,err:%v", request, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "聊天记录查询失败"
		return
	}

	role_list := make([]*HistoryAllItem, 0)
	mapExistsRole := map[int32]int{} // key是role_id，value是列表中的下标。
	role_ids := make([]int32, 0)
	for _, data := range list {
		role_id := data.CharacterId
		index, ok := mapExistsRole[role_id]
		if !ok { // 不存在，则添加。
			index = len(role_list)
			mapExistsRole[role_id] = index
			role_list = append(role_list, &HistoryAllItem{RoleInfo: nil, List: make([]*ChatRecordInfo, 0)})
			role_ids = append(role_ids, role_id)
		}
		var info ChatRecordInfo
		copy_from_mysql(data, &info)
		role_list[index].List = append(role_list[index].List, &info)
	}
	if len(role_ids) > 0 {
		// 根据角色id列表，查询角色的头像和名称
		role_infos, err := dao.Character_QueryList(role_ids)
		if err != nil {
			logrus.Errorf("查询角色基础信息失败,role_ids:%v,err:%v", role_ids, err)
			reply.Status = http.StatusInternalServerError
			reply.Message = "查询角色基础信息失败"
			return
		}
		for _, role_info := range role_infos {
			role_id := role_info.ID
			var detail role.RoleInfo
			role.Copy_mysql_data(role_info, &detail)
			role_list[mapExistsRole[role_id]].RoleInfo = &detail
		}
	}

	reply.Data = &HistoryAllReply{RoleList: role_list}
}
