const Vaccine = require('../models/Vaccine')
const { Op } = require('sequelize')

// 获取疫苗列表
exports.getVaccines = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, keyword = '', type = '', status = '' } = req.query
    
    // 构建查询条件
    const where = {}
    
    // 关键词搜索
    if (keyword) {
      where[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { manufacturer: { [Op.like]: `%${keyword}%` } }
      ]
    }
    
    // 疫苗类型筛选
    if (type) {
      where.type = type
    }
    
    // 状态筛选
    if (status) {
      where.status = status
    }
    
    // 分页查询
    const offset = (page - 1) * pageSize
    const { count, rows } = await Vaccine.findAndCountAll({
      where,
      order: [['createTime', 'DESC']],
      limit: parseInt(pageSize),
      offset: parseInt(offset)
    })
    
    res.json({
      code: 200,
      data: {
        list: rows,
        total: count,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      },
      message: '获取疫苗列表成功'
    })
  } catch (error) {
    console.error('获取疫苗列表失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}

// 获取疫苗详情
exports.getVaccineById = async (req, res) => {
  try {
    const { id } = req.params
    
    const vaccine = await Vaccine.findByPk(id)
    
    if (!vaccine) {
      return res.status(404).json({
        code: 404,
        message: '疫苗不存在'
      })
    }
    
    res.json({
      code: 200,
      data: vaccine,
      message: '获取疫苗详情成功'
    })
  } catch (error) {
    console.error('获取疫苗详情失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}

// 创建疫苗
exports.createVaccine = async (req, res) => {
  try {
    const {
      name,
      type,
      manufacturer,
      approvalNumber,
      specification,
      price,
      validDays,
      storageCondition,
      notes,
      stockCount = 0
    } = req.body
    
    // 验证必填字段
    if (!name || !type || !manufacturer || !approvalNumber || !specification || !price || !validDays || !storageCondition) {
      return res.status(400).json({
        code: 400,
        message: '请填写所有必填字段'
      })
    }
    
    // 验证疫苗类型
    const validTypes = ['foot_and_mouth_disease', 'bovine_tuberculosis', 'brucellosis', 'rabies', 'other']
    if (!validTypes.includes(type)) {
      return res.status(400).json({
        code: 400,
        message: '疫苗类型无效'
      })
    }
    
    // 检查批准文号是否已存在
    const existingVaccine = await Vaccine.findOne({
      where: { approvalNumber }
    })
    
    if (existingVaccine) {
      return res.status(400).json({
        code: 400,
        message: '该批准文号已存在'
      })
    }
    
    // 创建疫苗
    const vaccine = await Vaccine.create({
      name,
      type,
      manufacturer,
      approvalNumber,
      specification,
      price: parseFloat(price),
      validDays: parseInt(validDays),
      storageCondition,
      notes,
      stockCount: parseInt(stockCount),
      status: stockCount > 0 ? 'valid' : 'low_stock'
    })
    
    res.json({
      code: 200,
      data: vaccine,
      message: '创建疫苗成功'
    })
  } catch (error) {
    console.error('创建疫苗失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}

// 更新疫苗
exports.updateVaccine = async (req, res) => {
  try {
    const { id } = req.params
    const updateData = req.body
    
    // 验证疫苗类型
    if (updateData.type) {
      const validTypes = ['foot_and_mouth_disease', 'bovine_tuberculosis', 'brucellosis', 'rabies', 'other']
      if (!validTypes.includes(updateData.type)) {
        return res.status(400).json({
          code: 400,
          message: '疫苗类型无效'
        })
      }
    }
    
    // 如果更新批准文号，检查是否已存在
    if (updateData.approvalNumber) {
      const existingVaccine = await Vaccine.findOne({
        where: { 
          approvalNumber: updateData.approvalNumber,
          id: { [Op.ne]: id }
        }
      })
      
      if (existingVaccine) {
        return res.status(400).json({
          code: 400,
          message: '该批准文号已存在'
        })
      }
    }
    
    // 更新疫苗
    const [affectedRows] = await Vaccine.update(updateData, {
      where: { id }
    })
    
    if (affectedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '疫苗不存在'
      })
    }
    
    // 获取更新后的疫苗
    const updatedVaccine = await Vaccine.findByPk(id)
    
    res.json({
      code: 200,
      data: updatedVaccine,
      message: '更新疫苗成功'
    })
  } catch (error) {
    console.error('更新疫苗失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}

// 删除疫苗
exports.deleteVaccine = async (req, res) => {
  try {
    const { id } = req.params
    
    const deletedRows = await Vaccine.destroy({
      where: { id }
    })
    
    if (deletedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '疫苗不存在'
      })
    }
    
    res.json({
      code: 200,
      message: '删除疫苗成功'
    })
  } catch (error) {
    console.error('删除疫苗失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}

// 批量删除疫苗
exports.batchDeleteVaccines = async (req, res) => {
  try {
    const { ids } = req.body
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '请选择要删除的疫苗'
      })
    }
    
    const deletedRows = await Vaccine.destroy({
      where: {
        id: {
          [Op.in]: ids
        }
      }
    })
    
    res.json({
      code: 200,
      data: { deletedCount: deletedRows },
      message: `成功删除 ${deletedRows} 个疫苗`
    })
  } catch (error) {
    console.error('批量删除疫苗失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}

// 疫苗入库
exports.stockIn = async (req, res) => {
  try {
    const { id } = req.params
    const { count, batchNumber, inDate } = req.body
    
    if (!count || count <= 0) {
      return res.status(400).json({
        code: 400,
        message: '入库数量必须大于0'
      })
    }
    
    const vaccine = await Vaccine.findByPk(id)
    if (!vaccine) {
      return res.status(404).json({
        code: 404,
        message: '疫苗不存在'
      })
    }
    
    // 更新库存数量
    const newStockCount = vaccine.stockCount + parseInt(count)
    const newStatus = newStockCount > 0 ? 'valid' : 'low_stock'
    
    await Vaccine.update({
      stockCount: newStockCount,
      status: newStatus
    }, {
      where: { id }
    })
    
    res.json({
      code: 200,
      message: '疫苗入库成功',
      data: {
        newStockCount,
        status: newStatus
      }
    })
  } catch (error) {
    console.error('疫苗入库失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}

// 疫苗出库
exports.stockOut = async (req, res) => {
  try {
    const { id } = req.params
    const { count, purpose, outDate } = req.body
    
    if (!count || count <= 0) {
      return res.status(400).json({
        code: 400,
        message: '出库数量必须大于0'
      })
    }
    
    const vaccine = await Vaccine.findByPk(id)
    if (!vaccine) {
      return res.status(404).json({
        code: 404,
        message: '疫苗不存在'
      })
    }
    
    if (vaccine.stockCount < count) {
      return res.status(400).json({
        code: 400,
        message: '库存不足，无法出库'
      })
    }
    
    // 更新库存数量
    const newStockCount = vaccine.stockCount - parseInt(count)
    let newStatus = 'valid'
    if (newStockCount === 0) {
      newStatus = 'low_stock'
    } else if (newStockCount < 100) {
      newStatus = 'low_stock'
    }
    
    await Vaccine.update({
      stockCount: newStockCount,
      status: newStatus
    }, {
      where: { id }
    })
    
    res.json({
      code: 200,
      message: '疫苗出库成功',
      data: {
        newStockCount,
        status: newStatus
      }
    })
  } catch (error) {
    console.error('疫苗出库失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}
