const { query } = require('../config/database')

async function getGoods(ctx) {
  let sql = 'SELECT * FROM goods WHERE 1=1'
  const params = []
  
  if (ctx.query.hot === '1') {
    sql += ' AND is_hot = 1'
  }
  
  if (ctx.query.isNew === '1') {
    sql += ' AND is_new = 1'
  }
  
  if (ctx.query.category_id) {
    sql += ' AND category_id = ?'
    params.push(parseInt(ctx.query.category_id))
  }
  
  if (ctx.query.keyword) {
    sql += ' AND name LIKE ?'
    params.push(`%${ctx.query.keyword}%`)
  }
  
  sql += ' ORDER BY id DESC'
  
  const goods = await query(sql, params)
  
  ctx.body = {
    code: 200,
    data: goods
  }
}

async function getGoodsById(ctx) {
  const goodsId = parseInt(ctx.params.id)
  const goods = await query('SELECT * FROM goods WHERE id = ?', [goodsId])
  
  if (goods.length > 0) {
    ctx.body = {
      code: 200,
      data: goods[0]
    }
  } else {
    ctx.body = {
      code: 404,
      message: '商品不存在'
    }
  }
}

async function createGoods(ctx) {
  const { name, price, unit, categoryId, images, stock, pricingType, isHot, isNew, remark, goodsNo, barcode } = ctx.request.body
  
  if (!name || !price || !unit) {
    ctx.body = {
      code: 400,
      message: '缺少必填字段'
    }
    return
  }
  
  const sql = `INSERT INTO goods 
    (name, price, cost_price, unit, category_id, images, stock, pricing_type, is_hot, is_new, remark, goods_no, barcode)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
  
  const params = [
    name,
    parseFloat(price),
    parseFloat(ctx.request.body.costPrice || 0),
    unit,
    categoryId || null,
    JSON.stringify(images || []),
    parseInt(stock) || 0,
    parseInt(pricingType) || 1,
    parseInt(isHot) || 0,
    parseInt(isNew) || 0,
    remark || '',
    goodsNo || '',
    barcode || ''
  ]
  
  try {
    const result = await query(sql, params)
    ctx.body = {
      code: 200,
      message: '添加成功',
      data: { id: result.insertId }
    }
  } catch (error) {
    console.error('添加商品失败:', error)
    ctx.body = {
      code: 500,
      message: '添加失败'
    }
  }
}

async function updateGoods(ctx) {
  const goodsId = parseInt(ctx.params.id)
  const { name, price, unit, categoryId, images, stock, pricingType, isHot, isNew, description } = ctx.request.body
  
  if (!name || !price || !unit) {
    ctx.body = {
      code: 400,
      message: '缺少必填字段'
    }
    return
  }
  
  const sql = `UPDATE goods SET 
    name = ?, price = ?, original_price = ?, unit = ?, category_id = ?, images = ?, 
    stock = ?, pricing_type = ?, is_hot = ?, is_new = ?, description = ?
    WHERE id = ?`
  
  const params = [
    name,
    parseFloat(price),
    parseFloat(ctx.request.body.originalPrice || 0),
    unit,
    categoryId || null,
    JSON.stringify(images || []),
    parseInt(stock) || 0,
    parseInt(pricingType) || 1,
    parseInt(isHot) || 0,
    parseInt(isNew) || 0,
    description || '',
    goodsId
  ]
  
  try {
    const result = await query(sql, params)
    if (result.affectedRows > 0) {
      ctx.body = {
        code: 200,
        message: '更新成功'
      }
    } else {
      ctx.body = {
        code: 404,
        message: '商品不存在'
      }
    }
  } catch (error) {
    console.error('更新商品失败:', error)
    ctx.body = {
      code: 500,
      message: '更新失败'
    }
  }
}

async function deleteGoods(ctx) {
  const goodsId = parseInt(ctx.params.id)
  
  try {
    const result = await query('DELETE FROM goods WHERE id = ?', [goodsId])
    if (result.affectedRows > 0) {
      ctx.body = {
        code: 200,
        message: '删除成功'
      }
    } else {
      ctx.body = {
        code: 404,
        message: '商品不存在'
      }
    }
  } catch (error) {
    console.error('删除商品失败:', error)
    ctx.body = {
      code: 500,
      message: '删除失败'
    }
  }
}

module.exports = {
  getGoods,
  getGoodsById,
  createGoods,
  updateGoods,
  deleteGoods
}