const api = require('../../utils/api'); const storage = require('../../utils/storage'); Page({ data: { loading: true, recipe: null, missingIngredients: [] }, onLoad(options) { if (options.id) { api.get('/api/recipe/' + options.id).then(data => { this.setData({ loading: false, recipe: data }); }).catch(() => { this.setData({ loading: false }); wx.showToast({ title: '加载失败', icon: 'none' }); }); } if (options.missing) { try { this.setData({ missingIngredients: JSON.parse(decodeURIComponent(options.missing)) }); } catch (e) { // ignore } } // 启用分享 wx.showShareMenu({ withShareTicket: false, menus: ['shareAppMessage', 'shareTimeline'] }); }, onShareAppMessage() { const recipe = this.data.recipe; if (!recipe) return {}; return { title: '我用冰箱剩菜做出了「' + recipe.name + '」!你也来试试?', path: '/pages/recipe-detail/recipe-detail?id=' + recipe.id, imageUrl: recipe.imageUrl || '' }; }, onShareTimeline() { const recipe = this.data.recipe; if (!recipe) return {}; return { title: recipe.name + ' · 冰箱盲盒开出的好菜', query: 'id=' + recipe.id, imageUrl: recipe.imageUrl || '' }; }, startTimer() { wx.showToast({ title: '计时器功能开发中', icon: 'none' }); }, addToShopping() { const recipe = this.data.recipe; if (!recipe || !recipe.ingredients) return; const raw = storage.get('shopping_list', []); const existing = Array.isArray(raw) ? raw : []; const names = new Set(existing.map(i => i.name)); // 只添加"缺少的食材";若无缺失信息则提示而非加全部 const missing = this.data.missingIngredients; if (!Array.isArray(missing) || missing.length === 0) { wx.showToast({ title: '该菜谱食材已齐全', icon: 'none' }); return; } const targetNames = new Set(missing); let added = 0; recipe.ingredients.forEach(ing => { if (!targetNames.has(ing.ingredientName)) return; if (names.has(ing.ingredientName)) return; existing.push({ name: ing.ingredientName, amount: ing.amount || '', from: recipe.name, checked: false }); names.add(ing.ingredientName); added++; }); storage.set('shopping_list', existing); if (added === 0) { wx.showToast({ title: '缺少食材已在清单中', icon: 'none' }); } else { wx.showToast({ title: '已添加 ' + added + ' 项缺少食材', icon: 'success' }); } } });