# AI Chat 组件使用指南

## 安装

```bash
npm install hxy-stencil-ai-chat
```

## 框架支持

- ✅ **React** - 官方适配层
- ✅ **Angular** - 官方适配层  
- ✅ **Vue** - 官方适配层
- ✅ **HTML 原生** - 直接使用 Web Components

---

## 1. React 使用案例

### 安装依赖
```bash
npm install hxy-stencil-ai-chat react react-dom
```

### 基本使用
```jsx
import React, { useState } from 'react';
import { AiChat } from 'hxy-stencil-ai-chat/react';

function App() {
  const [messages, setMessages] = useState([
    {
      id: '1',
      type: 'text',
      content: '你好！欢迎使用 AI 聊天组件！',
      timestamp: Date.now(),
      isUser: false
    },
    {
      id: '2',
      type: 'markdown',
      content: '# 支持 Markdown\n\n- **粗体文本**\n- *斜体文本*\n- `代码片段`\n- [链接](https://example.com)',
      timestamp: Date.now(),
      isUser: false
    },
    {
      id: '3',
      type: 'echarts',
      content: {
        title: { text: '数据图表' },
        xAxis: { data: ['周一', '周二', '周三', '周四', '周五'] },
        yAxis: {},
        series: [{ 
          data: [120, 200, 150, 80, 70], 
          type: 'bar',
          itemStyle: { color: '#007bff' }
        }]
      },
      timestamp: Date.now(),
      isUser: false
    }
  ]);

  const handleMessageSend = (event) => {
    const { content, timestamp } = event.detail;
    const newMessage = {
      id: Date.now().toString(),
      type: 'text',
      content,
      timestamp,
      isUser: true
    };
    setMessages(prev => [...prev, newMessage]);
    
    // 模拟 AI 回复
    setTimeout(() => {
      const aiReply = {
        id: (Date.now() + 1).toString(),
        type: 'text',
        content: `收到您的消息：${content}`,
        timestamp: Date.now(),
        isUser: false
      };
      setMessages(prev => [...prev, aiReply]);
    }, 1000);
  };

  return (
    <div style={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
      <h1>React AI Chat 示例</h1>
      <AiChat 
        messages={messages}
        showInput={true}
        inputPlaceholder="输入消息..."
        multilineInput={true}
        showAiAvatar={true}
        showUserAvatar={true}
        showTimestamp={true}
        onMessageSend={handleMessageSend}
        onMessageClick={(message) => console.log('Message clicked:', message)}
        onMessageLongPress={(message) => console.log('Message long pressed:', message)}
      />
    </div>
  );
}

export default App;
```

### 高级配置
```jsx
import React, { useState, useRef } from 'react';
import { AiChat } from 'hxy-stencil-ai-chat/react';

function AdvancedChat() {
  const [messages, setMessages] = useState([]);
  const aiChatRef = useRef();

  const handleCustomRenderer = () => {
    // 自定义渲染器示例
    const customMessage = {
      id: 'custom-1',
      type: 'custom',
      content: '这是自定义渲染的内容',
      customRenderer: 'my-custom-renderer',
      timestamp: Date.now(),
      isUser: false
    };
    setMessages(prev => [...prev, customMessage]);
  };

  return (
    <div>
      <button onClick={handleCustomRenderer}>添加自定义消息</button>
      <AiChat 
        ref={aiChatRef}
        messages={messages}
        showInput={true}
        inputPlaceholder="输入消息..."
        multilineInput={true}
        maxInputLength={500}
        inputDisabled={false}
        showAiAvatar={true}
        showUserAvatar={true}
        showTimestamp={true}
        aiAvatar="https://via.placeholder.com/40/007bff/ffffff?text=AI"
        userAvatar="https://via.placeholder.com/40/28a745/ffffff?text=U"
        customRenderers={{
          'my-custom-renderer': MyCustomComponent
        }}
        onMessageSend={(e) => console.log('Message sent:', e.detail)}
      />
    </div>
  );
}
```

---

## 2. Angular 使用案例

### 安装依赖
```bash
npm install hxy-stencil-ai-chat @angular/core @angular/common
```

### 模块配置
```typescript
// app.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { defineCustomElements } from 'hxy-stencil-ai-chat/loader';
import { AppComponent } from './app.component';

// 定义自定义元素
defineCustomElements();

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA] // 允许自定义元素
})
export class AppModule { }
```

### 组件使用
```typescript
// app.component.ts
import { Component } from '@angular/core';

interface ChatMessage {
  id: string;
  type: 'text' | 'markdown' | 'echarts' | string;
  content: string | any;
  timestamp: number;
  isUser: boolean;
  customRenderer?: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  messages: ChatMessage[] = [
    {
      id: '1',
      type: 'text',
      content: '你好！这是 Angular 中的 AI 聊天组件！',
      timestamp: Date.now(),
      isUser: false
    },
    {
      id: '2',
      type: 'markdown',
      content: '# Angular 支持\n\n- **TypeScript** 支持\n- *响应式* 设计\n- `组件化` 开发',
      timestamp: Date.now(),
      isUser: false
    },
    {
      id: '3',
      type: 'echarts',
      content: {
        title: { text: 'Angular 图表' },
        xAxis: { data: ['Q1', 'Q2', 'Q3', 'Q4'] },
        yAxis: {},
        series: [{ 
          data: [100, 150, 200, 180], 
          type: 'line',
          smooth: true
        }]
      },
      timestamp: Date.now(),
      isUser: false
    }
  ];

  onMessageSend(event: CustomEvent) {
    const { content, timestamp } = event.detail;
    const newMessage: ChatMessage = {
      id: Date.now().toString(),
      type: 'text',
      content,
      timestamp,
      isUser: true
    };
    this.messages = [...this.messages, newMessage];
    
    // 模拟 AI 回复
    setTimeout(() => {
      const aiReply: ChatMessage = {
        id: (Date.now() + 1).toString(),
        type: 'text',
        content: `Angular 收到：${content}`,
        timestamp: Date.now(),
        isUser: false
      };
      this.messages = [...this.messages, aiReply];
    }, 1000);
  }

  onMessageClick(message: ChatMessage) {
    console.log('Message clicked:', message);
  }

  onMessageLongPress(message: ChatMessage) {
    console.log('Message long pressed:', message);
  }
}
```

```html
<!-- app.component.html -->
<div class="app-container">
  <h1>Angular AI Chat 示例</h1>
  <ai-chat
    [messages]="messages"
    [showInput]="true"
    [inputPlaceholder]="'输入消息...'"
    [multilineInput]="true"
    [showAiAvatar]="true"
    [showUserAvatar]="true"
    [showTimestamp]="true"
    [aiAvatar]="'https://via.placeholder.com/40/007bff/ffffff?text=AI'"
    [userAvatar]="'https://via.placeholder.com/40/28a745/ffffff?text=U'"
    (messageSend)="onMessageSend($event)"
    (messageClick)="onMessageClick($event.detail)"
    (messageLongPress)="onMessageLongPress($event.detail)">
  </ai-chat>
</div>
```

```css
/* app.component.css */
.app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

h1 {
  text-align: center;
  margin: 20px 0;
  color: #333;
}
```

---

## 3. Vue 使用案例

### Vue 2 和 Vue 3 兼容性

✅ **Vue 2.7+** - 完全支持  
✅ **Vue 3.x** - 完全支持  
✅ **官方适配层** - Vue 3 专用  
✅ **Web Components** - Vue 2/3 通用方案

### 安装依赖

**Vue 2:**
```bash
npm install hxy-stencil-ai-chat@1.0.13 vue@2.7.14
```

**Vue 3:**
```bash
npm install hxy-stencil-ai-chat@1.0.13 vue@3.4.0
```

### Vue 2 使用（推荐方案）

**方案 1：直接使用 Web Components（推荐）**
```vue
<template>
  <div class="app-container">
    <h1>Vue 2 AI Chat 示例</h1>
    <ai-chat
      :messages="messages"
      :show-input="true"
      input-placeholder="在 Vue 2 中输入消息..."
      :multiline-input="true"
      :show-ai-avatar="true"
      :show-user-avatar="true"
      :show-timestamp="true"
      ai-avatar="https://via.placeholder.com/40/4fc08d/ffffff?text=AI"
      user-avatar="https://via.placeholder.com/40/28a745/ffffff?text=U"
      @message-send="handleMessageSend"
      @message-click="handleMessageClick"
      @message-long-press="handleMessageLongPress"
    />
  </div>
</template>

<script>
import { defineCustomElements } from 'hxy-stencil-ai-chat/loader';

// 注册 Web Components
defineCustomElements();

export default {
  name: 'App',
  data() {
    return {
      messages: [
        {
          id: '1',
          type: 'text',
          content: '你好！这是 Vue 2 中的 AI 聊天组件！',
          timestamp: Date.now(),
          isUser: false
        },
        {
          id: '2',
          type: 'markdown',
          content: '# Vue 2 支持\n\n- **Options API** 选项式 API\n- *响应式* 数据\n- `组件化` 开发',
          timestamp: Date.now(),
          isUser: false
        },
        {
          id: '3',
          type: 'echarts',
          content: {
            title: { text: 'Vue 2 图表' },
            xAxis: { data: ['Q1', 'Q2', 'Q3', 'Q4'] },
            yAxis: {},
            series: [{ 
              data: [100, 150, 200, 180], 
              type: 'line',
              smooth: true
            }]
          },
          timestamp: Date.now(),
          isUser: false
        }
      ]
    }
  },
  methods: {
    handleMessageSend(event) {
      const { content, timestamp } = event.detail;
      const newMessage = {
        id: Date.now().toString(),
        type: 'text',
        content,
        timestamp,
        isUser: true
      };
      this.messages.push(newMessage);
      
      // 模拟 AI 回复
      setTimeout(() => {
        const aiReply = {
          id: (Date.now() + 1).toString(),
          type: 'text',
          content: `Vue 2 收到：${content}`,
          timestamp: Date.now(),
          isUser: false
        };
        this.messages.push(aiReply);
      }, 1000);
    },
    handleMessageClick(message) {
      console.log('Message clicked:', message);
    },
    handleMessageLongPress(message) {
      console.log('Message long pressed:', message);
    }
  }
}
</script>

<style scoped>
.app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

h1 {
  text-align: center;
  margin: 20px 0;
  color: #333;
}
</style>
```

### Vue 3 使用

**方案 1：直接使用 Web Components（推荐）**
```vue
<template>
  <div class="app-container">
    <h1>Vue 3 AI Chat 示例</h1>
    <ai-chat
      :messages="messages"
      :show-input="true"
      input-placeholder="在 Vue 3 中输入消息..."
      :multiline-input="true"
      :show-ai-avatar="true"
      :show-user-avatar="true"
      :show-timestamp="true"
      ai-avatar="https://via.placeholder.com/40/4fc08d/ffffff?text=AI"
      user-avatar="https://via.placeholder.com/40/28a745/ffffff?text=U"
      @message-send="handleMessageSend"
      @message-click="handleMessageClick"
      @message-long-press="handleMessageLongPress"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { defineCustomElements } from 'hxy-stencil-ai-chat/loader';

// 注册 Web Components
defineCustomElements();

const messages = ref([
  {
    id: '1',
    type: 'text',
    content: '你好！这是 Vue 3 中的 AI 聊天组件！',
    timestamp: Date.now(),
    isUser: false
  },
  {
    id: '2',
    type: 'markdown',
    content: '# Vue 3 支持\n\n- **Composition API** 组合式 API\n- *响应式* 数据\n- `Teleport` 传送门',
    timestamp: Date.now(),
    isUser: false
  },
  {
    id: '3',
    type: 'echarts',
    content: {
      title: { text: 'Vue 3 图表' },
      xAxis: { data: ['Jan', 'Feb', 'Mar', 'Apr', 'May'] },
      yAxis: {},
      series: [{ 
        data: [50, 80, 120, 100, 90], 
        type: 'pie',
        radius: '50%'
      }]
    },
    timestamp: Date.now(),
    isUser: false
  }
]);

const handleMessageSend = (event) => {
  const { content, timestamp } = event.detail;
  const newMessage = {
    id: Date.now().toString(),
    type: 'text',
    content,
    timestamp,
    isUser: true
  };
  messages.value.push(newMessage);
  
  // 模拟 AI 回复
  setTimeout(() => {
    const aiReply = {
      id: (Date.now() + 1).toString(),
      type: 'text',
      content: `Vue 3 收到：${content}`,
      timestamp: Date.now(),
      isUser: false
    };
    messages.value.push(aiReply);
  }, 1000);
};

const handleMessageClick = (message) => {
  console.log('Message clicked:', message);
};

const handleMessageLongPress = (message) => {
  console.log('Message long pressed:', message);
};
</script>

<style scoped>
.app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

h1 {
  text-align: center;
  margin: 20px 0;
  color: #333;
}
</style>
```

**方案 2：使用官方适配层（仅 Vue 3）**
```vue
<template>
  <div class="app-container">
    <h1>Vue 3 官方适配层示例</h1>
    <ai-chat
      :messages="messages"
      :show-input="true"
      input-placeholder="使用官方适配层..."
      @message-send="handleMessageSend"
    />
  </div>
</template>

<script>
import { defineCustomElements } from 'hxy-stencil-ai-chat/loader';
// 注意：Vue 3 官方适配层需要手动注册
defineCustomElements();

export default {
  name: 'App',
  data() {
    return {
      messages: [
        {
          id: '1',
          type: 'text',
          content: 'Vue 3 官方适配层示例',
          timestamp: Date.now(),
          isUser: false
        }
      ]
    }
  },
  methods: {
    handleMessageSend(event) {
      console.log('Message sent:', event.detail);
    }
  }
}
</script>
```

### Vue 3 Composition API
```vue
<template>
  <div class="app-container">
    <h1>Vue 3 AI Chat 示例</h1>
    <ai-chat
      :messages="messages"
      :show-input="true"
      input-placeholder="输入消息..."
      :multiline-input="true"
      @message-send="handleMessageSend"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { defineCustomElements } from 'hxy-stencil-ai-chat/loader';

// 定义自定义元素
defineCustomElements();

const messages = ref([
  {
    id: '1',
    type: 'text',
    content: 'Vue 3 Composition API 支持！',
    timestamp: Date.now(),
    isUser: false
  }
]);

const handleMessageSend = (event) => {
  const { content, timestamp } = event.detail;
  messages.value.push({
    id: Date.now().toString(),
    type: 'text',
    content,
    timestamp,
    isUser: true
  });
};
</script>
```

---

## 4. HTML 原生使用案例

### 基本使用
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chat 原生 HTML 示例</title>
    <script type="module" src="https://unpkg.com/hxy-stencil-ai-chat@latest/dist/stenci-ai-chat/stenci-ai-chat.esm.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        .container {
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: #333;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>原生 HTML AI Chat 示例</h1>
        <ai-chat id="chatComponent"></ai-chat>
    </div>

    <script>
        // 获取组件实例
        const chatComponent = document.getElementById('chatComponent');
        
        // 设置初始消息
        chatComponent.messages = [
            {
                id: '1',
                type: 'text',
                content: '你好！这是原生 HTML 中的 AI 聊天组件！',
                timestamp: Date.now(),
                isUser: false
            },
            {
                id: '2',
                type: 'markdown',
                content: '# 原生 HTML 支持\n\n- **直接使用** Web Components\n- *无需框架* 依赖\n- `轻量级` 实现',
                timestamp: Date.now(),
                isUser: false
            },
            {
                id: '3',
                type: 'echarts',
                content: {
                    title: { text: '原生图表' },
                    xAxis: { data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] },
                    yAxis: {},
                    series: [{ 
                        data: [20, 40, 30, 50, 35], 
                        type: 'scatter',
                        symbolSize: 20
                    }]
                },
                timestamp: Date.now(),
                isUser: false
            }
        ];

        // 配置组件属性
        chatComponent.showInput = true;
        chatComponent.inputPlaceholder = '输入消息...';
        chatComponent.multilineInput = true;
        chatComponent.showAiAvatar = true;
        chatComponent.showUserAvatar = true;
        chatComponent.showTimestamp = true;
        chatComponent.aiAvatar = 'https://via.placeholder.com/40/007bff/ffffff?text=AI';
        chatComponent.userAvatar = 'https://via.placeholder.com/40/28a745/ffffff?text=U';

        // 监听事件
        chatComponent.addEventListener('messageSend', (event) => {
            const { content, timestamp } = event.detail;
            const newMessage = {
                id: Date.now().toString(),
                type: 'text',
                content,
                timestamp,
                isUser: true
            };
            chatComponent.messages = [...chatComponent.messages, newMessage];
            
            // 模拟 AI 回复
            setTimeout(() => {
                const aiReply = {
                    id: (Date.now() + 1).toString(),
                    type: 'text',
                    content: `原生 HTML 收到：${content}`,
                    timestamp: Date.now(),
                    isUser: false
                };
                chatComponent.messages = [...chatComponent.messages, aiReply];
            }, 1000);
        });

        chatComponent.addEventListener('messageClick', (event) => {
            console.log('Message clicked:', event.detail);
        });

        chatComponent.addEventListener('messageLongPress', (event) => {
            console.log('Message long pressed:', event.detail);
        });
    </script>
</body>
</html>
```

### CDN 使用
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chat CDN 示例</title>
    <!-- 使用 CDN -->
    <script type="module" src="https://unpkg.com/hxy-stencil-ai-chat@latest/dist/stenci-ai-chat/stenci-ai-chat.esm.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/hxy-stencil-ai-chat@latest/dist/stenci-ai-chat/stenci-ai-chat.css">
</head>
<body>
    <ai-chat 
        id="chatComponent"
        show-input="true"
        input-placeholder="输入消息..."
        multiline-input="true"
        show-ai-avatar="true"
        show-user-avatar="true"
        show-timestamp="true">
    </ai-chat>

    <script>
        // 组件会自动初始化
        const chatComponent = document.getElementById('chatComponent');
        
        // 设置消息
        chatComponent.messages = [
            {
                id: '1',
                type: 'text',
                content: 'CDN 方式使用 AI Chat 组件！',
                timestamp: Date.now(),
                isUser: false
            }
        ];
    </script>
</body>
</html>
```

---

## 5. 组件属性说明

### 主要属性
- `messages`: 消息数组
- `showInput`: 是否显示输入框
- `inputPlaceholder`: 输入框占位符
- `multilineInput`: 是否多行输入
- `maxInputLength`: 最大输入长度
- `inputDisabled`: 是否禁用输入
- `showAiAvatar`: 是否显示 AI 头像
- `showUserAvatar`: 是否显示用户头像
- `showTimestamp`: 是否显示时间戳
- `aiAvatar`: AI 头像 URL
- `userAvatar`: 用户头像 URL
- `customRenderers`: 自定义渲染器

### 事件
- `messageSend`: 消息发送事件
- `messageClick`: 消息点击事件
- `messageLongPress`: 消息长按事件

### 消息类型
- `text`: 纯文本
- `markdown`: Markdown 格式
- `echarts`: ECharts 图表
- `custom`: 自定义类型

---

## 6. 样式自定义

### CSS 变量
```css
ai-chat {
  --ai-chat-bg-color: #f5f5f5;
  --ai-chat-text-color: #333;
  --ai-chat-primary-color: #007bff;
  --ai-chat-border-color: #e0e0e0;
  --ai-chat-message-bg: #ffffff;
  --ai-chat-user-message-bg: #007bff;
  --ai-chat-user-message-color: #ffffff;
}
```

### 响应式设计
```css
@media (max-width: 768px) {
  ai-chat {
    --ai-chat-font-size: 14px;
    --ai-chat-padding: 8px;
  }
}
```

---

## 7. 最佳实践

1. **性能优化**: 大量消息时考虑虚拟滚动
2. **样式定制**: 使用 CSS 变量进行主题定制
3. **事件处理**: 合理使用事件监听器
4. **类型安全**: TypeScript 项目中使用类型定义
5. **响应式**: 确保在不同设备上的良好体验

---

## 8. 故障排除

### 常见问题
1. **组件不显示**: 检查是否正确导入和初始化
2. **样式问题**: 检查 CSS 变量和 Shadow DOM
3. **事件不触发**: 检查事件监听器绑定
4. **类型错误**: 检查 TypeScript 类型定义

### 调试技巧
```javascript
// 检查组件状态
console.log(chatComponent.messages);
console.log(chatComponent.showInput);

// 监听所有事件
chatComponent.addEventListener('*', (event) => {
  console.log('Event:', event.type, event.detail);
});
```
