const { query } = require('../config/database') const fetch = require('node-fetch') const { AI_VL_MODEL, AI_RECOGNIZE_LIMIT } = require('../config/constants') const AI_API_KEY = process.env.DASHSCOPE_API_KEY const AI_API_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions' async function getByBarcode(ctx) { try { const { barcode } = ctx.request.body if (!barcode) { ctx.body = { code: 400, message: '请提供条形码' } return } const goods = await query('SELECT * FROM goods WHERE barcode = ? LIMIT 1', [barcode]) if (goods.length > 0) { ctx.body = { code: 200, data: goods[0] } } else { ctx.body = { code: 404, message: '未找到该商品' } } } catch (error) { console.error('条码查询失败:', error) ctx.body = { code: 500, message: '查询失败' } } } async function recognizeImage(ctx) { try { const { imageData } = ctx.request.body if (!imageData) { ctx.body = { code: 400, message: '请提供图片数据' } return } if (!AI_API_KEY) { ctx.body = { code: 500, message: 'AI 识别未配置' } return } const response = await fetch(AI_API_URL, { method: 'POST', headers: { 'Authorization': `Bearer ${AI_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: AI_VL_MODEL, messages: [ { role: 'user', content: [ { type: 'text', text: '请识别这张图片中的商品,返回商品名称。只返回名称,不要其他内容。' }, { type: 'image_url', image_url: { url: imageData } } ] } ] }) }) const result = await response.json() const name = result?.choices?.[0]?.message?.content?.trim() || '' const goods = name ? await query('SELECT * FROM goods WHERE name LIKE ? LIMIT ?', [`%${name}%`, AI_RECOGNIZE_LIMIT]) : [] ctx.body = { code: 200, data: { message: name ? `识别到: ${name}` : '未识别到商品', goods: goods || [] } } } catch (error) { console.error('图片识别失败:', error) ctx.body = { code: 500, message: '识别失败' } } } module.exports = { getByBarcode, recognizeImage }