// Package robot -----------------------------
// @file      : ruler_ReplyWhenWaiterNoAction.go
// @author    : JJXu
// @contact   : wavingbear@163.com
// @time      : 2025/6/13 18:02
// -------------------------------------------
package robot

import (
	"context"
	"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/dto"
	"fonchain-fiee/pkg/service/asChat/logic"
	"time"
)

// 客服指定时间不回复则自动回复
func NewReplyWhenWaiterNoAction(title string, delaySecond time.Duration) IRobotTask {
	return &RobotTaskReplyWhenWaiterNoAction{
		delaySecond: delaySecond,
		title:       title,
	}
}

type RobotTaskReplyWhenWaiterNoAction struct {
	title       string
	runTime     time.Time
	Response    string
	Receiver    *accountFiee.ChatUserData
	Sender      *accountFiee.ChatUserData
	Msg         string
	Resp        string
	delaySecond time.Duration
}

func (r *RobotTaskReplyWhenWaiterNoAction) Hit(event ws.ListenEventData, sender *accountFiee.ChatUserData) (hit bool) {
	if event.Client == nil || event.EventType != ws.EventChatMessage {
		return
	}
	//客服和机器人的的消息不需要处理
	if event.ChatUser.Role != 1 {
		return
	}
	hit = true // 立即保存SessionId的值
	r.Sender = sender
	r.Receiver = event.ChatUser
	r.runTime = time.Now().Add(r.delaySecond * time.Second)
	return
}

func (r *RobotTaskReplyWhenWaiterNoAction) Run(cache *chatCache.ChatCache) error {
	clientSessionId := fmt.Sprintf("%d", r.Receiver.ID)
	fmt.Println("延时回复 sessionID:", clientSessionId)
	//如果客服已经回复则不发送消息
	chatRecordListRes, err := service.AccountFieeProvider.GetChatRecordList(context.Background(), &accountFiee.GetChatRecordListRequest{
		Query: &accountFiee.ChatRecordData{
			SessionId: clientSessionId,
		},
		Page:     1,
		PageSize: 1,
		Order:    "created_at desc",
	})
	if err != nil || chatRecordListRes.Total == 0 {
		return err
	}
	checkUserId := chatRecordListRes.List[0].UserId
	checkChatUser, err := service.AccountFieeProvider.GetChatUserDetail(context.Background(), &accountFiee.GetChatUserByIdRequest{Id: checkUserId})
	if err != nil || checkChatUser.Role != 1 {
		return err
	}
	err = logic.NewMessage(context.Background(), cache, r.Sender, dto.NewMessageRequest{
		Waiter:    true,
		Robot:     true,
		AtUserId:  r.Receiver.ID,
		SessionId: clientSessionId,
		Message: dto.Message{
			MsgType:    1,
			Text:       r.Resp,
			LocalStamp: time.Now().Unix(),
		},
	})
	return err
}
func (r *RobotTaskReplyWhenWaiterNoAction) RunTime() time.Time {
	return r.runTime
}
func (r *RobotTaskReplyWhenWaiterNoAction) SetResponse(response string) {
	r.Resp = response
}
func (r *RobotTaskReplyWhenWaiterNoAction) GetResponse() string {
	return r.Response
}
func (r *RobotTaskReplyWhenWaiterNoAction) SetTitle(title string) {
	r.title = title
}
func (r *RobotTaskReplyWhenWaiterNoAction) GetTitle() string {
	return r.title
}
