index.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <template>
  2. <div class="chat bg-gray-900 comBg">
  3. <Header ref="Header" v-show="false" />
  4. <div class="flex flex-col items-center justify-center h-screen px-4">
  5. <!-- onClick={() => navigate('/')} -->
  6. <div
  7. class="text-white px-3 py-2 rounded-lg mb-4 absolute top-2 left-2"
  8. style="background-color: var(--bg-color1);"
  9. @click="goBack"
  10. >
  11. <!-- <i class="fas fa-chevron-left mr-2"></i> -->
  12. 返回
  13. </div>
  14. <div class="content">
  15. <div class="leftImg">
  16. <img :src="baseApi + info.picture" alt="">
  17. <div class="aiInfo">
  18. <span class="photo">
  19. <img :src="baseApi + info.picture">
  20. </span>
  21. <div class="info">
  22. <div class="name">{{ info.characterName }}</div>
  23. <div class="tags">
  24. <span class="tag" v-for="(item, index) in info.labelArr" :key="index">
  25. {{ item }}
  26. </span>
  27. </div>
  28. <div class="infoContent">{{ info.prologue }}</div>
  29. </div>
  30. </div>
  31. </div>
  32. <div class="chat-box">
  33. <div class="messages" ref="messages">
  34. <template v-for="(item, index) in returnMessage">
  35. <div v-if="item.role == 'assistant'" class="text-white mb-4 flex" :key="index">
  36. <!-- ai返回的信息 -->
  37. <div class="pt-2 photo">
  38. <img
  39. :src="baseApi + info.picture"
  40. class="rounded-full w-14 h-14 object-cover"
  41. />
  42. </div>
  43. <div class="messageRight">
  44. <!-- <div class="yyPlay ml-4"></div> -->
  45. <div class="yyPlayBg mt-1 ml-6 w-16 p-1 cursor-pointer">
  46. <img class="yyPlay" src="@/assets/images/播放/yyPlay.png" alt="">
  47. </div>
  48. <div class="message mt-4 ml-4 p-3 rounded-r-md rounded-bl-md text-xs" >
  49. <div v-show="!item.content" class="loadingMessage" >
  50. <div v-loading="!item.content" element-loading-background="rgba(0, 0, 0, 0.0)"></div>
  51. </div>
  52. <p v-show="item.content">{{ item.content }} </p>
  53. <div class="messageOptions" v-show="returnMessage.length == 1">
  54. <div class="option" v-for="(item, index) in messageOptions" :key="index" @click="messageOptionClick(item.chatGuidance)">
  55. {{ item.chatGuidance }}
  56. </div>
  57. </div>
  58. </div>
  59. </div>
  60. </div>
  61. <!-- 用户发送的信息 -->
  62. <div v-if="item.role == 'user'" class="text-white mb-4 flex me" :key="index">
  63. <div class="pt-2 photo">
  64. <img
  65. src="@/assets/images/default_avatar_user.png"
  66. class="rounded-full w-14 h-14 object-cover"
  67. />
  68. </div>
  69. <div class="messageRight">
  70. <div class="message mr-4 mt-4 p-3 rounded-l-md rounded-br-md text-xs">
  71. <p>{{ item.content }}</p>
  72. </div>
  73. </div>
  74. </div>
  75. </template>
  76. </div>
  77. <div class="absolute left-2 right-2 bottom-4 ">
  78. <!-- <div class="flex items-center text-gray-400 text-xs mb-4 ">
  79. <span>@Leon S Kennedy - Resident Evil</span>
  80. </div> -->
  81. <div class="flex">
  82. <el-button class="buttonBg1 mButton" @click="newStart" style="margin-right: 5px;" type="primary" round icon="el-icon-plus"></el-button>
  83. <input
  84. type="text"
  85. placeholder="输入消息..."
  86. class="flex-1 py-2 px-4 rounded-l-lg text-sm text-white focus:outline-none"
  87. style="background: #ffffff0f; border: 1px solid #5b5b5e;"
  88. v-model="content"
  89. @keydown="Enterkey"
  90. />
  91. <button @click="getStreamChatWithWeb" class="buttonBg1 text-white px-4 rounded-r-lg text-sm">
  92. 发送
  93. </button>
  94. </div>
  95. </div>
  96. </div>
  97. </div>
  98. </div>
  99. </div>
  100. </template>
  101. <script>
  102. import Header from "@/views/homeComponents/Header.vue"
  103. import { streamChatWithWebApi, getGuidanceApi } from "@/api/chat.js"
  104. import { detailApi } from "@/api/detail.js"
  105. import { Message, MessageBox, Notification, Loading } from 'element-ui'
  106. export default {
  107. components: {
  108. Header
  109. },
  110. data() {
  111. return {
  112. messageOptions: [],
  113. info: {},
  114. messageLoading: false,
  115. returnMessage: [],
  116. content: ''
  117. }
  118. },
  119. mounted() {
  120. console.log(this.$refs.Header, 'this.$refs.Header');
  121. if (this.$route.query.characterId) {
  122. this.getDetail(this.$route.query.characterId)
  123. }
  124. },
  125. watch: {
  126. returnMessage: {
  127. handler(newVal, lodVal) {
  128. this.$nextTick(() => {
  129. let messages = this.$refs.messages
  130. messages.scrollTop = messages.scrollHeight
  131. })
  132. },
  133. deep: true
  134. }
  135. },
  136. methods: {
  137. getDetail(id) {
  138. detailApi(id).then(res => {
  139. console.log(res, '角色详情');
  140. this.info = res.data
  141. let HistoryMessage = JSON.parse(localStorage.getItem(`[userId:${123},aiId:${this.info.id}]`));
  142. if (HistoryMessage) {
  143. this.returnMessage = HistoryMessage
  144. } else {
  145. this.returnMessage.push({
  146. role: 'assistant',
  147. content: this.info.firstContent
  148. })
  149. localStorage.setItem(`[userId:${123},aiId:${this.info.id}]`, JSON.stringify(this.returnMessage));
  150. }
  151. this.getGuidance(id)
  152. })
  153. },
  154. getGuidance(id) {
  155. getGuidanceApi(id).then(res => {
  156. console.log(res, '聊天引导');
  157. this.messageOptions = res.data
  158. })
  159. },
  160. goBack() {
  161. this.$router.back()
  162. },
  163. newStart() {
  164. // 清空历史数据
  165. localStorage.removeItem(`[userId:${123},aiId:${this.info.id}]`);
  166. this.returnMessage = []
  167. this.getDetail(this.info.id)
  168. },
  169. Enterkey(e) {
  170. if (e.keyCode == 13) {
  171. this.getStreamChatWithWeb()
  172. }
  173. },
  174. async getStreamChatWithWeb_old() {
  175. this.messageLoading = true
  176. if (!this.content) {
  177. return
  178. }
  179. this.returnMessage.push({
  180. role: 'user',
  181. content: this.content
  182. })
  183. let HistoryMessage = JSON.parse(localStorage.getItem(`[userId:${123},aiId:${this.info.id}]`));
  184. // 历史记录取最新的20条传给后端
  185. if (HistoryMessage && HistoryMessage.length > 20) {
  186. HistoryMessage = HistoryMessage.slice(HistoryMessage.length - 1, 20)
  187. }
  188. let params = {
  189. historyMessage: HistoryMessage || [],
  190. characterId: this.info.id,
  191. prompt: JSON.parse(JSON.stringify(this.content))
  192. }
  193. // 清空输入框的值
  194. this.content = ''
  195. // 新增一条ai信息
  196. this.returnMessage.push({
  197. role: 'assistant',
  198. content: ''
  199. })
  200. let res = await streamChatWithWebApi(params)
  201. console.log(res.data.message.content, 'res');
  202. let content = res.data.message.content
  203. let index = 0
  204. let xing = 1
  205. let messageInterval = setInterval(() => {
  206. if (index > content.length - 1) {
  207. console.log('结束');
  208. // 消息全部显示后存到历史localStorage
  209. let HistoryMessage = []
  210. // 历史只存100条,长度超出截取最新的
  211. if (this.returnMessage.length > 100) {
  212. HistoryMessage = JSON.stringify(this.returnMessage.slice(this.returnMessage.length - 100, 100))
  213. } else {
  214. HistoryMessage = JSON.stringify(this.returnMessage)
  215. }
  216. localStorage.setItem(`[userId:${123},aiId:${this.info.id}]`, HistoryMessage);
  217. clearInterval(messageInterval)
  218. return
  219. }
  220. console.log(content[index], 'content[index]');
  221. if (content[index] == "*") {
  222. if (xing == 1) {
  223. xing = 2
  224. this.returnMessage[this.returnMessage.length - 1].content += "("
  225. } else if (xing == 2) {
  226. xing = 1
  227. this.returnMessage[this.returnMessage.length - 1].content += ")"
  228. }
  229. } else {
  230. this.returnMessage[this.returnMessage.length - 1].content += content[index]
  231. }
  232. index += 1
  233. }, 50)
  234. },
  235. async getStreamChatWithWeb() {
  236. this.messageLoading = true
  237. if (!this.content) {
  238. return
  239. }
  240. this.returnMessage.push({
  241. role: 'user',
  242. content: this.content
  243. })
  244. let HistoryMessage = JSON.parse(localStorage.getItem(`[userId:${123},aiId:${this.info.id}]`));
  245. // 历史记录取最新的20条传给后端
  246. if (HistoryMessage && HistoryMessage.length > 20) {
  247. HistoryMessage = HistoryMessage.slice(HistoryMessage.length - 1, 20)
  248. }
  249. let params = {
  250. historyMessage: HistoryMessage || [],
  251. characterId: this.info.id,
  252. prompt: this.content
  253. }
  254. // 新增一条ai信息
  255. this.returnMessage.push({
  256. role: 'assistant',
  257. content: ''
  258. })
  259. // 清空输入框的值
  260. this.content = ''
  261. let res = await streamChatWithWebApi(params)
  262. console.log(res, 'res');
  263. this.messageLoading = false
  264. if (res.status != 200) {
  265. this.$message.error(res.statusText)
  266. this.returnMessage.splice(this.returnMessage.length - 1, 1)
  267. return
  268. }
  269. const reader = res.body.getReader()
  270. const decoder=new TextDecoder()
  271. while(1){
  272. const {done, value} = await reader.read()
  273. // console.log(done, 'done');
  274. if(done){
  275. console.log(value, 'value');
  276. // if (typeof(value) == "undefined") {
  277. // this.$message.error('错误')
  278. // this.returnMessage.splice(this.returnMessage.length - 1, 1)
  279. // }
  280. console.log('结束');
  281. // 消息全部显示后存到历史localStorage
  282. let HistoryMessage = []
  283. // 历史只存100条,长度超出截取最新的
  284. if (this.returnMessage.length > 100) {
  285. HistoryMessage = JSON.stringify(this.returnMessage.slice(this.returnMessage.length - 100, 100))
  286. } else {
  287. HistoryMessage = JSON.stringify(this.returnMessage)
  288. }
  289. localStorage.setItem(`[userId:${123},aiId:${this.info.id}]`, HistoryMessage);
  290. break;
  291. }
  292. //txt就是一个一个的字 然后添加到页面上就可以了
  293. const txt = decoder.decode(value).split('data:')
  294. // const txt = decoder.decode(value)
  295. this.addMessage(txt)
  296. // let data = JSON.parse(txt).message.content
  297. console.log(txt, 'txt');
  298. // if (this.isJSON(txt) && JSON.parse(txt).code != 200) {
  299. // let data = JSON.parse(txt)
  300. // this.$message.error(data.msg)
  301. // this.returnMessage.splice(this.returnMessage.length - 1, 1)
  302. // break;
  303. // }
  304. }
  305. },
  306. addMessage(value) {
  307. // console.log(value, 'value');
  308. for (let i = 0; i < value.length; i++) {
  309. const element = value[i];
  310. if (this.isJSON(element)) {
  311. if(JSON.parse(element).code == 401) {
  312. this.returnMessage.splice(this.returnMessage.length - 1, 1)
  313. this.noLogin(element)
  314. break;
  315. }
  316. if(JSON.parse(element).code == 500) {
  317. this.returnMessage.splice(this.returnMessage.length - 1, 1)
  318. this.$message.error('系统错误请联系管理员')
  319. break;
  320. }
  321. let txt = JSON.parse(element).content
  322. this.returnMessage[this.returnMessage.length - 1].content += txt
  323. }
  324. }
  325. },
  326. noLogin(value) {
  327. let _this = this
  328. MessageBox.confirm(
  329. value.content,
  330. "系统提示",
  331. {
  332. confirmButtonText: "前往登录",
  333. cancelButtonText: "取消",
  334. type: "warning",
  335. }
  336. )
  337. .then(() => {
  338. // isRelogin.show = false;
  339. this.$store.dispatch("LogOut").then(() => {
  340. // location.href = "/";
  341. _this.$refs.Header.showLogin()
  342. });
  343. })
  344. .catch(() => {
  345. // isRelogin.show = false;
  346. });
  347. },
  348. isJSON(str) {
  349. if (typeof str == 'string') {
  350. try {
  351. JSON.parse(str);
  352. return true;
  353. } catch(e) {
  354. // console.log(e);
  355. return false;
  356. }
  357. }
  358. },
  359. messageOptionClick(value) {
  360. this.content = value
  361. this.getStreamChatWithWeb()
  362. },
  363. }
  364. }
  365. </script>
  366. <style lang="scss" scoped>
  367. .chat {
  368. min-height: 100vh;
  369. }
  370. .content {
  371. margin-top: 30px;
  372. background-size: 100% 100%;
  373. display: flex;
  374. height: 90vh;
  375. justify-content: center;
  376. width: 100vw;
  377. >.leftImg {
  378. border-radius: 16px 16px 16px 16px;
  379. height: 95%;
  380. position: relative;
  381. width: 380px;
  382. >img {
  383. border: 6px solid;
  384. border-image: linear-gradient(180deg, #b48733, #e8cf97, #b48733) 6 6;
  385. height: 99%;
  386. margin-right: 5px;
  387. object-fit: cover;
  388. }
  389. >.aiInfo {
  390. background-color: #ffffff1a;
  391. border-radius: 24px 24px 24px 24px;
  392. bottom: -70px;
  393. display: flex;
  394. height: 193px;
  395. justify-content: center;
  396. left: 50%;
  397. position: absolute;
  398. transform: translate(-50%, -50%);
  399. width: 100%;
  400. >.photo {
  401. width: 64px;
  402. height: 64px;
  403. font-size: 18px;
  404. position: absolute;
  405. top: -20px;
  406. box-sizing: border-box;
  407. margin: 0;
  408. padding: 0;
  409. color: #fff;
  410. line-height: 1.5714285714285714;
  411. list-style: none;
  412. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
  413. display: inline-flex;
  414. justify-content: center;
  415. align-items: center;
  416. overflow: hidden;
  417. white-space: nowrap;
  418. text-align: center;
  419. vertical-align: middle;
  420. background: rgba(0, 0, 0, 0.25);
  421. border: 1px solid transparent;
  422. border-radius: 50%;
  423. }
  424. >.info {
  425. padding-top: 50px;
  426. width: 80%;
  427. >.name {
  428. color: #fff;
  429. font-size: 22px;
  430. font-style: normal;
  431. font-weight: 700;
  432. line-height: 31px;
  433. text-align: center;
  434. text-transform: none;
  435. }
  436. >.tags {
  437. padding-bottom: 8px;
  438. text-align: center;
  439. >.tag {
  440. margin-right: 4px;
  441. background: #ffffff1a;
  442. border-radius: 4px 4px 4px 4px;
  443. color: #fff;
  444. font-size: 12px;
  445. font-weight: 500;
  446. line-height: 17px;
  447. border-color: transparent;
  448. }
  449. }
  450. >.infoContent {
  451. color: #fff;
  452. font-size: 16px;
  453. font-style: normal;
  454. font-weight: 500;
  455. height: 80px;
  456. line-height: 22px;
  457. overflow-y: auto;
  458. text-align: center;
  459. text-transform: none;
  460. }
  461. }
  462. }
  463. }
  464. >.chat-box {
  465. margin-left: 5px;
  466. position: relative;
  467. background-color: #ffffff1a;
  468. background-position: 50%;
  469. background-repeat: no-repeat;
  470. background-size: auto;
  471. border: 1px solid #635677 !important;
  472. border-radius: 20px;
  473. box-sizing: border-box;
  474. color: #fff !important;
  475. display: flex;
  476. flex-direction: column;
  477. height: 95%;
  478. // margin: 0 auto;
  479. width: 1010px;
  480. padding: 25px;
  481. }
  482. }
  483. .messages {
  484. height: calc(100% - 68px );
  485. overflow-y: auto;
  486. }
  487. .messages::-webkit-scrollbar {
  488. width: 0px;
  489. }
  490. .messageRight {
  491. max-width: calc(100% - 72px);
  492. min-width: 400px;
  493. }
  494. .yyPlayBg {
  495. background: rgba(103, 103, 168, 1);
  496. border-radius: 999px;
  497. position: absolute;
  498. }
  499. .yyPlay {
  500. width: 12px;
  501. height: 12px;
  502. // background: url('../../assets/images/播放/yyPlay.gif') no-repeat;
  503. // background-size: 170% 170%;
  504. // background-position: 50% 50%;
  505. // animation: heart-burst steps(28) 0.9s infinite both;
  506. // animation-play-state: paused;
  507. // height: 50px;
  508. // background: #fff;
  509. }
  510. .message {
  511. background: #ffffff0f;
  512. border: 1px solid #5b5b5e;
  513. // flex: 1;
  514. }
  515. .messageUser {
  516. background: #ffffff0f;
  517. border: 1px solid #5b5b5e;
  518. max-width: calc(100% - 72px);
  519. min-width: 400px;
  520. }
  521. .photo {
  522. width: 56px;
  523. }
  524. .me {
  525. flex-direction: row-reverse;
  526. }
  527. .loadingMessage {
  528. position: relative;
  529. // display: flex;
  530. // justify-content: center;
  531. width: 100%;
  532. height: 100%;
  533. }
  534. .messageOptions {
  535. // margin-top: 20px;
  536. display: flex;
  537. flex-wrap: wrap;
  538. justify-content: space-around;
  539. .option {
  540. background: #ade4ff32;
  541. border: 1px solid #5b5b5e;
  542. border-radius: 10px;
  543. padding: 10px;
  544. width: 40%;
  545. height: 50px;
  546. margin-top: 10px;
  547. cursor: pointer;
  548. }
  549. }
  550. </style>
  551. <style scoped>
  552. .loadingMessage >>> .el-loading-parent--relative {
  553. width: 100%;
  554. height: 100%;
  555. }
  556. .loadingMessage >>> .el-loading-spinner {
  557. display: flex;
  558. justify-content: center;
  559. }
  560. .mButton {
  561. border: solid 0px;
  562. }
  563. </style>