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

// 获取防疫记录列表
exports.getEpidemicRecords = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, keyword = '', type = '', status = '', startDate = '', endDate = '' } = req.query
    
    // 构建查询条件
    const where = {}
    
    // 关键词搜索
    if (keyword) {
      where[Op.or] = [
        { farmName: { [Op.like]: `%${keyword}%` } },
        { epidemicStaff: { [Op.like]: `%${keyword}%` } }
      ]
    }
    
    // 防疫类型筛选
    if (type) {
      where.type = type
    }
    
    // 状态筛选
    if (status) {
      where.status = status
    }
    
    // 日期范围筛选
    if (startDate && endDate) {
      where.epidemicDate = {
        [Op.between]: [startDate, endDate]
      }
    } else if (startDate) {
      where.epidemicDate = {
        [Op.gte]: startDate
      }
    } else if (endDate) {
      where.epidemicDate = {
        [Op.lte]: endDate
      }
    }
    
    // 分页查询
    const offset = (page - 1) * pageSize
    const { count, rows } = await EpidemicRecord.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.getEpidemicRecordById = async (req, res) => {
  try {
    const { id } = req.params
    
    const record = await EpidemicRecord.findByPk(id)
    
    if (!record) {
      return res.status(404).json({
        code: 404,
        message: '防疫记录不存在'
      })
    }
    
    res.json({
      code: 200,
      data: record,
      message: '获取防疫记录详情成功'
    })
  } catch (error) {
    console.error('获取防疫记录详情失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}

// 创建防疫记录
exports.createEpidemicRecord = async (req, res) => {
  try {
    const {
      farmName,
      type,
      epidemicStaff,
      phone,
      epidemicDate,
      count,
      vaccineName,
      area,
      disinfectant,
      healthResult,
      description,
      notes,
      status
    } = req.body
    
    // 验证必填字段
    if (!farmName || !type || !epidemicStaff || !phone || !epidemicDate) {
      return res.status(400).json({
        code: 400,
        message: '请填写所有必填字段'
      })
    }
    
    // 验证防疫类型
    const validTypes = ['vaccination', 'disinfection', 'health_check', 'other']
    if (!validTypes.includes(type)) {
      return res.status(400).json({
        code: 400,
        message: '防疫类型无效'
      })
    }
    
    // 验证状态
    const validStatuses = ['completed', 'pending', 'failed']
    if (status && !validStatuses.includes(status)) {
      return res.status(400).json({
        code: 400,
        message: '状态无效'
      })
    }
    
    // 创建防疫记录
    const record = await EpidemicRecord.create({
      farmName,
      type,
      epidemicStaff,
      phone,
      epidemicDate,
      count: count || 0,
      vaccineName,
      area,
      disinfectant,
      healthResult,
      description,
      notes,
      status: status || 'completed'
    })
    
    res.json({
      code: 200,
      data: record,
      message: '创建防疫记录成功'
    })
  } catch (error) {
    console.error('创建防疫记录失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}

// 更新防疫记录
exports.updateEpidemicRecord = async (req, res) => {
  try {
    const { id } = req.params
    const updateData = req.body
    
    // 验证防疫类型
    if (updateData.type) {
      const validTypes = ['vaccination', 'disinfection', 'health_check', 'other']
      if (!validTypes.includes(updateData.type)) {
        return res.status(400).json({
          code: 400,
          message: '防疫类型无效'
        })
      }
    }
    
    // 验证状态
    if (updateData.status) {
      const validStatuses = ['completed', 'pending', 'failed']
      if (!validStatuses.includes(updateData.status)) {
        return res.status(400).json({
          code: 400,
          message: '状态无效'
        })
      }
    }
    
    // 更新防疫记录
    const [affectedRows] = await EpidemicRecord.update(updateData, {
      where: { id }
    })
    
    if (affectedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '防疫记录不存在'
      })
    }
    
    // 获取更新后的记录
    const updatedRecord = await EpidemicRecord.findByPk(id)
    
    res.json({
      code: 200,
      data: updatedRecord,
      message: '更新防疫记录成功'
    })
  } catch (error) {
    console.error('更新防疫记录失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    })
  }
}

// 删除防疫记录
exports.deleteEpidemicRecord = async (req, res) => {
  try {
    const { id } = req.params
    
    const deletedRows = await EpidemicRecord.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.batchDeleteEpidemicRecords = 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 EpidemicRecord.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
    })
  }
}
