// Package service -----------------------------
// @file      : chat.go
// @author    : JJXu
// @contact   : wavingbear@163.com
// @time      : 2025/6/13 19:04
// -------------------------------------------
package logic

import (
	"context"
	"errors"
	"fmt"
	"fonchain-fiee/api/accountFiee"
	"fonchain-fiee/pkg/common/ws"
	"fonchain-fiee/pkg/service"
	"fonchain-fiee/pkg/service/asChat/chatCache"
	"fonchain-fiee/pkg/service/asChat/consts"
	"fonchain-fiee/pkg/service/asChat/dto"
	"go.uber.org/zap"
	"log"
)

func NewMessage(ctx context.Context, cache *chatCache.ChatCache, chatUser *accountFiee.ChatUserData, request dto.NewMessageRequest) (err error) {
	if request.SessionId == "" {
		return errors.New("sessionId不能为空")
	}
	if request.MsgType == 0 {
		return errors.New("msgType不能为空")
	}
	fmt.Println("NewMessage 1111111111111111111111111111111")
	fmt.Println("NewMessage 22222222222222222222222222222222222")
	//存储入库
	if chatUser.NickName != "" {
		chatUser.NickName = fmt.Sprintf("未知用户(%d)", chatUser.ID)
	}
	fmt.Println("NewMessage 3333333333333333333333333333333333")
	var data = accountFiee.ChatRecordData{
		SessionId:  request.SessionId,
		UserId:     chatUser.ID,
		Name:       chatUser.NickName,
		Avatar:     "",
		MsgType:    request.MsgType,
		Content:    request.Message.Text,
		LocalStamp: request.LocalStamp,
		Medias:     nil,
	}
	if len(request.Message.Media) > 0 {
		for _, media := range request.Message.Media {
			data.Medias = append(data.Medias, &accountFiee.ChatMediaData{
				ID: media.MediaId,
			})
		}
	}
	fmt.Println("NewMessage 4444444444444444444444444444444444")
	resp, err := service.AccountFieeProvider.CreateChatRecord(ctx, &data)
	if err != nil {
		return errors.New("消息发送失败")
	}
	fmt.Printf("CreateChatRecord resp:%+v\n", resp)
	//录入缓存
	err = cache.AddChatRecord(request.SessionId, resp.Data)
	if err != nil {
		log.Printf("cache.AddChatRecord 失败:%v", err)
		return errors.New("消息发送失败")
	}
	fmt.Println("NewMessage 5 消息数量+1")
	//新消息数量统计+1
	noticeUserId := consts.ChatRoom.GetUserIdInSession(request.SessionId, chatUser.ID)
	fmt.Println("NewMessage 5.1 消息数量配置结束")
	fmt.Printf("noticeUserId %+v\n", noticeUserId)
	for _, userId := range noticeUserId {
		fmt.Println("userId")
		cache.IncreaseNewMessageTotal(userId, request.SessionId)
	}
	fmt.Println("NewMessage 6")
	//发送websocket消息提醒通知
	var notice = dto.MessageListType{}
	notice.BuildMessage(resp.Data)
	fmt.Printf("ws消息提醒:%+v\n", notice)
	_, err = consts.ChatRoom.SendSessionMessage(chatUser.ID, request.SessionId, ws.NewChatMsgType, notice)
	if err != nil {
		log.Print("发送新消息通知失败", zap.Error(err), zap.Any("notice", notice))
	}
	fmt.Println("NewMessage 7 -end")
	return nil
}
