完成AI问答模块

This commit is contained in:
2025-07-08 21:42:38 +08:00
parent 38f67616fc
commit 9f8f113e43
35 changed files with 1563 additions and 146 deletions

2
.gitignore vendored
View File

@@ -1,3 +1,5 @@
/pnpm-lock.yaml
/.swc/
/.idea/
node_modules
node_modules

View File

@@ -0,0 +1,111 @@
# PC端显示手机版样式指南
## 功能说明
本项目已实现PC端浏览器中显示手机版样式的功能让用户在大屏幕设备上也能体验到移动端的界面效果。
## 实现原理
通过CSS媒体查询和容器限制在PC端屏幕宽度≥768px
1. 限制页面最大宽度为414pxiPhone 6/7/8 Plus尺寸
2. 页面居中显示
3. 添加阴影和圆角效果,模拟手机屏幕
4. 设置渐变背景,增强视觉效果
## 使用方法
### 1. 页面组件包装
在需要支持PC端手机版显示的页面组件中使用 `mobile-container` 类包装:
```tsx
function MyPage() {
return (
<div className="mobile-container">
{/* 页面内容 */}
</div>
);
}
```
### 2. 样式文件引入
确保在全局样式文件中引入了手机版容器样式:
```scss
// src/app.scss
@import './styles/mobile-container.scss';
```
## 响应式断点
- **移动端** (≤767px): 保持原有全屏显示
- **平板端** (768px-1023px): 414px宽度居中显示
- **桌面端** (1024px-1439px): 375px宽度居中显示
- **大屏端** (≥1440px): 414px宽度居中显示
## 视觉效果
### PC端效果
- 页面宽度: 414px
- 居中显示
- 圆角边框: 12px
- 阴影效果: 0 0 30px rgba(0, 0, 0, 0.15)
- 渐变背景: 蓝紫色渐变
### 移动端效果
- 保持原有全屏显示
- 无额外样式影响
## 已适配页面
以下页面已添加手机版容器支持:
1. **首页** (`src/pages/index/index.tsx`)
2. **文章列表** (`src/custom/article/article.tsx`)
3. **文章详情** (`src/pages/article/detail.tsx`)
4. **用户中心** (`src/pages/user/user.tsx`)
## 添加新页面支持
为新页面添加PC端手机版显示支持
```tsx
// 1. 导入样式(如果使用独立样式文件)
import './page.scss';
// 2. 使用容器包装
function NewPage() {
return (
<div className="mobile-container">
{/* 页面内容 */}
</div>
);
}
```
## 注意事项
1. **固定定位元素**: 使用 `fixed` 定位的元素需要特别处理确保在PC端不超出容器范围
2. **底部导航**: TabBar组件已自动适配PC端样式
3. **图片资源**: 确保图片能够正确缩放适应容器宽度
4. **交互体验**: PC端保持移动端的交互方式点击、滑动等
## 自定义配置
可以通过修改 `src/styles/mobile-container.scss` 来调整:
- 容器宽度
- 阴影效果
- 圆角大小
- 背景颜色
- 响应式断点
## 浏览器兼容性
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
支持所有现代浏览器的CSS Grid和Flexbox特性。

View File

@@ -0,0 +1,91 @@
# Taro RichText 富文本组件使用指南
## 基本用法
```tsx
import { RichText } from '@tarojs/components';
// 显示HTML字符串
<RichText
nodes={htmlString}
space="nbsp"
/>
```
## 主要属性
### nodes
- **类型**: `string | Array<Node>`
- **说明**: 富文本内容支持HTML字符串或节点数组
### space
- **类型**: `'ensp' | 'emsp' | 'nbsp'`
- **说明**: 显示连续空格的方式
- `ensp`: 中文字符空格一半大小
- `emsp`: 中文字符空格大小
- `nbsp`: 根据字体设置的空格大小
### selectable
- **类型**: `boolean`
- **默认值**: `false`
- **说明**: 富文本是否可以长按选中
## HTML内容处理
### 支持的HTML标签
- 文本标签: `p`, `span`, `div`, `h1-h6`, `strong`, `b`, `em`, `i`
- 列表标签: `ul`, `ol`, `li`
- 其他标签: `img`, `a`, `br`, `hr`
### 样式处理
富文本内容的样式通过CSS全局样式定义
```scss
.content {
:global {
p { margin: 16px 0; }
img { max-width: 100%; }
// 更多样式...
}
}
```
## 实际应用示例
### 文章详情页面
```tsx
<View className={'content text-gray-700 text-sm'}>
<RichText
nodes={item?.content || ''}
space="nbsp"
/>
</View>
```
### 协议页面
```tsx
<View className={'content text-gray-700 text-sm p-4'}>
<RichText nodes={content}/>
</View>
```
## 注意事项
1. **安全性**: RichText会直接渲染HTML注意防范XSS攻击
2. **性能**: 大量富文本内容可能影响性能
3. **兼容性**: 不同平台对HTML标签支持程度不同
4. **样式**: 使用`:global`确保样式能正确应用到富文本内容
## 常见问题
### 图片不显示
- 检查图片URL是否正确
- 确保图片域名在小程序白名单中
### 样式不生效
- 使用`:global`包裹富文本样式
- 检查CSS选择器优先级
### 内容被截断
- 检查容器高度设置
- 使用`max-width: 100%`防止内容溢出

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

50
src/api/ai/index.ts Normal file
View File

@@ -0,0 +1,50 @@
import request from '@/utils/request';
import type { ApiResult } from '@/api/index';
/**
* AI聊天消息接口
*/
export interface AiChatMessage {
query: string;
user?: string;
responseMode?: string;
conversationId?: string;
type?: string;
requestType?: number;
}
/**
* AI聊天响应接口
*/
export interface AiChatResponse {
answer: string;
taskId: string;
}
/**
* 发送AI聊天消息
*/
export async function sendAiMessage(data: AiChatMessage) {
const res = await request.post<ApiResult<string>>(
'/chat/message',
data
);
if (res.code === 0) {
return res.data;
}
return Promise.reject(new Error(res.message));
}
/**
* 停止AI聊天
*/
export async function stopAiMessage(data: { taskId: string; type?: string }) {
const res = await request.post<ApiResult<string>>(
'/chat/messageStop',
data
);
if (res.code === 0) {
return res.data;
}
return Promise.reject(new Error(res.message));
}

View File

@@ -46,13 +46,15 @@ export default defineAppConfig({
"root": "honor",
"pages": [
"index",
"detail"
"detail",
"list"
]
},
{
"root": "expert",
"pages": [
"index"
"index",
"detail"
]
},
],

6
src/article/detail.scss Normal file
View File

@@ -0,0 +1,6 @@
.content{
img{
box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
margin-bottom: 40px !important;
}
}

View File

@@ -1,26 +1,26 @@
import {useEffect, useState} from 'react'
import {Tag} from '@nutui/nutui-react-taro'
// import {Tag} from '@nutui/nutui-react-taro'
import {useRouter} from '@tarojs/taro'
import {Divider} from '@nutui/nutui-react-taro'
import {CmsArticle} from "@/api/cms/cmsArticle/model"
import {Eye} from '@nutui/icons-react-taro'
// import {Eye} from '@nutui/icons-react-taro'
// 显示html富文本
import {View, RichText} from '@tarojs/components'
import Line from "@/components/Gap";
import {getCmsArticle} from "@/api/cms/cmsArticle";
import './detail.scss';
function Detail() {
const {params} = useRouter();
// 文章详情
const [item, setItem] = useState<CmsArticle>()
// 浏览量
const [views, setViews] = useState<number>()
// const [views, setViews] = useState<number>()
const reload = () => {
getCmsArticle(Number(params.id)).then(data => {
if (data) {
setItem(data)
setViews(data.actualViews)
// setViews(data.actualViews)
}
})
}
@@ -32,10 +32,10 @@ function Detail() {
return (
<div className={'bg-white'}>
<div className={'p-3 font-bold text-lg'}>{item?.title}</div>
<div className={'flex justify-between px-3'}>
<Tag type={'success'}>{item?.categoryName}</Tag>
<div className={'flex items-center gap-2 text-xs text-gray-400'}><Eye size={14}/>{views}</div>
</div>
{/*<div className={'flex justify-between px-3'}>*/}
{/* <Tag type={'success'}>{item?.categoryName}</Tag>*/}
{/* <div className={'flex items-center gap-2 text-xs text-gray-400'}><Eye size={14}/>{views}</div>*/}
{/*</div>*/}
<Divider/>
<View className={'content text-gray-700 text-sm'}>
<RichText
@@ -43,7 +43,6 @@ function Detail() {
space="nbsp"
/>
</View>
<Line height={44}/>
</div>
)
}

View File

@@ -0,0 +1,4 @@
export default definePageConfig({
navigationBarTitleText: '详情',
navigationBarBackgroundColor: '#ffe0e0'
})

10
src/expert/detail.css Normal file
View File

@@ -0,0 +1,10 @@
.content{
img{
margin: 12px;
background-color: #F2FE03;
padding: 6px;
border-radius: 16px;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
margin-bottom: 40px !important;
}
}

46
src/expert/detail.tsx Normal file
View File

@@ -0,0 +1,46 @@
import {useEffect, useState} from 'react'
import {useRouter} from '@tarojs/taro'
import {Divider} from '@nutui/nutui-react-taro'
import {CmsArticle} from "@/api/cms/cmsArticle/model"
// 显示html富文本
import {View, RichText} from '@tarojs/components'
// import Line from "@/components/Gap";
import {getCmsArticle} from "@/api/cms/cmsArticle";
import './detail.css';
function Detail() {
const {params} = useRouter();
// 文章详情
const [item, setItem] = useState<CmsArticle>()
const reload = () => {
getCmsArticle(Number(params.id)).then(data => {
if (data) {
setItem(data)
}
})
}
useEffect(() => {
reload();
}, []);
return (
<div style={{
background: 'linear-gradient(to bottom, #F63D3D, #C01717)',
minHeight: '100vh'
}}>
<div className={'p-3 font-bold text-center text-lg text-[#F2FE03]'}>{item?.title}</div>
<Divider/>
{/*<img src={item?.image} alt={item?.title} />*/}
<View className={'content text-[#F2FE03] text-sm'}>
<RichText
nodes={item?.content || '暂无内容'}
space="nbsp"
/>
</View>
</div>
)
}
export default Detail

View File

@@ -1,18 +1,18 @@
.veteran-page {
min-height: 100vh;
background: linear-gradient(135deg, #d32f2f 0%, #b71c1c 100%);
.hero-section {
position: relative;
padding: 40px 20px 60px;
background: linear-gradient(135deg, #d32f2f 0%, #b71c1c 100%);
overflow: hidden;
.hero-content {
position: relative;
z-index: 2;
text-align: center;
.hero-title {
font-size: 28px;
font-weight: bold;
@@ -20,7 +20,7 @@
margin-bottom: 20px;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
.hero-subtitle {
font-size: 14px;
line-height: 1.6;
@@ -30,7 +30,7 @@
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}
}
.hero-decoration {
position: absolute;
top: 0;
@@ -38,7 +38,7 @@
width: 100%;
height: 100%;
pointer-events: none;
.decoration-circle {
position: absolute;
top: -50px;
@@ -49,7 +49,7 @@
border-radius: 50%;
animation: rotate 20s linear infinite;
}
.decoration-star {
position: absolute;
bottom: 20px;
@@ -60,7 +60,7 @@
border-right: 15px solid transparent;
border-bottom: 10px solid rgba(255, 255, 255, 0.1);
transform: rotate(35deg);
&::before {
content: '';
position: absolute;
@@ -76,10 +76,10 @@
}
}
}
.veteran-list {
padding: 20px 15px;
.veteran-card {
background: #fff;
border-radius: 12px;
@@ -91,16 +91,16 @@
border: 2px solid #d32f2f;
transition: all 0.3s ease;
cursor: pointer;
&:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}
.veteran-avatar {
flex-shrink: 0;
margin-right: 15px;
.avatar-img {
width: 60px;
height: 60px;
@@ -110,17 +110,17 @@
background: #f5f5f5;
}
}
.veteran-info {
flex: 1;
.veteran-name {
font-size: 18px;
font-weight: bold;
color: #d32f2f;
margin: 0 0 8px 0;
}
.veteran-description {
font-size: 13px;
line-height: 1.5;
@@ -146,36 +146,36 @@
.veteran-page {
.hero-section {
padding: 30px 15px 50px;
.hero-content {
.hero-title {
font-size: 24px;
}
.hero-subtitle {
font-size: 13px;
}
}
}
.veteran-list {
padding: 15px 10px;
.veteran-card {
padding: 15px;
.veteran-avatar {
.avatar-img {
width: 50px;
height: 50px;
}
}
.veteran-info {
.veteran-name {
font-size: 16px;
}
.veteran-description {
font-size: 12px;
}

View File

@@ -4,7 +4,7 @@ import {CmsArticle} from "@/api/cms/cmsArticle/model";
import Taro from '@tarojs/taro'
import {useRouter} from '@tarojs/taro'
import {Image} from '@nutui/nutui-react-taro'
import {getCmsNavigation, pageCmsNavigation} from "@/api/cms/cmsNavigation";
import {getCmsNavigation} from "@/api/cms/cmsNavigation";
import {CmsNavigation} from "@/api/cms/cmsNavigation/model";
/**
@@ -14,7 +14,6 @@ import {CmsNavigation} from "@/api/cms/cmsNavigation/model";
const Index = () => {
const {params} = useRouter();
const [navigation, setNavigation] = useState<CmsNavigation>()
const [childCategory, setChildCategory] = useState<CmsNavigation[]>([])
const [list, setList] = useState<CmsArticle[]>([])
const reload = async () => {
@@ -22,8 +21,6 @@ const Index = () => {
const categoryId = Number(params.id);
// 当前栏目信息
const navs = await getCmsNavigation(categoryId);
// 二级栏目
const childCateogry = await pageCmsNavigation({parentId: categoryId});
// 终极新闻列表
const articles = await pageCmsArticle({categoryId});
@@ -31,10 +28,6 @@ const Index = () => {
if (navs) {
setNavigation(navs);
}
// 获取子级栏目
if (childCateogry) {
setChildCategory(childCateogry.list)
}
// 新闻列表
if (articles) {
setList(articles?.list || [])
@@ -46,56 +39,51 @@ const Index = () => {
}, [])
return (
<>
<div className={'bg-red-200 h-full'}>
<div style={{padding: navigation?.span + 'px'}}>
<Image src={navigation?.style} width={'100%'}
height={'auto'}/>
</div>
<div className={'bg-white rounded-lg py-3 px-2'}>
<div className={'grid grid-cols-2 gap-3'}>
{
// 子级栏目
childCategory.map((item, index) => {
return (
<div
key={index}
className={'flex flex-col justify-center items-center cursor-pointer'}
onClick={() => Taro.navigateTo({url: `./index?id=${item.navigationId}`})}
>
{/* 图片容器 */}
<div className={'w-full mb-2 flex justify-center bg-gray-50 rounded-lg'}>
<img
className={'object-cover rounded-lg'}
src={item.icon}
alt={item.title || ''}
/>
</div>
</div>
)
})
}
</div>
<div className={'grid grid-cols-3 gap-3'}>
<div className={'rounded-lg py-3 px-2'}>
<div className={'grid grid-cols-1 gap-3'}>
{
// 终极文章列表
list.map((item, index) => {
return (
<div
key={index}
className={'flex flex-col items-center cursor-pointer my-1'}
className={'flex items-center cursor-pointer'}
style={{
border: '3px solid #F2FE03',
backgroundColor: '#C01717',
color: '#F2FE03',
borderRadius: '16px',
}}
onClick={() => Taro.navigateTo({url: `./detail?id=${item.articleId}`})}
>
{/* 图片容器 */}
<div className={'w-full mb-2 flex justify-center bg-gray-50 rounded-lg'}>
<div className={'w-full m-3 flex justify-center'}
style={{
width: '108px',
height: '160px',
}}>
<img
className={'object-cover rounded-lg'}
className={'object-cover'}
src={item.image}
alt={item.title || ''}
/>
</div>
{/* 标题 */}
<div className={'text-xs text-center text-gray-800 leading-tight px-1'}>
{item.title}
<div className={'flex flex-col items-start my-3 text-sm leading-tight'} style={{
color: '#F2FE03'
}}>
<p className={'font-bold py-1'}>{item.title}</p>
<p className={'text-xs line-clamp-6'} style={{
width: '240px',
overflow: 'hidden',
}}>
{item.comments || '暂无'}
</p>
</div>
</div>
)
@@ -103,7 +91,7 @@ const Index = () => {
}
</div>
</div>
</>
</div>
)
}
export default Index

10
src/honor/detail.scss Normal file
View File

@@ -0,0 +1,10 @@
.content{
img{
margin: 12px;
background-color: #F2FE03;
padding: 6px;
border-radius: 16px;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
margin-bottom: 40px !important;
}
}

View File

@@ -1,26 +1,21 @@
import {useEffect, useState} from 'react'
import {Tag} from '@nutui/nutui-react-taro'
import {useRouter} from '@tarojs/taro'
import {Divider} from '@nutui/nutui-react-taro'
import {CmsArticle} from "@/api/cms/cmsArticle/model"
import {Eye} from '@nutui/icons-react-taro'
// 显示html富文本
import {View, RichText} from '@tarojs/components'
import Line from "@/components/Gap";
// import Line from "@/components/Gap";
import {getCmsArticle} from "@/api/cms/cmsArticle";
import './detail.scss';
function Detail() {
const {params} = useRouter();
// 文章详情
const [item, setItem] = useState<CmsArticle>()
// 浏览量
const [views, setViews] = useState<number>()
const reload = () => {
getCmsArticle(Number(params.id)).then(data => {
if (data) {
setItem(data)
setViews(data.actualViews)
}
})
}
@@ -30,20 +25,38 @@ function Detail() {
}, []);
return (
<div className={'bg-white'}>
<div className={'p-3 font-bold text-lg'}>{item?.title}</div>
<div className={'flex justify-between px-3'}>
<Tag type={'success'}>{item?.categoryName}</Tag>
<div className={'flex items-center gap-2 text-sm text-gray-400'}><Eye size={14}/>{views}</div>
<div style={{
background: 'linear-gradient(to bottom, #F63D3D, #C01717)',
minHeight: '100vh'
}}>
<div className={'p-4'}>
<div
className={'relative'}
style={{
background: 'url(https://oss.wsdns.cn/20250708/d7a8aad52f6048e5adce13ef0ea86216.png)',
backgroundSize: '100%',
backgroundRepeat: 'no-repeat',
width: '100%',
height: '70px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
>
{/* 标题 */}
<div
className={'absolute z-50 text-sm text-center text-[#F2FE03] font-bold leading-tight px-1'}
>
{item?.title}
</div>
</div>
</div>
<Divider/>
<View className={'content text-gray-700 text-sm'}>
<View className={'content text-[#F2FE03] text-sm'}>
<RichText
nodes={item?.content || '暂无内容'}
space="nbsp"
/>
</View>
<Line height={44}/>
</div>
)
}

View File

@@ -4,7 +4,7 @@ import {CmsArticle} from "@/api/cms/cmsArticle/model";
import Taro from '@tarojs/taro'
import {useRouter} from '@tarojs/taro'
import {Image} from '@nutui/nutui-react-taro'
import {getCmsNavigation} from "@/api/cms/cmsNavigation";
import {getCmsNavigation, pageCmsNavigation} from "@/api/cms/cmsNavigation";
import {CmsNavigation} from "@/api/cms/cmsNavigation/model";
/**
@@ -14,6 +14,7 @@ import {CmsNavigation} from "@/api/cms/cmsNavigation/model";
const Index = () => {
const {params} = useRouter();
const [navigation, setNavigation] = useState<CmsNavigation>()
const [childCategory, setChildCategory] = useState<CmsNavigation[]>([])
const [list, setList] = useState<CmsArticle[]>([])
const reload = async () => {
@@ -21,6 +22,8 @@ const Index = () => {
const categoryId = Number(params.id);
// 当前栏目信息
const navs = await getCmsNavigation(categoryId);
// 二级栏目
const childCateogry = await pageCmsNavigation({parentId: categoryId});
// 终极新闻列表
const articles = await pageCmsArticle({categoryId});
@@ -28,6 +31,10 @@ const Index = () => {
if (navs) {
setNavigation(navs);
}
// 获取子级栏目
if (childCateogry) {
setChildCategory(childCateogry.list)
}
// 新闻列表
if (articles) {
setList(articles?.list || [])
@@ -39,12 +46,46 @@ const Index = () => {
}, [])
return (
<>
<div className={'bg-red-200 h-full'}>
<div style={{padding: navigation?.span + 'px'}}>
<Image src={navigation?.style} width={'100%'}
height={'auto'}/>
</div>
<div className={'bg-white rounded-lg py-3 px-3'}>
<div className={'py-3 px-3'}>
{
// 子级栏目
childCategory && childCategory.map((item, index) => {
return (
<div
key={index}
className={'relative'}
style={{
background: 'url(https://oss.wsdns.cn/20250706/4dd93518d88f4b4a9028a769ad010295.png)',
backgroundSize: '100%',
backgroundRepeat: 'no-repeat',
margin: '10px 0',
width: '100%',
height: '66px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
onClick={() => Taro.navigateTo({url: `./list?id=${item.navigationId}`})}
>
{/* 标题 */}
<div
className={'absolute z-50 text-sm text-center text-[#F2FE03] font-bold leading-tight px-1'}
style={{
backgroundImage: `url(https://oss.wsdns.cn/20250706/4dd93518d88f4b4a9028a769ad010295.png})`,
width: '100%',
height: 'auto'
}}>
{item.title}
</div>
</div>
)
})
}
{
// 终极文章列表
list.map((item, index) => {
@@ -80,7 +121,8 @@ const Index = () => {
})
}
</div>
</>
</div>
)
}
export default Index

5
src/honor/list.config.ts Normal file
View File

@@ -0,0 +1,5 @@
export default definePageConfig({
navigationBarTitleText: '光荣榜',
navigationBarBackgroundColor: '#d32f2f',
navigationBarTextStyle: 'white'
})

186
src/honor/list.scss Normal file
View File

@@ -0,0 +1,186 @@
.veteran-page {
min-height: 100vh;
background: linear-gradient(135deg, #d32f2f 0%, #b71c1c 100%);
.hero-section {
position: relative;
padding: 40px 20px 60px;
background: linear-gradient(135deg, #d32f2f 0%, #b71c1c 100%);
overflow: hidden;
.hero-content {
position: relative;
z-index: 2;
text-align: center;
.hero-title {
font-size: 28px;
font-weight: bold;
color: #fff;
margin-bottom: 20px;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
.hero-subtitle {
font-size: 14px;
line-height: 1.6;
color: rgba(255, 255, 255, 0.9);
margin: 0 auto;
max-width: 320px;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}
}
.hero-decoration {
position: absolute;
top: 0;
right: 0;
width: 100%;
height: 100%;
pointer-events: none;
.decoration-circle {
position: absolute;
top: -50px;
right: -50px;
width: 150px;
height: 150px;
border: 2px solid rgba(255, 255, 255, 0.1);
border-radius: 50%;
animation: rotate 20s linear infinite;
}
.decoration-star {
position: absolute;
bottom: 20px;
right: 30px;
width: 0;
height: 0;
border-left: 15px solid transparent;
border-right: 15px solid transparent;
border-bottom: 10px solid rgba(255, 255, 255, 0.1);
transform: rotate(35deg);
&::before {
content: '';
position: absolute;
left: -15px;
top: 3px;
width: 0;
height: 0;
border-left: 15px solid transparent;
border-right: 15px solid transparent;
border-bottom: 10px solid rgba(255, 255, 255, 0.1);
transform: rotate(-70deg);
}
}
}
}
.veteran-list {
padding: 20px 15px;
.veteran-card {
background: #fff;
border-radius: 12px;
margin-bottom: 15px;
padding: 20px;
display: flex;
align-items: flex-start;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
border: 2px solid #d32f2f;
transition: all 0.3s ease;
cursor: pointer;
&:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}
.veteran-avatar {
flex-shrink: 0;
margin-right: 15px;
.avatar-img {
width: 60px;
height: 60px;
border-radius: 50%;
object-fit: cover;
border: 3px solid #d32f2f;
background: #f5f5f5;
}
}
.veteran-info {
flex: 1;
.veteran-name {
font-size: 18px;
font-weight: bold;
color: #d32f2f;
margin: 0 0 8px 0;
}
.veteran-description {
font-size: 13px;
line-height: 1.5;
color: #666;
text-align: justify;
}
}
}
}
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
/* 响应式设计 */
@media (max-width: 375px) {
.veteran-page {
.hero-section {
padding: 30px 15px 50px;
.hero-content {
.hero-title {
font-size: 24px;
}
.hero-subtitle {
font-size: 13px;
}
}
}
.veteran-list {
padding: 15px 10px;
.veteran-card {
padding: 15px;
.veteran-avatar {
.avatar-img {
width: 50px;
height: 50px;
}
}
.veteran-info {
.veteran-name {
font-size: 16px;
}
.veteran-description {
font-size: 12px;
}
}
}
}
}
}

123
src/honor/list.tsx Normal file
View File

@@ -0,0 +1,123 @@
import {useEffect, useState} from "react";
import {pageCmsArticle} from "@/api/cms/cmsArticle";
import {CmsArticle} from "@/api/cms/cmsArticle/model";
import Taro from '@tarojs/taro'
import {useRouter} from '@tarojs/taro'
import {Image} from '@nutui/nutui-react-taro'
import {getCmsNavigation} from "@/api/cms/cmsNavigation";
import {CmsNavigation} from "@/api/cms/cmsNavigation/model";
/**
* 文章终极列表
* @constructor
*/
const List = () => {
const {params} = useRouter();
const [navigation, setNavigation] = useState<CmsNavigation>()
const [list, setList] = useState<CmsArticle[]>([])
const reload = async () => {
// 获取栏目ID
const categoryId = Number(params.id);
// 当前栏目信息
const navs = await getCmsNavigation(categoryId);
// 终极新闻列表
const articles = await pageCmsArticle({categoryId});
// 当前栏目信息
if (navs) {
setNavigation(navs);
}
// 新闻列表
if (articles) {
setList(articles?.list || [])
}
}
useEffect(() => {
reload()
}, [])
return (
<div className={'bg-red-200 h-full'}>
<div style={{padding: navigation?.span + 'px'}}>
<Image src={navigation?.style} width={'100%'}
height={'auto'}/>
</div>
<div className={'p-4'}>
<div
className={'relative'}
style={{
background: 'url(https://oss.wsdns.cn/20250708/d7a8aad52f6048e5adce13ef0ea86216.png)',
backgroundSize: '100%',
backgroundRepeat: 'no-repeat',
width: '100%',
height: '70px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
>
{/* 标题 */}
<div
className={'absolute z-50 text-sm text-center text-[#F2FE03] font-bold leading-tight px-1'}
>
{navigation?.categoryName}
</div>
</div>
</div>
<div className={'rounded-lg py-3 px-2'}>
<div className={'grid grid-cols-1 gap-3'}>
{
// 终极文章列表
list.map((item, index) => {
return (
<div
key={index}
className={'flex items-center cursor-pointer'}
style={{
border: '3px solid #F2FE03',
backgroundColor: '#C01717',
color: '#F2FE03',
borderRadius: '16px',
}}
onClick={() => Taro.navigateTo({url: `./detail?id=${item.articleId}`})}
>
{
// 图片容器
item.image && (
<div className={'w-full m-3 flex justify-center'}
style={{
width: '108px',
height: '160px',
}}>
<img
className={'object-cover'}
src={item.image}
alt={item.title || ''}
/>
</div>
)
}
{/* 标题 */}
<div className={'flex flex-col items-start my-3 text-sm leading-tight'} style={{
color: '#F2FE03'
}}>
<p className={'font-bold py-1'}>{item.title}</p>
<p className={'text-xs line-clamp-6'} style={{
width: '240px',
overflow: 'hidden',
}}>
{item.comments || '暂无'}
</p>
</div>
</div>
)
})
}
</div>
</div>
</div>
)
}
export default List

View File

@@ -0,0 +1,3 @@
export default definePageConfig({
navigationBarTitleText: 'AI问答'
})

289
src/pages/ai/index.scss Normal file
View File

@@ -0,0 +1,289 @@
.ai-chat {
height: 94vh;
display: flex;
flex-direction: column;
background-color: #f5f5f5;
.chat-header {
background: linear-gradient(135deg, #a6ea66 0%, #ead1ff 100%);
color: white;
padding: 16px;
text-align: center;
font-size: 18px;
font-weight: bold;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.chat-container {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.messages-container {
flex: 1;
padding: 16px;
overflow-y: auto;
scroll-behavior: smooth;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.2);
border-radius: 2px;
}
}
.message {
margin-bottom: 16px;
display: flex;
align-items: flex-start;
animation: fadeInUp 0.3s ease-out;
&.user {
flex-direction: row-reverse;
.message-content {
background: linear-gradient(135deg, #ff3535 0%, #FF0000 100%);
color: white;
margin-left: 0;
margin-right: 12px;
}
}
&.ai {
flex-direction: row;
.message-content {
background: white;
color: #333;
margin-left: 12px;
margin-right: 0;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
}
.avatar {
width: 40px;
height: 40px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
flex-shrink: 0;
&.user-avatar {
background: linear-gradient(135deg, #df2626 0%, #d10a0a 100%);
color: white;
}
&.ai-avatar {
background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);
color: white;
}
}
.message-content {
max-width: 70%;
padding: 12px 16px;
border-radius: 18px;
word-wrap: break-word;
line-height: 1.5;
font-size: 14px;
position: relative;
.typing-indicator {
display: flex;
align-items: center;
gap: 4px;
.dot {
width: 6px;
height: 6px;
border-radius: 50%;
background-color: #999;
animation: typing 1.4s infinite ease-in-out;
&:nth-child(1) { animation-delay: -0.32s; }
&:nth-child(2) { animation-delay: -0.16s; }
&:nth-child(3) { animation-delay: 0s; }
}
}
}
}
.input-container {
background: white;
padding: 16px;
border-top: 1px solid #e0e0e0;
display: flex;
align-items: flex-end;
gap: 12px;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
.input-wrapper {
flex: 1;
position: relative;
}
.message-input {
width: 100%;
min-height: 40px;
max-height: 120px;
padding: 10px 16px;
border: 1px solid #e0e0e0;
border-radius: 20px;
font-size: 14px;
line-height: 1.5;
resize: none;
outline: none;
background: #f9f9f9;
transition: all 0.3s ease;
&:focus {
border-color: #ffc6c6;
background: white;
box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}
&::placeholder {
color: #999;
}
}
.send-button {
width: 40px;
height: 40px;
border-radius: 50%;
background: linear-gradient(135deg, #ff0000 0%, #af1403 100%);
border: none;
color: white;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.3s ease;
flex-shrink: 0;
&:hover {
transform: scale(1.05);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}
&:active {
transform: scale(0.95);
}
&:disabled {
background: #ccc;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
}
}
.quick-questions {
padding: 16px;
background: white;
border-top: 1px solid #e0e0e0;
.quick-title {
font-size: 14px;
color: #666;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 8px;
}
.questions-list {
display: flex;
flex-direction: column;
gap: 8px;
.question-item {
padding: 12px 16px;
background: #f9f9f9;
border: 1px solid #e0e0e0;
border-radius: 12px;
font-size: 14px;
color: #333;
cursor: pointer;
transition: all 0.3s ease;
text-align: left;
&:hover {
background: #667eea;
color: white;
border-color: #667eea;
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}
&:active {
transform: translateY(0);
}
}
}
}
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px 20px;
text-align: center;
.empty-icon {
font-size: 64px;
margin-bottom: 16px;
opacity: 0.5;
}
.empty-title {
font-size: 18px;
font-weight: bold;
color: #333;
margin-bottom: 8px;
}
.empty-desc {
font-size: 14px;
color: #666;
line-height: 1.5;
}
}
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes typing {
0%, 80%, 100% {
transform: scale(0);
opacity: 0.5;
}
40% {
transform: scale(1);
opacity: 1;
}
}

269
src/pages/ai/index.tsx Normal file
View File

@@ -0,0 +1,269 @@
import { useEffect, useState, useRef } from "react";
import { View, Textarea } from '@tarojs/components';
// import Toast from '@tarojs/taro';
import Taro from '@tarojs/taro';
import { Button } from '@nutui/nutui-react-taro';
import { User, ArrowUp } from '@nutui/icons-react-taro';
import { sendAiMessage, stopAiMessage } from '@/api/ai';
import { createWebSocket } from '@/utils/websocket';
import './index.scss';
import {APP_API_URL} from "@/utils/server";
// 消息类型
interface Message {
id?: string;
type?: 'user' | 'ai';
query?: string;
timestamp?: number;
isTyping?: boolean;
user?: string;
responseMode?: string;
}
/**
* AI问答页面
*/
const AiChat = () => {
const [messages, setMessages] = useState<Message[]>([]);
const [inputValue, setInputValue] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [currentTaskId, setCurrentTaskId] = useState<string>('');
const messagesEndRef = useRef<HTMLDivElement>(null);
const wsRef = useRef<any>(null);
// 快捷问题
const quickQuestions = [
"当兵的注意事项?",
"男兵应征报名对象:",
"当兵公务员考试?",
"请问您还有什么问题吗?"
];
// 滚动到底部
const scrollToBottom = () => {
setTimeout(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, 100);
};
// 初始化WebSocket连接
const initWebSocket = () => {
const wsUrl = APP_API_URL.replace('https', 'ws') + '/chat/' + Taro.getStorageSync('UserId') || 'token';
// const wsUrl = 'ws://127.0.0.1:9000/chat/test'
wsRef.current = createWebSocket(wsUrl);
wsRef.current.onMessage((data: any) => {
console.log('收到WebSocket消息:', data);
if (data.answer) {
if (data.answer === '__END__') {
// 消息结束移除typing状态
setMessages(prev => prev.map(msg =>
msg.isTyping ? { ...msg, isTyping: false } : msg
));
setIsLoading(false);
setCurrentTaskId('');
} else {
// 更新AI回复消息
setMessages(prev => {
const lastMessage = prev[prev.length - 1];
if (lastMessage && lastMessage.type === 'ai' && lastMessage.isTyping) {
// 更新最后一条AI消息
return prev.map((msg, index) =>
index === prev.length - 1
? { ...msg, query: msg.query + data.answer }
: msg
);
} else {
// 创建新的AI消息
return [...prev, {
id: Date.now().toString(),
type: 'ai',
query: data.answer,
timestamp: Date.now(),
isTyping: true
}];
}
});
if (data.taskId) {
setCurrentTaskId(data.taskId);
}
}
scrollToBottom();
}
});
wsRef.current.onOpen(() => {
console.log('WebSocket连接成功');
});
wsRef.current.onError((error: any) => {
console.error('WebSocket连接错误:', error);
// Toast.showToast({ title: '连接失败,请检查网络', icon: 'error'});
});
wsRef.current.connect().catch((error: any) => {
console.error('WebSocket连接失败:', error);
});
};
useEffect(() => {
initWebSocket();
Taro.hideTabBar();
return () => {
if (wsRef.current) {
wsRef.current.close();
}
};
}, []);
useEffect(() => {
scrollToBottom();
}, [messages]);
// 发送消息
const handleSendMessage = async (content: string) => {
if (!content.trim() || isLoading) return;
const userMessage: Message = {
id: Date.now().toString(),
type: 'user',
query: content.trim(),
timestamp: Date.now(),
user: `${Taro.getStorageSync('UserId')}`
};
setMessages(prev => [...prev, userMessage]);
setInputValue('');
setIsLoading(true);
try {
await sendAiMessage({
query: content.trim(),
user: `${Taro.getStorageSync('UserId')}`,
responseMode: 'streaming',
});
} catch (error) {
console.error('发送消息失败:', error);
// Toast.showToast({ title: '发送失败,请重试', icon: 'error'});
setIsLoading(false);
}
};
// 停止AI回复
const handleStopMessage = async () => {
if (currentTaskId) {
try {
await stopAiMessage({ taskId: currentTaskId });
setIsLoading(false);
setCurrentTaskId('');
setMessages(prev => prev.map(msg =>
msg.isTyping ? { ...msg, isTyping: false } : msg
));
} catch (error) {
console.error('停止消息失败:', error);
}
}
};
// 处理快捷问题点击
const handleQuickQuestion = (question: string) => {
console.log(question,'qqq')
handleSendMessage(question);
};
return (
<View className="ai-chat">
{/*<View className="chat-header">*/}
{/* AI智能问答*/}
{/*</View>*/}
<View className="chat-container">
<View className="messages-container">
{messages.length === 0 ? (
<View className="empty-state">
<View className="empty-icon">🤖</View>
<View className="empty-title">AI助手</View>
<View className="empty-desc">
</View>
</View>
) : (
messages.map((message) => (
<View key={message.id} className={`message ${message.type}`}>
<View className={`avatar ${message.type}-avatar`}>
{message.type === 'user' ? <User size={20} /> : '🤖'}
</View>
<View className="message-content">
{message.isTyping ? (
<View className="typing-indicator">
<View className="dot"></View>
<View className="dot"></View>
<View className="dot"></View>
</View>
) : (
message.query
)}
</View>
</View>
))
)}
<View ref={messagesEndRef} />
</View>
{messages.length === 0 && (
<View className="quick-questions">
<View className="quick-title">
💡
</View>
<View className="questions-list">
{quickQuestions.map((question, index) => (
<View
key={index}
className="question-item"
onClick={() => handleQuickQuestion(question)}
>
{question}
</View>
))}
</View>
</View>
)}
<View className="input-container">
<View className="input-wrapper">
<Textarea
className="message-input"
value={inputValue}
placeholder="请输入您的问题..."
onInput={(e) => setInputValue(e.detail.value)}
onConfirm={() => handleSendMessage(inputValue)}
disabled={isLoading}
autoHeight
maxlength={500}
/>
</View>
{isLoading ? (
<Button
onClick={handleStopMessage}
type="danger"
icon={<ArrowUp />}
>
</Button>
) : (
<Button
type="danger"
onClick={() => handleSendMessage(inputValue)}
disabled={!inputValue.trim()}
icon={<ArrowUp />}
>
</Button>
)}
</View>
</View>
</View>
);
};
export default AiChat;

View File

@@ -10,7 +10,6 @@ const MyPage = () => {
const reload = () => {
pageCmsAd({keywords: '幻灯片'}).then(data => {
console.log(data,'幻灯片')
if(data && data?.count > 0){
const cmsAd = data.list[0];
setHeight(cmsAd.height)

View File

@@ -10,8 +10,6 @@ const Page = () => {
const reload = () => {
getSiteInfo().then(res => {
console.log(res);
console.log(res.topNavs, 'top');
setNavItems(res.topNavs || []);
})
};
@@ -21,19 +19,21 @@ const Page = () => {
}, [])
return (
<div className={'py-2 my-3 mx-2'}>
<div className={'bg-white grid grid-cols-1 md:grid-cols-3 lg:grid-cols-3 gap-2'}>
{
navItems.map((item) => (
<div className={'flex flex-col justify-center items-center'} onClick={() => Taro.navigateTo({url: `/${item.model}/index?id=${item.navigationId}`})}>
<Image className={'shadow-xl rounded-lg'} style={{borderRadius: '8px'}} src={item.icon}
height={90} width={90}/>
<div className={'mt-2 text-gray-700'} style={{fontSize: '15px'}}>{item?.title}</div>
</div>
))
}
<>
<div className={'py-2 my-3 mx-2'}>
<div className={'bg-white grid grid-cols-1 md:grid-cols-3 lg:grid-cols-3 gap-2'}>
{
navItems?.map((item) => (
<div className={'flex flex-col justify-center items-center'} onClick={() => Taro.navigateTo({url: `/${item.model}/index?id=${item.navigationId}`})}>
<Image className={'shadow-xl rounded-lg'} style={{borderRadius: '8px'}} src={item.icon}
height={90} width={90}/>
<div className={'mt-2 text-gray-700'} style={{fontSize: '15px'}}>{item?.title}</div>
</div>
))
}
</div>
</div>
</div>
</>
)
}
export default Page

View File

@@ -1,4 +1,4 @@
import {Avatar, Tag, Space} from '@nutui/nutui-react-taro'
import {Avatar} from '@nutui/nutui-react-taro'
import {useEffect, useState} from "react";
import {User} from "@/api/system/user/model";
import navTo from "@/utils/common";
@@ -15,9 +15,9 @@ function UserCard() {
}, []);
const reload = async () => {
setIsLogin(true)
if(Taro.getStorageSync('UserId')){
if (Taro.getStorageSync('UserId')) {
setUserInfo(await getUserInfo())
setIsLogin(true)
}
};
@@ -35,7 +35,7 @@ function UserCard() {
}}
>
<div className={'user-card-header flex w-full justify-between items-center'}>
<div className={'flex items-center mx-4'}>
<div className={'flex items-center mx-1'}>
{
IsLogin && (
<Avatar size="large" src={userInfo?.avatar} shape="round"/>
@@ -43,24 +43,16 @@ function UserCard() {
}
{
!IsLogin && (
<Avatar size="large" src={userInfo?.avatar} shape="round"/>
<Avatar size="large" onClick={() => Taro.navigateTo({url: '/passport/sms-login'})}
src={userInfo?.avatar} shape="round"/>
)
}
<div className={'user-info flex flex-col px-2'}>
{IsLogin ? (
<Space className={'grade text-xs py-1'}>
<Tag type="warning" round>
<div className={'p-1'}>{'注册用户'}</div>
</Tag>
{/*{*/}
{/* userInfo?.organizationName && (*/}
{/* <Tag type="warning" round>*/}
{/* <div className={'p-1'}>{userInfo?.organizationName}</div>*/}
{/* </Tag>*/}
{/* )*/}
{/*}*/}
</Space>
) : ''}
<div className={'user-info flex flex-col px-1'}>
{!IsLogin ? (
<div className={'p-1 text-sm text-white'}>{'点击登录'}</div>
) :
<div className={'p-1 text-sm text-white'}>{userInfo?.mobile}</div>
}
</div>
</div>
<div

View File

@@ -163,7 +163,7 @@ const SmsLogin = () => {
maxLength={11}
value={formData.phone}
onChange={(value) => setFormData({...formData, phone: value})}
style={{backgroundColor: '#ffffff', borderRadius: '8px'}}
style={{backgroundColor: '#f3f3f3', borderRadius: '8px'}}
/>
</div>
<div className={'flex justify-between items-center bg-white rounded-lg my-2 pr-2'}>
@@ -173,7 +173,7 @@ const SmsLogin = () => {
maxLength={6}
value={formData.code}
onChange={(value) => setFormData({...formData, code: value})}
style={{ backgroundColor: '#ffffff', borderRadius: '8px'}}
style={{ backgroundColor: '#f3f3f3', borderRadius: '8px', marginRight: '16px'}}
/>
<Button
size="small"
@@ -187,7 +187,7 @@ const SmsLogin = () => {
</div>
<div className={'flex justify-center my-5'}>
<Button
type="info"
type="primary"
size={'large'}
className={'w-full rounded-lg p-2'}
loading={loading}

View File

@@ -2,8 +2,8 @@ import {useEffect, useState} from 'react'
import {useRouter} from '@tarojs/taro'
import {Divider} from '@nutui/nutui-react-taro'
import {CmsArticle} from "@/api/cms/cmsArticle/model"
import {Eye} from '@nutui/icons-react-taro'
import dayjs from 'dayjs';
// import {Eye} from '@nutui/icons-react-taro'
// import dayjs from 'dayjs';
// 显示html富文本
import {View, RichText} from '@tarojs/components'
import Line from "@/components/Gap";
@@ -14,13 +14,13 @@ function Detail() {
// 文章详情
const [item, setItem] = useState<CmsArticle>()
// 浏览量
const [views, setViews] = useState<number>()
// const [views, setViews] = useState<number>()
const reload = () => {
getCmsArticle(Number(params.id)).then(data => {
if (data) {
setItem(data)
setViews(data.actualViews)
// setViews(data.actualViews)
}
})
}
@@ -32,11 +32,11 @@ function Detail() {
return (
<div className={'bg-white'}>
<div className={'p-3 font-bold text-lg'}>{item?.title}</div>
<div className={'flex items-center text-gray-400 text-xs px-3 gap-3'}>
<div className={'text-red-800'}>{item?.author}</div>
<div>{dayjs(item?.createTime).format('YYYY-MM-DD')}</div>
<div className={'flex items-center gap-1'}><Eye size={14}/>{views}</div>
</div>
{/*<div className={'flex items-center text-gray-400 text-xs px-3 gap-3'}>*/}
{/* <div className={'text-red-800'}>{item?.author}</div>*/}
{/* <div>{dayjs(item?.createTime).format('YYYY-MM-DD')}</div>*/}
{/* <div className={'flex items-center gap-1'}><Eye size={14}/>{views}</div>*/}
{/*</div>*/}
<Divider/>
<View className={'content text-gray-700 text-sm'}>
<RichText

View File

@@ -46,12 +46,12 @@ const Index = () => {
}, [])
return (
<>
<div className={'bg-red-200 h-full'}>
<div style={{padding: navigation?.span + 'px'}}>
<Image src={navigation?.style} width={'100%'}
height={'auto'}/>
</div>
<div className={'bg-white rounded-lg py-3 px-3'}>
<div className={'py-3 px-3'}>
<div className={'grid grid-cols-2 gap-3'}>
{
// 子级栏目
@@ -99,7 +99,7 @@ const Index = () => {
}
</div>
</div>
</>
</div>
)
}
export default Index

View File

@@ -4,7 +4,7 @@ import {BaseUrl, TenantId} from "@/utils/config";
let baseUrl = BaseUrl
if(process.env.NODE_ENV === 'development'){
// baseUrl = 'http://localhost:9000/api'
baseUrl = 'http://localhost:9000/api'
}
export function request<T>(options:any) {
const token = Taro.getStorageSync('access_token');

View File

@@ -7,7 +7,8 @@ export const TEMPLATE_ID = 10556;
export const SERVER_API_URL = 'https://server.gxwebsoft.com/api';
// export const SERVER_API_URL = 'http://127.0.0.1:8000/api';
// 服务接口
export const APP_API_URL = 'http://127.0.0.1:9000/api';
export const APP_API_URL = 'https://cms-api.websoft.top/api';
// export const APP_API_URL = 'http://127.0.0.1:9000/api';
/**
* 保存用户信息到本地存储
* @param token

176
src/utils/websocket.ts Normal file
View File

@@ -0,0 +1,176 @@
/**
* WebSocket连接管理类
*/
export class WebSocketManager {
private ws: WebSocket | null = null;
private url: string;
private reconnectAttempts = 0;
private maxReconnectAttempts = 5;
private reconnectInterval = 3000;
private heartbeatInterval: NodeJS.Timeout | null = null;
private heartbeatTimer = 30000; // 30秒心跳
// 事件回调
private onMessageCallback?: (data: any) => void;
private onOpenCallback?: () => void;
private onCloseCallback?: () => void;
private onErrorCallback?: (error: Event) => void;
constructor(url: string) {
this.url = url;
}
/**
* 连接WebSocket
*/
connect(): Promise<void> {
return new Promise((resolve, reject) => {
try {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
console.log('WebSocket连接成功');
this.reconnectAttempts = 0;
this.startHeartbeat();
this.onOpenCallback?.();
resolve();
};
this.ws.onmessage = (event) => {
console.log(event,'event>>>')
try {
const data = JSON.parse(event.data);
this.onMessageCallback?.(data);
} catch (error) {
console.error('解析WebSocket消息失败:', error);
}
};
this.ws.onclose = () => {
console.log('WebSocket连接关闭');
this.stopHeartbeat();
this.onCloseCallback?.();
this.handleReconnect();
};
this.ws.onerror = (error) => {
console.error('WebSocket连接错误:', error);
this.onErrorCallback?.(error);
reject(error);
};
} catch (error) {
reject(error);
}
});
}
/**
* 发送消息
*/
send(message: any): void {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(typeof message === 'string' ? message : JSON.stringify(message));
} else {
console.warn('WebSocket未连接无法发送消息');
}
}
/**
* 关闭连接
*/
close(): void {
this.stopHeartbeat();
if (this.ws) {
this.ws.close();
this.ws = null;
}
}
/**
* 重连处理
*/
private handleReconnect(): void {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
console.log(`尝试重连WebSocket (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
setTimeout(() => {
this.connect().catch(error => {
console.error('重连失败:', error);
});
}, this.reconnectInterval);
} else {
console.error('WebSocket重连次数已达上限');
}
}
/**
* 开始心跳
*/
private startHeartbeat(): void {
this.heartbeatInterval = setInterval(() => {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({ type: 'ping' }));
}
}, this.heartbeatTimer);
}
/**
* 停止心跳
*/
private stopHeartbeat(): void {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
}
/**
* 设置消息回调
*/
onMessage(callback: (data: any) => void): void {
this.onMessageCallback = callback;
}
/**
* 设置连接成功回调
*/
onOpen(callback: () => void): void {
this.onOpenCallback = callback;
}
/**
* 设置连接关闭回调
*/
onClose(callback: () => void): void {
this.onCloseCallback = callback;
}
/**
* 设置错误回调
*/
onError(callback: (error: Event) => void): void {
this.onErrorCallback = callback;
}
/**
* 获取连接状态
*/
getReadyState(): number {
return this.ws?.readyState ?? WebSocket.CLOSED;
}
/**
* 是否已连接
*/
isConnected(): boolean {
return this.ws?.readyState === WebSocket.OPEN;
}
}
/**
* 创建WebSocket连接
*/
export function createWebSocket(url: string): WebSocketManager {
return new WebSocketManager(url);
}