intelligentLifeChart.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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({ role: 'user', content });
  219. try {
  220. this.isLoading = true;
  221. let aiMsg = {
  222. role: 'ai',
  223. content: '',
  224. isStartGenerating: false,
  225. startGeneratingId: 0
  226. };
  227. this.messages.push(aiMsg);
  228. this.lastAiIndex = this.messages.length - 1;
  229. // 发送消息
  230. websocket.send(content);
  231. } catch (error) {
  232. console.error('发送消息失败:', error);
  233. this.handleError(error);
  234. }
  235. },
  236. onSend() {
  237. if (!this.question.trim() || this.isLoading) return;
  238. this.startStreamAnswer(this.question);
  239. this.question = '';
  240. },
  241. resetState() {
  242. this.answer = '';
  243. this.displayText = '';
  244. this.isComplete = false;
  245. this.error = null;
  246. this.retryCount = 0;
  247. this.lastResponseTime = Date.now();
  248. },
  249. handleError(error) {
  250. if (this.retryCount < this.maxRetries) {
  251. this.retryCount++;
  252. this.retryRequest();
  253. } else {
  254. this.error = '请求失败,请稍后重试';
  255. this.isLoading = false;
  256. uni.showToast({
  257. title: this.error,
  258. icon: 'none'
  259. });
  260. }
  261. },
  262. retryRequest() {
  263. uni.showToast({
  264. title: `正在重试 (${this.retryCount}/${this.maxRetries})`,
  265. icon: 'none'
  266. });
  267. setTimeout(() => {
  268. this.startStreamAnswer(this.question);
  269. }, 1000 * this.retryCount);
  270. },
  271. completeAnswer() {
  272. this.isComplete = true;
  273. this.isLoading = false;
  274. },
  275. stopStreamAnswer() {
  276. if (this.timer) {
  277. clearTimeout(this.timer);
  278. this.timer = null;
  279. }
  280. this.isLoading = false;
  281. },
  282. checkTimeout() {
  283. if (Date.now() - this.lastResponseTime > this.timeout) {
  284. this.handleError(new Error('请求超时'));
  285. }
  286. },
  287. goBack() {
  288. uni.navigateBack({
  289. delta: 1
  290. });
  291. },
  292. onChatScroll(e) {
  293. const threshold = 600; // 离底部100px以内不显示按钮
  294. const {
  295. scrollHeight,
  296. scrollTop
  297. } = e.detail;
  298. const clientHeight = e.detail.clientHeight || e.detail.height || 0;
  299. if (scrollHeight - scrollTop - clientHeight > threshold) {
  300. this.showToBottomBtn = true;
  301. } else {
  302. this.showToBottomBtn = false;
  303. }
  304. },
  305. onTextareaInput(e) {
  306. console.log(e.detail);
  307. // 获取textarea的实际高度
  308. const query = uni.createSelectorQuery().in(this);
  309. query.select('.input-box').boundingClientRect(data => {
  310. if (data) {
  311. // 将px转换为rpx (假设设计稿是750rpx宽度)
  312. const height = (data.height * 750) / uni.getSystemInfoSync().windowWidth;
  313. // 减去基础高度90rpx,得到额外增加的高度
  314. this.textareaHeight = Math.max(0, height - 90);
  315. // 滚动到底部
  316. this.scrollToBottom();
  317. }
  318. }).exec();
  319. },
  320. retrieveHistoricalRecords() {
  321. uni.request({
  322. url: this.$apiHost + '/Work/streamAnswerLast',
  323. method: 'GET',
  324. header: {
  325. 'content-type': 'application/json',
  326. 'sign': getApp().globalData.headerSign
  327. },
  328. data: {
  329. uuid: getApp().globalData.uuid,
  330. task_type: 2
  331. },
  332. success: (res) => {
  333. console.log("获取历史记录:", res.data.list);
  334. if (res.data.success === "yes" && res.data.list) {
  335. this.messages = res.data.list
  336. if (res && res.data && res.data.list && res.data.list.length > 0) {
  337. this.showToBottomBtn = true
  338. }
  339. } else {
  340. this.messages = []
  341. }
  342. },
  343. fail: (err) => {
  344. console.log('获取历史记录失败', err);
  345. uni.showToast({
  346. title: '获取历史记录失败',
  347. icon: 'none'
  348. });
  349. }
  350. })
  351. },
  352. // 重新计算元素高度
  353. recalculateHeights() {
  354. // 重新计算textarea高度
  355. const query = uni.createSelectorQuery().in(this);
  356. query.select('.input-box').boundingClientRect(data => {
  357. if (data) {
  358. const height = (data.height * 750) / uni.getSystemInfoSync().windowWidth;
  359. this.textareaHeight = Math.max(0, height - 90);
  360. }
  361. }).exec();
  362. },
  363. countdownFun(n) {
  364. if (this.timer) {
  365. clearInterval(this.timer);
  366. }
  367. this.countdown = n;
  368. // 倒计时
  369. this.timer = setInterval(() => {
  370. this.countdown--;
  371. if (this.countdown <= 0) {
  372. clearInterval(this.timer);
  373. }
  374. }, 1000);
  375. },
  376. goPage(page) {
  377. uni.navigateTo({
  378. url: page,
  379. });
  380. },
  381. newChar() {
  382. this.$refs["DialogBox"]
  383. .confirm({
  384. title: "是否创建新对话",
  385. content: "立即结束当前对话内容,开启新的对话?",
  386. DialogType: "inquiry",
  387. btn1: "取消",
  388. btn2: "确定",
  389. animation: 0,
  390. })
  391. .then(() => {
  392. websocket.send('clear');
  393. this.retrieveHistoricalRecords()
  394. });
  395. },
  396. switchToNormal() {
  397. this.$refs["DialogBox"]
  398. .confirm({
  399. title: "是否切回常规模式",
  400. content: "切换至普通常规模式进行创作?",
  401. DialogType: "inquiry",
  402. btn1: "取消",
  403. btn2: "确定",
  404. animation: 0,
  405. })
  406. .then(() => {
  407. this.goPage('/pages/makedetail/makeImgDetail')
  408. });
  409. }
  410. },
  411. async created() {
  412. await this.initWebSocket();
  413. this.retrieveHistoricalRecords();
  414. this.timer = setInterval(() => {
  415. if (this.isLoading) {
  416. this.checkTimeout();
  417. }
  418. }, 1000);
  419. uni.onKeyboardHeightChange(res => {
  420. this.keyboardHeight = res.height;
  421. if (res.height === 0) {
  422. this.$refs.cLottieRef.call('stop')
  423. } else {
  424. this.$refs.cLottieRef.call('play')
  425. }
  426. this.$nextTick(() => {
  427. this.recalculateHeights();
  428. this.scrollToBottom();
  429. });
  430. });
  431. const systemInfo = uni.getSystemInfoSync();
  432. this.statusBarHeight = systemInfo.statusBarHeight;
  433. this.windowBottom = systemInfo.safeAreaInsets ? systemInfo.safeAreaInsets.bottom : 0;
  434. },
  435. beforeDestroy() {
  436. websocket.close();
  437. this.stopStreamAnswer();
  438. }
  439. }
  440. </script>
  441. <style lang="scss">
  442. @import './intelligentLifeChart.scss';
  443. .to-bottom-btn {
  444. position: fixed;
  445. right: 50%;
  446. transform: translateX(50%);
  447. bottom: 20rpx;
  448. width: 60rpx;
  449. height: 60rpx;
  450. bottom: 220rpx;
  451. z-index: 999;
  452. opacity: .75;
  453. transition: opacity 0.2s;
  454. }
  455. .ai-bubble-row {
  456. display: flex;
  457. align-items: flex-start;
  458. }
  459. .ai-avatar {
  460. width: 60rpx;
  461. height: 60rpx;
  462. border-radius: 50%;
  463. margin-right: 20rpx;
  464. border: solid 2rpx rgb(238, 238, 238, .3);
  465. display: flex;
  466. align-items: flex-end;
  467. justify-content: center;
  468. image {
  469. width: 52rpx;
  470. height: 52rpx;
  471. }
  472. }
  473. .ai-bubble-content {
  474. flex: 1;
  475. }
  476. </style>tyle>