intelligentLifeChart.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. <template>
  2. <view class="dialog-generation">
  3. <view class="subject-matter-ofText" :style="{ paddingBottom: keyboardHeight + 'px' }">
  4. <!-- 顶部导航栏 -->
  5. <div class="navbar">
  6. <view class="navbar-left">
  7. <image @click="goBack()" class="back" src="../../static/vip/hy_icon_jiantou.png"></image>
  8. <view class="elf-name">精灵·小萌</view>
  9. <image class="deepseek" src="../../static/makedetail/deepseek-logo.png"></image>
  10. </view>
  11. <view class="navbar-right">
  12. <image @click="switchToNormal()" class="primary" src="../../static/makedetail/primary.png"></image>
  13. <image @click="newChar()" class="createChat" src="../../static/makedetail/createChat.png"></image>
  14. </view>
  15. </div>
  16. <!-- <view class="navbar-reserveASeat"> </view> -->
  17. <!-- 聊天内容区 -->
  18. <scroll-view class="chat-content" :scroll-into-view="toView" scroll-y
  19. :style="{ height: `calc(100% - ${370 + textareaHeight}rpx)` }" @scroll="onChatScroll">
  20. <template v-if="messages && messages.length > 0">
  21. <!-- <scroll-view class="chat-content" scroll-y> -->
  22. <view v-for="(msg, idx) in messages" :key="idx" :class="['chat-bubble', msg.role]">
  23. <template v-if="msg.role === 'user'">
  24. {{ msg.content }}
  25. </template>
  26. <template v-else-if="msg.role === 'ai'">
  27. <view class="ai-bubble-row">
  28. <view class="ai-avatar">
  29. <image src="../../static/makedetail/characterProfilePicture.png" mode="aspectFill">
  30. </image>
  31. </view>
  32. <view class="ai-bubble-content" v-if="!msg.isStartGenerating">
  33. <template v-if="idx === lastAiIndex && isLoading">
  34. <text>{{ displayText }}</text>
  35. <text v-if="isLoading" class="loading-dot">...</text>
  36. </template>
  37. <template v-else>
  38. <text>{{ msg.content }}</text>
  39. </template>
  40. </view>
  41. <view v-else class="ai-bubble-content">
  42. <text>OK!~小萌正在根据你的描述生成形象中</text><br>
  43. <div v-if="msg.isStartGenerating && msg.startGeneratingId == 0" class="btn-box">
  44. 点击查看
  45. ({{ countdown }}) s</div>
  46. <div v-else
  47. @click="goPage(`/pages/makedetail/makeImgDetail?id=${msg.startGeneratingId}`)"
  48. class="btn-box"> 点击查看
  49. </div>
  50. </view>
  51. </view>
  52. </template>
  53. </view>
  54. <view id="bottom-anchor"></view>
  55. <view v-if="error" class="chat-bubble ai error">{{ error }}</view>
  56. <image v-if="showToBottomBtn && keyboardHeight === 0" class="to-bottom-btn" @click="scrollToBottom"
  57. src="../../static/makedetail/toBottomBtn.png"></image>
  58. </template>
  59. <template v-else>
  60. <view class="chat-content-empty">
  61. <image src="../../static/makedetail/characterProfilePicture.png" mode="aspectFill"></image>
  62. <view class="chat-content-empty-title">嗨!我是创梦精灵</view>
  63. <view class="chat-content-empty-desc">与我聊聊你想要生成的角色吧!</view>
  64. </view>
  65. </template>
  66. <view style="width: 100%;height: 200rpx;"></view>
  67. </scroll-view>
  68. <!-- <view class="bom-reserveASeat"></view> -->
  69. <view class="bom-box" :style="{ bottom: 0 + 'px', height: `${190 + textareaHeight}rpx` }">
  70. <view class="bom-box-bg">
  71. <c-lottie ref="cLottieRef" :src='"/static/lottie/xiaomeng.json"' class="icon-img" height="108rpx"
  72. width="112rpx" :loop="true" :autoPlay="false"></c-lottie>
  73. </view>
  74. <!-- 底部输入区 -->
  75. <view class="input-bar">
  76. <!-- <image class="icon-img" src="../../static/makedetail/characterProfilePicture.png" mode="aspectFill">
  77. </image> -->
  78. <textarea :autoHeight="true" class="input-box" :adjust-position="false" v-model="question"
  79. :disabled="isLoading" placeholder="给我发送消息吧..." maxlength="400" @input="onTextareaInput"
  80. confirm-type="search" @confirm="onSend" rows="1"
  81. style="overflow-y:auto;max-height:176rpx;min-height:44rpx;" />
  82. <!-- <button class="send-btn" :disabled="isLoading || !question.trim()" @click="onSend">{{ isLoading ?
  83. '生成中...' :
  84. '发送' }}</button> -->
  85. <image v-if="isLoading" class="stop" src="../../static/makedetail/stop.png" mode=""
  86. @click="stopStreamAnswer" />
  87. <image v-else-if="!isLoading && !question.trim() && keyboardHeight === 0" class="keyboard"
  88. src="../../static/makedetail/keyboard.png" mode="" />
  89. <image v-else-if="!isLoading && question.trim() && keyboardHeight !== 0" class="send"
  90. src="../../static/makedetail/send.png" mode="" @click="onSend" />
  91. </view>
  92. <!-- 底部提示 -->
  93. <view class="footer-tip">内容由AI生成,禁用相关功能请联系管理员。</view>
  94. </view>
  95. </view>
  96. <DialogBox ref="DialogBox"></DialogBox>
  97. </view>
  98. </template>
  99. <script>
  100. import websocket from '@/common/websocket.js';
  101. export default {
  102. data() {
  103. return {
  104. question: '',
  105. answer: '',
  106. displayText: '',
  107. isComplete: false,
  108. isLoading: false,
  109. error: null,
  110. retryCount: 0,
  111. maxRetries: 3,
  112. timer: null,
  113. lastResponseTime: 0,
  114. timeout: 30000,
  115. typingSpeed: 50,
  116. messages: [],
  117. lastAiIndex: -1,
  118. keyboardHeight: 0,
  119. statusBarHeight: 0,
  120. windowBottom: 0,
  121. toView: '',
  122. showToBottomBtn: false,
  123. textareaHeight: 0,
  124. isConnected: false,
  125. isStartGenerating: false,
  126. countdown: 0,
  127. };
  128. },
  129. methods: {
  130. scrollToBottom() {
  131. this.toView = '';
  132. this.$nextTick(() => {
  133. this.toView = 'bottom-anchor';
  134. });
  135. },
  136. async initWebSocket() {
  137. if (this.isConnected) return;
  138. try {
  139. await websocket.connect('wss://e.zhichao.art/Gapi/Work/streamAnswer', {
  140. uuid: getApp().globalData.uuid
  141. });
  142. this.isConnected = true;
  143. // 设置消息处理回调
  144. websocket.onMessage((data) => {
  145. console.log("data:", data);
  146. if (this.isLoading) {
  147. if (data.includes('[DONE]')) {
  148. this.completeAnswer();
  149. } else if (data == 'PING' || data == 'PONG') {
  150. // 心跳消息 忽略
  151. } else if (data.includes('ID:')) {
  152. // 提取ID
  153. const aiMsg = this.messages[this.lastAiIndex];
  154. if (aiMsg) {
  155. aiMsg.startGeneratingId = data.split(':')[1];
  156. }
  157. } else if (data.includes('OKOKOK')) {
  158. const aiMsg = this.messages[this.lastAiIndex];
  159. if (aiMsg) {
  160. aiMsg.isStartGenerating = true;
  161. }
  162. this.isStartGenerating = true;
  163. this.countdownFun(20);
  164. } else {
  165. const aiMsg = this.messages[this.lastAiIndex];
  166. if (aiMsg) {
  167. aiMsg.isStartGenerating = false;
  168. this.displayText += data;
  169. this.answer += data;
  170. aiMsg.content += data;
  171. this.retryCount = 0;
  172. this.lastResponseTime = Date.now();
  173. this.scrollToBottom();
  174. }
  175. }
  176. }
  177. });
  178. // 设置错误处理回调
  179. websocket.onError((error) => {
  180. console.error('WebSocket错误:', error);
  181. this.isConnected = false;
  182. this.handleError(error);
  183. });
  184. // 设置关闭处理回调
  185. websocket.onClose(() => {
  186. console.log('WebSocket已关闭');
  187. this.isConnected = false;
  188. this.isLoading = false;
  189. });
  190. } catch (error) {
  191. console.error('WebSocket初始化失败:', error);
  192. this.isConnected = false;
  193. this.handleError(error);
  194. }
  195. },
  196. async startStreamAnswer(content) {
  197. if (!content.trim()) {
  198. uni.showToast({
  199. title: '请输入问题',
  200. icon: 'none'
  201. });
  202. return;
  203. }
  204. // 检查连接状态,如果断开则重连
  205. if (!this.isConnected) {
  206. try {
  207. await this.initWebSocket();
  208. } catch (error) {
  209. console.error('重连失败:', error);
  210. uni.showToast({
  211. title: '连接已断开,请重试',
  212. icon: 'none'
  213. });
  214. return;
  215. }
  216. }
  217. this.resetState();
  218. this.messages.push({
  219. role: 'user',
  220. content
  221. });
  222. try {
  223. this.isLoading = true;
  224. let aiMsg = {
  225. role: 'ai',
  226. content: '',
  227. isStartGenerating: false,
  228. startGeneratingId: 0
  229. };
  230. this.messages.push(aiMsg);
  231. this.lastAiIndex = this.messages.length - 1;
  232. // 发送消息
  233. websocket.send(content);
  234. } catch (error) {
  235. console.error('发送消息失败:', error);
  236. this.handleError(error);
  237. }
  238. },
  239. onSend() {
  240. if (!this.question.trim() || this.isLoading) return;
  241. this.startStreamAnswer(this.question);
  242. this.question = '';
  243. },
  244. resetState() {
  245. this.answer = '';
  246. this.displayText = '';
  247. this.isComplete = false;
  248. this.error = null;
  249. this.retryCount = 0;
  250. this.lastResponseTime = Date.now();
  251. },
  252. handleError(error) {
  253. if (this.retryCount < this.maxRetries) {
  254. this.retryCount++;
  255. this.retryRequest();
  256. } else {
  257. this.error = '请求失败,请稍后重试';
  258. this.isLoading = false;
  259. uni.showToast({
  260. title: this.error,
  261. icon: 'none'
  262. });
  263. }
  264. },
  265. retryRequest() {
  266. uni.showToast({
  267. title: `正在重试 (${this.retryCount}/${this.maxRetries})`,
  268. icon: 'none'
  269. });
  270. setTimeout(() => {
  271. this.startStreamAnswer(this.question);
  272. }, 1000 * this.retryCount);
  273. },
  274. completeAnswer() {
  275. this.isComplete = true;
  276. this.isLoading = false;
  277. },
  278. stopStreamAnswer() {
  279. if (this.timer) {
  280. clearTimeout(this.timer);
  281. this.timer = null;
  282. }
  283. this.isLoading = false;
  284. },
  285. checkTimeout() {
  286. if (Date.now() - this.lastResponseTime > this.timeout) {
  287. this.handleError(new Error('请求超时'));
  288. }
  289. },
  290. goBack() {
  291. uni.navigateBack({
  292. delta: 1
  293. });
  294. },
  295. onChatScroll(e) {
  296. const threshold = 600; // 离底部100px以内不显示按钮
  297. const {
  298. scrollHeight,
  299. scrollTop
  300. } = e.detail;
  301. const clientHeight = e.detail.clientHeight || e.detail.height || 0;
  302. if (scrollHeight - scrollTop - clientHeight > threshold) {
  303. this.showToBottomBtn = true;
  304. } else {
  305. this.showToBottomBtn = false;
  306. }
  307. },
  308. onTextareaInput(e) {
  309. console.log(e.detail);
  310. // 获取textarea的实际高度
  311. const query = uni.createSelectorQuery().in(this);
  312. query.select('.input-box').boundingClientRect(data => {
  313. if (data) {
  314. // 将px转换为rpx (假设设计稿是750rpx宽度)
  315. const height = (data.height * 750) / uni.getSystemInfoSync().windowWidth;
  316. // 减去基础高度90rpx,得到额外增加的高度
  317. this.textareaHeight = Math.max(0, height - 90);
  318. // 滚动到底部
  319. this.scrollToBottom();
  320. }
  321. }).exec();
  322. },
  323. retrieveHistoricalRecords() {
  324. uni.request({
  325. url: this.$apiHost + '/Work/streamAnswerLast',
  326. method: 'GET',
  327. header: {
  328. 'content-type': 'application/json',
  329. 'sign': getApp().globalData.headerSign
  330. },
  331. data: {
  332. uuid: getApp().globalData.uuid,
  333. task_type: 2
  334. },
  335. success: (res) => {
  336. console.log("获取历史记录:", res.data.list);
  337. if (res.data.success === "yes" && res.data.list) {
  338. this.messages = res.data.list
  339. if (res && res.data && res.data.list && res.data.list.length > 0) {
  340. this.showToBottomBtn = true
  341. }
  342. } else {
  343. this.messages = []
  344. }
  345. },
  346. fail: (err) => {
  347. console.log('获取历史记录失败', err);
  348. uni.showToast({
  349. title: '获取历史记录失败',
  350. icon: 'none'
  351. });
  352. }
  353. })
  354. },
  355. // 重新计算元素高度
  356. recalculateHeights() {
  357. // 重新计算textarea高度
  358. const query = uni.createSelectorQuery().in(this);
  359. query.select('.input-box').boundingClientRect(data => {
  360. if (data) {
  361. const height = (data.height * 750) / uni.getSystemInfoSync().windowWidth;
  362. this.textareaHeight = Math.max(0, height - 90);
  363. }
  364. }).exec();
  365. },
  366. countdownFun(n) {
  367. if (this.timer) {
  368. clearInterval(this.timer);
  369. }
  370. this.countdown = n;
  371. // 倒计时
  372. this.timer = setInterval(() => {
  373. this.countdown--;
  374. if (this.countdown <= 0) {
  375. clearInterval(this.timer);
  376. }
  377. }, 1000);
  378. },
  379. goPage(page) {
  380. uni.navigateTo({
  381. url: page,
  382. });
  383. },
  384. newChar() {
  385. this.$refs["DialogBox"]
  386. .confirm({
  387. title: "是否创建新对话",
  388. content: "立即结束当前对话内容,开启新的对话?",
  389. DialogType: "inquiry",
  390. btn1: "取消",
  391. btn2: "确定",
  392. animation: 0,
  393. })
  394. .then(() => {
  395. websocket.send('clear');
  396. this.retrieveHistoricalRecords()
  397. });
  398. },
  399. switchToNormal() {
  400. this.$refs["DialogBox"]
  401. .confirm({
  402. title: "是否切回常规模式",
  403. content: "切换至普通常规模式进行创作?",
  404. DialogType: "inquiry",
  405. btn1: "取消",
  406. btn2: "确定",
  407. animation: 0,
  408. })
  409. .then(() => {
  410. this.goPage('/pages/makedetail/makeImgDetail')
  411. });
  412. }
  413. },
  414. async created() {
  415. await this.initWebSocket();
  416. this.retrieveHistoricalRecords();
  417. this.timer = setInterval(() => {
  418. if (this.isLoading) {
  419. this.checkTimeout();
  420. }
  421. }, 1000);
  422. uni.onKeyboardHeightChange(res => {
  423. this.keyboardHeight = res.height;
  424. if (res.height === 0) {
  425. this.$refs.cLottieRef.call('stop')
  426. } else {
  427. this.$refs.cLottieRef.call('play')
  428. }
  429. this.$nextTick(() => {
  430. this.recalculateHeights();
  431. this.scrollToBottom();
  432. });
  433. });
  434. const systemInfo = uni.getSystemInfoSync();
  435. this.statusBarHeight = systemInfo.statusBarHeight;
  436. this.windowBottom = systemInfo.safeAreaInsets ? systemInfo.safeAreaInsets.bottom : 0;
  437. },
  438. beforeDestroy() {
  439. websocket.close();
  440. this.stopStreamAnswer();
  441. }
  442. }
  443. </script>
  444. <style lang="scss">
  445. @import './intelligentLifeChart.scss';
  446. .to-bottom-btn {
  447. position: fixed;
  448. right: 50%;
  449. transform: translateX(50%);
  450. bottom: 20rpx;
  451. width: 60rpx;
  452. height: 60rpx;
  453. bottom: 220rpx;
  454. z-index: 999;
  455. opacity: .75;
  456. transition: opacity 0.2s;
  457. }
  458. .ai-bubble-row {
  459. display: flex;
  460. align-items: flex-start;
  461. }
  462. .ai-avatar {
  463. width: 60rpx;
  464. height: 60rpx;
  465. border-radius: 50%;
  466. margin-right: 20rpx;
  467. border: solid 2rpx rgba(238, 238, 238, .3);
  468. display: flex;
  469. align-items: flex-end;
  470. justify-content: center;
  471. image {
  472. width: 52rpx;
  473. height: 52rpx;
  474. }
  475. }
  476. .ai-bubble-content {
  477. flex: 1;
  478. }
  479. </style>tyle>