index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. const _app = getApp()
  2. // 办公助手服务配置
  3. const ServiceConfig = {
  4. // 样例API地址,请替换为您的真实服务地址
  5. apiUrl: 'https://kt.colexiu.com/edu-app/open/coze/agent',
  6. // 请求超时时间(毫秒)
  7. timeout: 60000,
  8. // 请求头配置
  9. headers: {
  10. 'Content-Type': 'application/json'
  11. }
  12. }
  13. // 用户信息管理
  14. const UserManager = {
  15. // 获取用户唯一标识
  16. getUserIdentifier: function () {
  17. return new Promise((resolve, _reject) => {
  18. // 尝试从缓存获取用户ID
  19. const cachedUserId = tt.getStorageSync('user_id')
  20. if (cachedUserId) {
  21. resolve(cachedUserId)
  22. return
  23. }
  24. // 调用登录API获取用户标识
  25. tt.login({
  26. force: false, // 不强制调起登录框
  27. success: function (res) {
  28. console.log('登录成功:', res)
  29. if (res.isLogin && res.code) {
  30. // 已登录用户,使用code作为临时标识
  31. // 实际应用中,应该将code发送到服务端换取openid
  32. const userId = 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
  33. // 缓存用户ID
  34. tt.setStorageSync('user_id', userId)
  35. resolve(userId)
  36. } else if (res.anonymousCode) {
  37. // 匿名用户,使用anonymousCode作为标识
  38. const anonymousUserId = 'anonymous_' + res.anonymousCode.substr(0, 16)
  39. // 缓存匿名用户ID
  40. tt.setStorageSync('user_id', anonymousUserId)
  41. resolve(anonymousUserId)
  42. } else {
  43. // 生成默认用户ID
  44. const defaultUserId = 'default_' + Date.now()
  45. tt.setStorageSync('user_id', defaultUserId)
  46. resolve(defaultUserId)
  47. }
  48. },
  49. fail: function (err) {
  50. console.error('登录失败:', err)
  51. // 生成默认用户ID作为备选
  52. const defaultUserId = 'default_' + Date.now()
  53. tt.setStorageSync('user_id', defaultUserId)
  54. resolve(defaultUserId)
  55. }
  56. })
  57. })
  58. },
  59. // 清除用户信息
  60. clearUserInfo: function () {
  61. tt.removeStorageSync('user_id')
  62. }
  63. }
  64. Page({
  65. data: {
  66. appName: '酷乐秀',
  67. version: '1.0.0',
  68. messageContent: '',
  69. showReply: false,
  70. replyContent: '',
  71. isLoading: false,
  72. apiError: false,
  73. currentUserId: '',
  74. chatMessages: [], // 聊天消息列表(按时间顺序)
  75. scrollTop: 0, // 滚动位置
  76. scrollIntoView: '' // 滚动锚点
  77. },
  78. onLoad: function () {
  79. console.log('办公效率助手小程序已加载')
  80. this.setData({
  81. appName: '酷乐秀',
  82. version: '1.0.0'
  83. })
  84. // 初始化用户标识
  85. this.initUserIdentifier()
  86. },
  87. // 初始化用户标识
  88. initUserIdentifier: function () {
  89. const that = this
  90. UserManager.getUserIdentifier()
  91. .then(userId => {
  92. console.log('获取到用户ID:', userId)
  93. that.setData({
  94. currentUserId: userId
  95. })
  96. })
  97. .catch(err => {
  98. console.error('获取用户ID失败:', err)
  99. // 生成默认用户ID
  100. const defaultUserId = 'default_' + Date.now()
  101. that.setData({
  102. currentUserId: defaultUserId
  103. })
  104. tt.setStorageSync('user_id', defaultUserId)
  105. })
  106. },
  107. onShow: function () {
  108. console.log('办公效率助手小程序页面显示')
  109. },
  110. // 页面初次渲染完成
  111. onReady: function () {
  112. console.log('页面初次渲染完成')
  113. // 可以在这里添加需要在页面渲染完成后执行的逻辑
  114. },
  115. // 点击发送消息按钮(兼容两种方法名)
  116. handleSendMessage: function () {
  117. this.handleSendPrivateMessage()
  118. },
  119. // 点击发送消息按钮
  120. handleSendPrivateMessage: function () {
  121. const content = this.data.messageContent.trim()
  122. if (!content) {
  123. tt.showToast({
  124. title: '请输入消息内容',
  125. icon: 'none',
  126. duration: 2000
  127. })
  128. return
  129. }
  130. // 将用户消息添加到聊天记录
  131. const userMessage = {
  132. type: 'user',
  133. content: content,
  134. time: this.getCurrentTime(),
  135. timestamp: Date.now()
  136. }
  137. this.setData({
  138. chatMessages: [...this.data.chatMessages, userMessage],
  139. isLoading: true,
  140. apiError: false,
  141. messageContent: ''
  142. }, () => {
  143. // 滚动到底部
  144. this.scrollToBottom()
  145. })
  146. // 调用助手服务
  147. this.callReplyService(content)
  148. },
  149. // 调用助手服务
  150. callReplyService: function (userMessage) {
  151. const that = this
  152. // 获取用户ID并调用服务
  153. UserManager.getUserIdentifier()
  154. .then(userId => {
  155. console.log('调用助手服务,用户ID:', userId)
  156. // 更新当前用户ID
  157. that.setData({
  158. currentUserId: userId
  159. })
  160. // 发起服务请求
  161. tt.request({
  162. url: ServiceConfig.apiUrl,
  163. method: 'POST',
  164. data: {
  165. message: userMessage,
  166. userId: userId, // 添加用户ID参数
  167. appId: 'yyszkt_help',
  168. timestamp: Date.now(),
  169. // 可以根据需要添加更多参数
  170. context: 'music_assistant', // 保持接口参数不变
  171. language: 'zh-CN',
  172. userType: userId.startsWith('anonymous_') ? 'anonymous' : 'registered'
  173. },
  174. header: ServiceConfig.headers,
  175. timeout: ServiceConfig.timeout,
  176. success: function (res) {
  177. console.log('服务调用成功:', res)
  178. // 处理助手回复
  179. let assistantReply = ''
  180. if (res.statusCode === 200 && res.data) {
  181. // 根据API响应格式处理回复
  182. if (typeof res.data === 'string') {
  183. assistantReply = res.data
  184. } else if (res.data.reply) {
  185. assistantReply = res.data.reply
  186. } else if (res.data.choices && res.data.choices[0] && res.data.choices[0].message) {
  187. assistantReply = res.data.choices[0].message.content
  188. } else {
  189. assistantReply = '已收到您的消息,我这边正在为您整理建议。'
  190. }
  191. } else {
  192. // API调用失败,使用备用回复
  193. assistantReply = that.generateFallbackResponse(userMessage)
  194. }
  195. // 将助手回复添加到聊天记录
  196. const assistantReplyMessage = {
  197. type: 'assistant',
  198. content: assistantReply,
  199. time: that.getCurrentTime(),
  200. timestamp: Date.now()
  201. }
  202. that.setData({
  203. chatMessages: [...that.data.chatMessages, assistantReplyMessage],
  204. replyContent: assistantReply,
  205. showReply: true,
  206. isLoading: false
  207. }, () => {
  208. // 滚动到底部
  209. that.scrollToBottom()
  210. })
  211. // 清空输入框
  212. that.setData({
  213. messageContent: ''
  214. })
  215. },
  216. fail: function (err) {
  217. console.error('服务调用失败:', err)
  218. // 显示错误提示
  219. tt.showToast({
  220. title: '网络异常,使用本地建议',
  221. icon: 'none',
  222. duration: 2000
  223. })
  224. // 使用本地备用建议
  225. const fallbackReply = that.generateFallbackResponse(userMessage)
  226. that.setData({
  227. replyContent: fallbackReply,
  228. showReply: true,
  229. isLoading: false,
  230. apiError: true
  231. })
  232. // 清空输入框
  233. that.setData({
  234. messageContent: ''
  235. })
  236. },
  237. complete: function () {
  238. console.log('服务调用完成')
  239. }
  240. })
  241. })
  242. .catch(err => {
  243. console.error('获取用户ID失败:', err)
  244. // 使用默认用户ID继续调用
  245. const defaultUserId = 'default_' + Date.now()
  246. that.callReplyServiceWithUserId(userMessage, defaultUserId)
  247. })
  248. },
  249. // 使用指定用户ID调用服务
  250. callReplyServiceWithUserId: function (userMessage, userId) {
  251. const that = this
  252. tt.request({
  253. url: ServiceConfig.apiUrl,
  254. method: 'POST',
  255. data: {
  256. message: userMessage,
  257. userId: userId,
  258. appId: 'yyszkt_help',
  259. timestamp: Date.now(),
  260. context: 'music_assistant',
  261. language: 'zh-CN',
  262. userType: userId.startsWith('anonymous_') ? 'anonymous' : 'registered'
  263. },
  264. header: ServiceConfig.headers,
  265. timeout: ServiceConfig.timeout,
  266. success: function (res) {
  267. // 成功处理逻辑...
  268. let assistantReply = ''
  269. if (res.statusCode === 200 && res.data) {
  270. if (typeof res.data === 'string') {
  271. assistantReply = res.data
  272. } else if (res.data.reply) {
  273. assistantReply = res.data.reply
  274. } else if (res.data.choices && res.data.choices[0] && res.data.choices[0].message) {
  275. assistantReply = res.data.choices[0].message.content
  276. } else {
  277. assistantReply = '已收到您的消息,我这边正在为您整理建议。'
  278. }
  279. } else {
  280. assistantReply = that.generateFallbackResponse(userMessage)
  281. }
  282. // 将助手回复添加到聊天记录
  283. const assistantReplyMessage = {
  284. type: 'assistant',
  285. content: assistantReply,
  286. time: that.getCurrentTime(),
  287. timestamp: Date.now()
  288. }
  289. that.setData({
  290. chatMessages: [...that.data.chatMessages, assistantReplyMessage],
  291. replyContent: assistantReply,
  292. showReply: true,
  293. isLoading: false
  294. }, () => {
  295. // 滚动到底部
  296. that.scrollToBottom()
  297. })
  298. that.setData({
  299. messageContent: ''
  300. })
  301. },
  302. fail: function (err) {
  303. console.error('服务调用失败:', err)
  304. tt.showToast({
  305. title: '网络异常,使用本地建议',
  306. icon: 'none',
  307. duration: 2000
  308. })
  309. const fallbackReply = that.generateFallbackResponse(userMessage)
  310. // 将助手回复添加到聊天记录
  311. const assistantReplyMessage = {
  312. type: 'assistant',
  313. content: fallbackReply,
  314. time: that.getCurrentTime(),
  315. timestamp: Date.now()
  316. }
  317. that.setData({
  318. chatMessages: [...that.data.chatMessages, assistantReplyMessage],
  319. replyContent: fallbackReply,
  320. showReply: true,
  321. isLoading: false,
  322. apiError: true
  323. }, () => {
  324. // 滚动到底部
  325. that.scrollToBottom()
  326. })
  327. that.setData({
  328. messageContent: ''
  329. })
  330. },
  331. complete: function () {
  332. }
  333. })
  334. },
  335. // 生成备用回复(当API调用失败时使用)
  336. generateFallbackResponse: function (userMessage) {
  337. return this.generateReplyResponse(userMessage)
  338. },
  339. // 生成助手回复内容(本地备用)
  340. generateReplyResponse: function (userMessage) {
  341. return '当前客服不在线,暂无法回复消息,请稍等。'
  342. },
  343. // 关闭助手回复区域
  344. handleCloseReply: function () {
  345. this.setData({
  346. showReply: false,
  347. replyContent: '',
  348. apiError: false
  349. })
  350. },
  351. // 重新获取用户ID(用于调试或重置)
  352. refreshUserIdentifier: function () {
  353. const that = this
  354. UserManager.clearUserInfo()
  355. tt.showLoading({
  356. title: '重新获取用户信息...',
  357. mask: true
  358. })
  359. UserManager.getUserIdentifier()
  360. .then(userId => {
  361. tt.hideLoading()
  362. that.setData({
  363. currentUserId: userId
  364. })
  365. tt.showToast({
  366. title: '用户信息更新成功',
  367. icon: 'success',
  368. duration: 2000
  369. })
  370. })
  371. .catch(_err => {
  372. tt.hideLoading()
  373. tt.showToast({
  374. title: '用户信息更新失败',
  375. icon: 'none',
  376. duration: 2000
  377. })
  378. })
  379. },
  380. // 输入框内容变化
  381. handleInputChange: function (e) {
  382. this.setData({
  383. messageContent: e.detail.value
  384. })
  385. },
  386. // 跳转产品介绍
  387. handleGoProduct: function () {
  388. tt.redirectTo({
  389. url: '/pages/product/index'
  390. })
  391. },
  392. // 跳转申请试用
  393. handleGoTrial: function () {
  394. tt.redirectTo({
  395. url: '/pages/trial/index'
  396. })
  397. },
  398. // 获取当前时间
  399. getCurrentTime: function () {
  400. const now = new Date()
  401. const hours = now.getHours().toString().padStart(2, '0')
  402. const minutes = now.getMinutes().toString().padStart(2, '0')
  403. return `${hours}:${minutes}`
  404. },
  405. // 滚动到底部 - 完全重写的专业级实现
  406. scrollToBottom: function () {
  407. this.setData({
  408. scrollIntoView: ''
  409. })
  410. setTimeout(() => {
  411. this.setData({
  412. scrollIntoView: 'bottom-anchor'
  413. })
  414. }, 20)
  415. setTimeout(() => {
  416. this.setData({
  417. scrollTop: this.data.scrollTop + 9999
  418. })
  419. }, 120)
  420. setTimeout(() => {
  421. this.ensureLastMessageInView(0)
  422. }, 180)
  423. },
  424. // 确保最后一条消息完整显示在消息区可视范围内
  425. ensureLastMessageInView: function (retryCount) {
  426. const MAX_RETRY = 5
  427. if (retryCount >= MAX_RETRY) {
  428. return
  429. }
  430. const query = tt.createSelectorQuery()
  431. query.selectAll('.message-item').boundingClientRect()
  432. query.select('.chat-container').boundingClientRect()
  433. query.exec((res) => {
  434. const messageRects = res[0]
  435. const chatRect = res[1]
  436. if (!messageRects || !messageRects.length || !chatRect) {
  437. return
  438. }
  439. const lastMessageRect = messageRects[messageRects.length - 1]
  440. const safeBottom = chatRect.bottom - 16
  441. const overlapHeight = lastMessageRect.bottom - safeBottom
  442. if (overlapHeight > 0) {
  443. this.setData({
  444. scrollIntoView: '',
  445. scrollTop: this.data.scrollTop + overlapHeight + 24
  446. })
  447. setTimeout(() => {
  448. this.ensureLastMessageInView(retryCount + 1)
  449. }, 60)
  450. }
  451. })
  452. },
  453. })