index.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. <template>
  2. <view>
  3. <cu-custom bgColor="bg-cyan" :isBack="$squni.getPrePage() != null">
  4. <block slot="backText">返回</block>
  5. <block slot="content">AirSmartChat</block>
  6. </cu-custom>
  7. <view class="cu-chat">
  8. <block v-for="(x,i) in msgList" :key="i">
  9. <!-- 用户消息 -->
  10. <view v-if="x.my && x.type === 'msg'" class="cu-item self" :class="[i === 0 ? 'first' : '', i === 1 ? 'sec' : '']">
  11. <view class="main">
  12. <view class="content bg-cyan shadow"><!-- @click="x.msg && $squni.copy(x.msg)" -->
  13. <text>{{ x.msg }}</text>
  14. </view>
  15. </view>
  16. <image class="cu-avatar round" src="/static/logo-100.png">
  17. <view v-if="i === 0" class="date">{{ x.date }}</view>
  18. </view>
  19. <!-- AI消息 -->
  20. <view v-if="!x.my && x.type === 'msg'" class="cu-item" :class="[i === 0 ? 'first' : '', i === 1 ? 'sec' : '']">
  21. <view class="flex flex-direction align-center">
  22. <image class="cu-avatar round chat-avatar" src="/static/robot.png">
  23. <text v-if="i === 0" class="cuIcon-title" :class="[statusColor]"></text>
  24. </view>
  25. <view class="main">
  26. <view class="content shadow"><!-- @click="x.msg && $squni.copy(x.msg)" -->
  27. <text>{{ x.msg }}</text>
  28. </view>
  29. </view>
  30. <view v-if="i === 0" class="date">{{ x.date }}</view>
  31. </view>
  32. <view v-if="x.type === 'error'" class="cu-info">
  33. <text class="cuIcon-roundclosefill text-red "></text> {{ x.msg }}
  34. </view>
  35. </block>
  36. <view v-if="msgLoading" class="cu-item">
  37. <view class="flex flex-direction align-center">
  38. <image class="cu-avatar round chat-avatar" src="/static/robot.png">
  39. </view>
  40. <view class="main">
  41. <text class="cuIcon-loading2 cuIconfont-spin text-cyan"></text>
  42. </view>
  43. </view>
  44. </view>
  45. <view class="cu-bar foot input" :style="[{bottom:inputBottom+'px'}]">
  46. <view class="tip-box">
  47. <button class="cu-btn round shadow sm cuIcon line-cyan" @click="startNewChat">
  48. <text class="cuIcon-paint"></text>
  49. </button>
  50. <button class="cu-btn round shadow sm line-cyan" @click="$squni.navigateTo('/pages/main/history')">历史消息</button>
  51. <button class="cu-btn round shadow sm bg-orange" @click="$squni.navigateTo('/pages/main/prompt/prompt')">提示词</button>
  52. <button class="cu-btn round shadow sm line-cyan" @click="openBottomFunc">我的信息</button>
  53. </view>
  54. <!-- <view class="action func" @click="openBottomFunc">
  55. <text class="cuIcon-list text-cyan" style="font-size: 60upx;"></text>
  56. </view> -->
  57. <input v-model="msg" class="solid padding-lr" :adjust-position="false" :focus="false" maxlength="5000"
  58. cursor-spacing="10" :placeholder="loading ? '小AirSmart正在思考中,请稍后~' : '你可以问我任何问题'"
  59. @focus="inputFocus" @blur="inputBlur" @confirm="sendMsg"></input>
  60. <!-- <view class="action">
  61. <text class="cuIcon-emojifill text-grey"></text>
  62. </view> -->
  63. <button class="cu-btn bg-cyan shadow" :disabled="loading" @click="sendMsg">
  64. <text class="cuIcon-loading2 cuIconfont-spin" v-if="loading || !ready"></text>{{ !ready ? '连接中' : '发送' }}
  65. </button>
  66. </view>
  67. <bottom-func v-if="bottomFuncShow" ref="bottomFunc" :chatAsset="chatAsset" @rewarded-video-ad="() => chatAsset.dfn += 2"></bottom-func>
  68. </view>
  69. </template>
  70. <script>
  71. import {
  72. dateFormat, interval
  73. } from '@/util/squ.js'
  74. import {
  75. scrollToBottom
  76. } from '@/util/squni.js'
  77. import websocket from '@/util/websocket'
  78. import {
  79. sendMsgApi, getUserChatAssetApi, startNewChatApi, findPromptListApi
  80. } from '@/api/chat.js'
  81. import BottomFunc from './bottom-func'
  82. const HELLO_MSG = {
  83. type: 'msg',
  84. my: false,
  85. msg: '连接中,请稍后~',
  86. date: dateFormat(new Date(), 'yyyy年MM月dd日 hh:mm')
  87. }
  88. export default {
  89. components: { BottomFunc },
  90. data() {
  91. return {
  92. loading: false,
  93. userId: null,
  94. msgList: [HELLO_MSG],
  95. msgContent: "",
  96. msg: "",
  97. inputBottom: 0,
  98. bottomFuncShow: false,
  99. chatAsset: {},
  100. assetType: 'n',
  101. statusColor: 'text-red',
  102. statusTimer: null,
  103. msgLoading: false,
  104. promptId: null,
  105. curPrompt: {}
  106. }
  107. },
  108. computed: {
  109. ready () {
  110. return this.statusColor === 'text-green'
  111. }
  112. },
  113. watch: {
  114. loading(n, o) {
  115. if (n !== o && !n) {
  116. let last = this.msgList[this.msgList.length - 1]
  117. if (!last.my) {
  118. this.addHistory(last)
  119. }
  120. }
  121. },
  122. statusColor(n, o) {
  123. if (n === 'text-green') {
  124. let prompt = ''
  125. if (this.curPrompt && this.curPrompt.title) {
  126. prompt = `(提示词:${this.curPrompt.title})`
  127. }
  128. HELLO_MSG.msg = '你好,我是AirSmartChat机器人,可以帮你解答疑惑或提供灵感' + prompt
  129. } else {
  130. HELLO_MSG.msg = '连接中,请稍后~'
  131. }
  132. }
  133. },
  134. async onShow() {
  135. await this.$ready
  136. this.userId = this.$store.getters.userId
  137. if(!this.userId) {
  138. this.$squni.toast('请先进行登录哦')
  139. return
  140. }
  141. this.promptId = this.$squni.getCurQuery('promptId')
  142. if(this.promptId) {
  143. findPromptListApi({ id: this.promptId }).then(res => {
  144. if (res.status === 'success') {
  145. this.curPrompt = res.data
  146. if(this.ready && HELLO_MSG.msg.indexOf('提示词') < 0) {
  147. let prompt = ''
  148. if (this.curPrompt && this.curPrompt.title) {
  149. prompt = `(提示词:${this.curPrompt.title})`
  150. }
  151. HELLO_MSG.msg += prompt
  152. }
  153. }
  154. })
  155. }
  156. getUserChatAssetApi().then(res => {
  157. if (res.status === 'success') {
  158. this.chatAsset = res.data
  159. }
  160. })
  161. this.heartStatus()
  162. try {
  163. //建立socket连接
  164. websocket.connectSocket(this.$config.wssUrl + '/tools/chat/user/' + this.userId, msg => {
  165. this.recvMsg(msg)
  166. }, () => {
  167. //如果连接成功则发送心跳检测
  168. this.heartBeatTest()
  169. })
  170. } catch (error) {
  171. console.log('websocket connectSocket error:' + error)
  172. }
  173. },
  174. onHide() {
  175. this.closeSocket()
  176. },
  177. methods: {
  178. logout() {
  179. this.loginLoading = true
  180. doLoginApi('H5', {
  181. username: this.email || this.phone|| this.username,
  182. password: this.password
  183. }).then(res => {
  184. this.loginLoading = false
  185. if (res === LoginSuccess) {
  186. uni.showToast({ title: '登录成功' })
  187. // 跳转到主页发现已经登录,会自动重新获取用户信息,此处无需获取
  188. window.location.href = getUrlQuery('_originHref')
  189. } else {
  190. uni.showToast({ title: (res && res.data && res.data.message) || '登录失败', icon: 'none' })
  191. this.createCode(4)
  192. }
  193. })
  194. },
  195. sendMsg() {
  196. if (this.msg == "") {
  197. this.$squni.toast('请先输入您的问题哦')
  198. return
  199. }
  200. let msg = this.msg
  201. this.putMsg(this.msg, true)
  202. this.msgLoading = true
  203. this.loading = true
  204. // ======== 开发环境模拟回复 ========
  205. //return this.mockReply()
  206. // ======== 开发环境模拟回复 ========
  207. if(this.calcAsset() === false) {
  208. this.loading = false
  209. return
  210. }
  211. // 发送消息: M1/M2
  212. websocket.sendMessage(JSON.stringify({
  213. model: 'M1',
  214. msg: msg,
  215. platform: this.$squni.getStorageSync('platform'),
  216. openid: this.$squni.getStorageSync('openid'),
  217. promptId: this.promptId
  218. }), null, () => {
  219. this.putMsgError('机器人被拔网线了,请稍后再试~')
  220. })
  221. },
  222. recvMsg(msg) {
  223. this.msgLoading = false
  224. if(!msg) {
  225. this.putMsgError('机器人开小差了,请稍后再试~')
  226. return
  227. }
  228. // 发送消息
  229. // 1+1
  230. // 收到消息
  231. // {"role":"assistant","content":null}
  232. // {"role":null,"content":"2"}
  233. // {"role":null,"content":null}
  234. // [DONE]
  235. if (msg === '[DONE]') {
  236. this.loading = false
  237. } else {
  238. try {
  239. let msgJson = JSON.parse(msg)
  240. if (msgJson.role === 'sqchat') {
  241. let content = msgJson.content
  242. if (msgJson.codeKey) {
  243. content += `[${msgJson.codeKey}]`
  244. if(msgJson.codeKey === 'chat.asset_short') {
  245. this.openBottomFunc()
  246. } else if(msgJson.codeKey.indexOf('chat.asset_') >= 0) {
  247. this.chatAsset[this.assetType]++
  248. }
  249. }
  250. this.putMsgError(content)
  251. } if (msgJson.role === 'assistant') {
  252. this.putMsg('', false)
  253. } else if (msgJson.role == null && msgJson.content) {
  254. this.msgList[this.msgList.length - 1].msg += msgJson.content
  255. scrollToBottom()
  256. }
  257. } catch(error) {
  258. this.putMsgError(msg)
  259. }
  260. }
  261. },
  262. startNewChat() {
  263. HELLO_MSG.date = dateFormat(new Date(), 'yyyy年MM月dd日 hh:mm')
  264. this.msgList = [HELLO_MSG]
  265. startNewChatApi()
  266. },
  267. sendMsgBak() {
  268. let that = this
  269. if (this.msg == "") {
  270. return
  271. }
  272. this.msgContent += (this.userId + ":" + this.msg + "\n")
  273. this.putMsg(this.msg, true)
  274. this.loading = true
  275. // ======== 开发环境模拟回复 ========
  276. return this.mockReply()
  277. // ======== 开发环境模拟回复 ========
  278. sendMsgApi({
  279. userId: this.userId + '',
  280. question: this.msgContent
  281. }).then(({
  282. status, data
  283. }) => {
  284. if (status === 'success') {
  285. this.putMsg(data.ack, false)
  286. this.msgContent += ("openai:" + this.msg + "\n")
  287. } else {
  288. this.putMsg(res.message || '机器人开小差了,请稍后再试~', false, 'error')
  289. }
  290. that.loading = false
  291. })
  292. },
  293. calcAsset() {
  294. if (this.chatAsset.dfn > 0) {
  295. this.chatAsset.dfn--
  296. this.assetType = 'dfn'
  297. } else if (this.chatAsset.n > 0) {
  298. this.chatAsset.n--
  299. this.assetType = 'n'
  300. } else {
  301. this.$squni.toast('剩余次数不足')
  302. this.openBottomFunc()
  303. return false
  304. }
  305. },
  306. putMsg (msg, my = false, type = 'msg') {
  307. let item = {
  308. type: type,
  309. msg: msg,
  310. my: my,
  311. date: dateFormat(new Date(), 'yyyy年MM月dd日 hh:mm')
  312. }
  313. this.msgList.push(item)
  314. scrollToBottom()
  315. if (my) {
  316. this.addHistory(item)
  317. // 清除消息
  318. this.msg = ''
  319. this.msgReply = ''
  320. }
  321. },
  322. putMsgError(msg) {
  323. this.putMsg(msg, false, 'error')
  324. this.msgLoading = false
  325. this.loading = false
  326. },
  327. addHistory(item) {
  328. if (item.type === 'msg') {
  329. let chatHistory = this.$squni.getStorageSync('chatHistory')
  330. if(!chatHistory) {
  331. chatHistory = []
  332. }
  333. if(chatHistory.length >= 50) {
  334. chatHistory.splice(0, 1)
  335. }
  336. chatHistory.push(item)
  337. this.$squni.setStorageSync('chatHistory', chatHistory)
  338. }
  339. },
  340. //心跳检测
  341. heartBeatTest() {
  342. let globalTimer = null
  343. //清除定时器
  344. clearInterval(globalTimer)
  345. //开启定时器定时检测心跳
  346. globalTimer = setInterval(() => {
  347. //发送消息给服务端
  348. websocket.sendMessage('PING', null, () => {
  349. //如果失败则清除定时器
  350. clearInterval(globalTimer)
  351. })
  352. }, 10000)
  353. },
  354. heartStatus() {
  355. this.statusTimer = interval(() => {
  356. if (websocket.isOpen) {
  357. this.statusColor = 'text-green'
  358. } else if(this.statusColor === 'text-red') {
  359. this.statusColor = 'text-yellow'
  360. } else {
  361. this.statusColor = 'text-red'
  362. }
  363. }, this.statusTimer, 200)
  364. },
  365. closeSocket() {
  366. websocket.closeSocket()
  367. clearInterval(this.statusTimer)
  368. this.statusColor = 'text-red'
  369. },
  370. inputFocus(e) {
  371. this.inputBottom = e.detail.height
  372. },
  373. inputBlur(e) {
  374. this.inputBottom = 0
  375. },
  376. openBottomFunc() {
  377. this.bottomFuncShow = true
  378. this.$nextTick(() => {
  379. this.$refs.bottomFunc.open()
  380. })
  381. },
  382. mockReply() {
  383. // 开发环境模拟回复
  384. if (process.env.NODE_ENV === 'development') {
  385. setTimeout(() => {
  386. this.putMsg('这是模拟返回消息: ' + new Date(), false)
  387. this.loading = false
  388. }, 1000)
  389. return
  390. }
  391. }
  392. }
  393. }
  394. </script>
  395. <style>
  396. page {
  397. padding-bottom: 220upx;
  398. }
  399. .cu-chat .chat-avatar.cu-avatar {
  400. width: 82upx;
  401. height: 82upx;
  402. }
  403. .cu-item:not(.first) {
  404. padding-bottom: 0upx;
  405. }
  406. .cu-item.sec {
  407. padding-top: 0upx;
  408. }
  409. .cu-chat .cu-item>.main {
  410. max-width: calc(100% - 160upx);
  411. }
  412. .main .content {
  413. word-wrap: break-word;
  414. cursor: text;
  415. user-select: text;
  416. }
  417. .cu-bar.foot {
  418. box-shadow: 0 -0.5px 1px rgba(0, 0, 0, 0.1);
  419. }
  420. .foot {
  421. padding-top: 20upx;
  422. padding-bottom: 60upx;
  423. }
  424. .foot .cu-btn {
  425. margin-right: 20upx;
  426. }
  427. .foot .action.func {
  428. margin-left: 30upx;
  429. }
  430. .foot .tip-box {
  431. position: absolute;
  432. top: -60upx;
  433. margin: 0 30upx;
  434. }
  435. </style>