package robot

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

type RobotTaskWithKeyworkds struct {
	title    string
	runTime  time.Time
	Response string
	Receiver *accountFiee.ChatUserData
	Sender   *accountFiee.ChatUserData
	Msg      string
	Resp     string
	keywords []string
}

func NewReplyWhenHitKeywords(title string, keywords []string) IRobotTask {
	return &RobotTaskWithKeyworkds{title: title, keywords: keywords}
}
func (r *RobotTaskWithKeyworkds) Hit(event ws.ListenEventData, sender *accountFiee.ChatUserData) (hit bool) {
	//fmt.Printf("event.EventType != ws.EventChatMessage:%v\n", event.EventType != ws.EventChatMessage)
	//fmt.Printf("event.Msg: %v\n", event.Msg == "")
	//fmt.Printf("event.Client == nil: %v\n", event.Client == nil)
	//fmt.Printf("event.ChatUser == nil: %v\n", event.ChatUser == nil)
	//fmt.Printf("event.ChatUser.Role != 1: %v\n", event.ChatUser.Role != 1)
	//fmt.Printf("r.keywords: %+v\n", r.keywords)
	if event.EventType != ws.EventChatMessage || event.Msg == "" || event.Client == nil || event.ChatUser == nil {
		return
	}
	if event.ChatUser.Role != 1 {
		return
	}
	r.Sender = sender
	r.Receiver = event.ChatUser
	for _, v := range r.keywords {
		if strings.Contains(event.Msg, v) {
			fmt.Printf("关键词比对:%s ----- %s : true", event.Msg, v)
			hit = true
			break
		}
		fmt.Printf("关键词比对:%s ----- %s: false", event.Msg, v)
	}
	return
}

func (r *RobotTaskWithKeyworkds) Run(cache *chatCache.ChatCache) (err error) {
	err = logic.NewMessage(context.Background(), cache, r.Sender, dto.NewMessageRequest{
		Waiter:    true,
		Robot:     true,
		AtUserId:  r.Receiver.ID,
		SessionId: fmt.Sprintf("%d", r.Receiver.ID),
		Message: dto.Message{
			MsgType:    1,
			Text:       r.Resp,
			LocalStamp: time.Now().Unix(),
		},
	})
	return
}

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

func (r *RobotTaskWithKeyworkds) SetResponse(response string) {
	r.Resp = response
}

func (r *RobotTaskWithKeyworkds) GetResponse() string {
	return r.Response
}
func (r *RobotTaskWithKeyworkds) SetTitle(title string) {
	r.title = title
}
func (r *RobotTaskWithKeyworkds) GetTitle() string {
	return r.title
}
