package robot

import (
	"context"
	"fonchain-fiee/api/accountFiee"
	"fonchain-fiee/pkg/common/ws"
	"fonchain-fiee/pkg/service"
	"fonchain-fiee/pkg/service/asChat/chatCache"
	"fonchain-fiee/pkg/service/asChat/dto"
	"fonchain-fiee/pkg/service/asChat/logic"
	"strconv"
	"time"
)

func NewReplyWhenUserJoinSession(title string) IRobotTask {
	return &ReplyWhenUserJoinSession{title: title}
}

type ReplyWhenUserJoinSession struct {
	Response  string
	Sender    *accountFiee.ChatUserData
	Msg       string
	Resp      string
	sessionId string
	atUserId  int
	title     string
}

func (r *ReplyWhenUserJoinSession) Hit(event ws.ListenEventData, sender *accountFiee.ChatUserData) (hit bool) {
	if event.EventType != ws.EventUserJoin {
		return
	}
	if event.Client == nil {
		return
	}
	ctx := context.Background()
	queryRes, err := service.AccountFieeProvider.GetChatRecordList(ctx, &accountFiee.GetChatRecordListRequest{
		Query: &accountFiee.ChatRecordData{
			SessionId: event.Client.SessionId,
		},
		Page:     1,
		PageSize: 1,
		Order:    "created_at desc",
	})
	if err != nil {
		return
	}
	//如果最近一次的消息也是机器人发送的,就不再发送了
	for i, v := range queryRes.List {
		if i == 0 {
			if v.UserId == sender.ID {
				return
			} else {
				break
			}
		}
	}
	hit = true
	r.Sender = sender
	r.sessionId = event.Client.SessionId
	r.atUserId, _ = strconv.Atoi(event.Client.SessionId)
	return
}

func (r *ReplyWhenUserJoinSession) Run(cache *chatCache.ChatCache) (err error) {
	err = logic.NewMessage(context.Background(), cache, r.Sender, dto.NewMessageRequest{
		Waiter:    true,
		Robot:     true,
		AtUserId:  int64(r.atUserId),
		SessionId: r.sessionId,
		Message: dto.Message{
			MsgType:    1,
			Text:       r.Resp,
			LocalStamp: time.Now().Unix(),
		},
	})
	return
}

func (r *ReplyWhenUserJoinSession) RunTime() time.Time {
	return time.Time{}
}

func (r *ReplyWhenUserJoinSession) SetResponse(response string) {
	r.Resp = response
}
func (r *ReplyWhenUserJoinSession) GetResponse() string {
	return r.Response
}
func (r *ReplyWhenUserJoinSession) SetTitle(title string) {
	r.title = title
}
func (r *ReplyWhenUserJoinSession) GetTitle() string {
	return r.title
}