import { AgUiEventType, DifyAgent } from '@shangzy/ag-ui-dify'
import { RunAgentInput, EventType, TextMessageContentEvent } from '@ag-ui/client'
import { cacheGet, getUserInfo } from '@/utils/cacheUtil'
import { useState } from 'react'

const Test1: React.FC = () => {
  const [message, setMessage] = useState('')
  const userInfo = getUserInfo()
  const runAgent = () => {
    const difyJson = {
      conversation_id: '',
      files: [],
      query: '1312313',
      appKey: cacheGet('appKey'),
      inputs: {
        Token: cacheGet('token'),
        tenantid: cacheGet('tenantId')
      },
      user: userInfo?.id || 'anonymous'
    }
    const content: string = JSON.stringify(difyJson)
    // 准备输入参数
    const input: RunAgentInput = {
      threadId: new Date().getTime().toString(),
      runId: new Date().getTime().toString(),
      messages: [
        {
          id: new Date().getTime().toString(),
          role: 'user',
          content: content
        }
      ],
      context: [],
      tools: []
    }
    // 订阅Agent事件
    new DifyAgent({
      baseUrl: '/dify',
      showMetadata: true
    })
      .run(input)
      .subscribe({
        next: (event: AgUiEventType) => {
          console.log('🚀 ~ ChatApp ~ aa ~ event:', event)
          try {
            switch (event.type) {
              case EventType.RUN_STARTED:
                // 可以在这里处理运行开始事件
                break

              case EventType.TEXT_MESSAGE_START:
                // 处理消息开始事件
                break

              case EventType.TEXT_MESSAGE_CONTENT:
                const textEvent = event as TextMessageContentEvent
                setMessage(prev => prev + textEvent.delta)
                break

              case EventType.TEXT_MESSAGE_END:
                break

              case EventType.RUN_FINISHED:
                break
            }
          } catch (err) {
            console.error('处理事件时出错:', err)
          }
        },
        error: () => {},
        complete: () => {}
      })
  }
  return (
    <>
      <div onClick={() => runAgent()}>发起请求</div>
      <div>{message}</div>
    </>
  )
}
export default Test1
