<template>
  <div>
    Demo
    <AIRobot ref="AIRobotRef" @onMessage="onMessage" />
  </div>
</template>

<script setup lang="ts">
import AIRobot from '@component-lib/ai-robot'
import request from 'axios'
import { ref } from 'vue'

/*
 * AI机器人相关
 * */
const AIRobotRef = ref()
// 用户输入的内容
const onMessage = (message) => {
  console.log('onMessage', message)
  // dify的本地接口
  const api_key = 'app-gy94avRz2btKlrDX1m1AXLmm'
  request
    .post(
      'http://localhost/v1/chat-messages',
      {
        inputs: {},
        query: message.body.text,
        response_mode: 'blocking',
        user: 'abc-123',
        conversation_id: ''
      },
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${api_key}`
        }
      }
    )
    .then((res) => {
      const answer = res.data.answer
      let text = answer

      // 模拟业务接口处理
      if (answer.includes('"success')) {
        const data = JSON.parse(answer)
        if (data.success) {
          text = data.data.map((i) => i.name).join('，')
        } else text = data.message
      }

      AIRobotRef.value.handleResponse({ text })
    })
    .catch((err) => {
      console.log(err)
      AIRobotRef.value.handleResponse({ text: '开小差了～暂时无法回答您的问题' })
    })
}
</script>

<style scoped></style>
