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

// 获取库存列表
async function getStockList(ctx) {
  const keyword = ctx.query.keyword
  const threshold = parseInt(ctx.query.threshold) || 0

  let sql = `
    SELECT 
      s.id,
      s.goods_id,
      g.name as goods_name,
      g.images as goods_image,
      g.unit as goods_unit,
      s.quantity,
      s.warehouse
    FROM stock s
    LEFT JOIN goods g ON s.goods_id = g.id
    WHERE 1=1
  `
  const params = []

  if (keyword) {
    sql += ' AND (g.name LIKE ? OR g.barcode LIKE ?)'
    params.push(`%${keyword}%`, `%${keyword}%`)
  }

  if (threshold > 0) {
    sql += ' AND s.quantity <= ?'
    params.push(threshold)
  }

  sql += ' ORDER BY s.quantity ASC'

  const stockList = await query(sql, params)

  ctx.body = {
    code: 200,
    data: stockList
  }
}

// 调整库存
async function adjustStock(ctx) {
  const goodsId = ctx.params.id
  const { quantity, type } = ctx.request.body

  if (!quantity || quantity <= 0) {
    ctx.body = {
      code: 400,
      message: '请输入有效的调整数量'
    }
    return
  }

  // 先检查库存记录是否存在
  let stockRecords = await query('SELECT * FROM stock WHERE goods_id = ?', [goodsId])

  if (stockRecords.length === 0) {
    // 如果库存记录不存在，先创建
    if (type === 'add') {
      await query(
        'INSERT INTO stock (goods_id, quantity, warehouse) VALUES (?, ?, ?)',
        [goodsId, quantity, '默认仓库']
      )
    } else {
      ctx.body = {
        code: 400,
        message: '库存不足，无法减少'
      }
      return
    }
  } else {
    const currentStock = stockRecords[0]
    let newQuantity

    if (type === 'add') {
      newQuantity = currentStock.quantity + quantity
    } else {
      newQuantity = currentStock.quantity - quantity
      if (newQuantity < 0) {
        ctx.body = {
          code: 400,
          message: '库存不足，无法减少'
        }
        return
      }
    }

    await query(
      'UPDATE stock SET quantity = ? WHERE goods_id = ?',
      [newQuantity, goodsId]
    )
  }

  // 获取更新后的库存
  const updatedStock = await query('SELECT * FROM stock WHERE goods_id = ?', [goodsId])

  ctx.body = {
    code: 200,
    data: updatedStock[0],
    message: '库存调整成功'
  }
}

// 获取单个商品的库存
async function getStockByGoodsId(ctx) {
  const goodsId = ctx.params.id

  const stockRecords = await query('SELECT * FROM stock WHERE goods_id = ?', [goodsId])

  if (stockRecords.length > 0) {
    ctx.body = {
      code: 200,
      data: stockRecords[0]
    }
  } else {
    ctx.body = {
      code: 200,
      data: { goods_id: goodsId, quantity: 0, warehouse: '默认仓库' }
    }
  }
}

module.exports = {
  getStockList,
  adjustStock,
  getStockByGoodsId
}
