ai-recommend.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. Page({
  2. data: {
  3. loading: false,
  4. recommendation: null,
  5. error: null
  6. },
  7. onLoad: function(options) {
  8. if (!options.attractions) {
  9. this.setData({ error: '未获取到景点信息' });
  10. return;
  11. }
  12. const attractions = decodeURIComponent(options.attractions).split(',');
  13. this.getAIRecommendation(attractions);
  14. },
  15. getAIRecommendation: function(attractions) {
  16. this.setData({ loading: true, error: null });
  17. wx.request({
  18. url: 'http://127.0.0.1:8000/api/ai-travel-plan/',
  19. method: 'POST',
  20. data: {
  21. locations: attractions,
  22. days: 3,
  23. budget: 5000,
  24. preferences: []
  25. },
  26. success: (res) => {
  27. console.log('完整响应:', res); // 添加调试日志
  28. if (res.data && res.data.status === 'success') { // 修改判断条件
  29. this.setData({
  30. recommendation: res.data.data.recommendation || '无推荐内容'
  31. });
  32. } else {
  33. this.setData({
  34. error: res.data?.error || res.data?.message || '获取推荐失败'
  35. });
  36. }
  37. },
  38. fail: (err) => {
  39. console.error('请求失败:', err); // 添加错误日志
  40. this.setData({ error: `请求失败: ${err.errMsg || '未知错误'}` });
  41. },
  42. complete: () => {
  43. this.setData({ loading: false });
  44. }
  45. });
  46. },
  47. formatRecommendation: function(text) {
  48. // 简单处理Markdown格式
  49. const nodes = [];
  50. const lines = text.split('\n');
  51. lines.forEach(line => {
  52. if (line.startsWith('#')) {
  53. nodes.push({
  54. name: 'h2',
  55. attrs: { class: 'heading' },
  56. children: [{ type: 'text', text: line.replace(/^#+\s*/, '') }]
  57. });
  58. } else if (line.startsWith('* ')) {
  59. nodes.push({
  60. name: 'view',
  61. attrs: { class: 'list-item' },
  62. children: [{
  63. name: 'text',
  64. children: [{ type: 'text', text: '• ' + line.substring(2) }]
  65. }]
  66. });
  67. } else {
  68. nodes.push({
  69. name: 'text',
  70. children: [{ type: 'text', text: line }]
  71. });
  72. }
  73. });
  74. return nodes;
  75. },
  76. // 保存行程方法
  77. savePlan: function() {
  78. wx.showToast({
  79. title: '行程已保存',
  80. icon: 'success'
  81. });
  82. },
  83. // 重试方法
  84. retry: function() {
  85. this.getAIRecommendation(this.data.attractions);
  86. }
  87. });