const express = require('express');
const router = express.Router();

// 中间件将在服务器启动时设置
let authenticateToken = null;
let checkPermission = null;
let pool = null;

// 设置中间件和数据库连接（从主服务器导入）
function setMiddleware(auth, permission, dbPool) {
  authenticateToken = auth;
  checkPermission = permission;
  pool = dbPool;
  console.log('✅ Cattle模块中间件设置完成');
}

// 获取牛只列表（无需认证的测试版本）
router.get('/', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      owner_id, 
      breed, 
      status, 
      health_status,
      search 
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockCattle = [
        {
          id: 1,
          ear_tag: 'XL001',
          name: '小花',
          breed: '西门塔尔牛',
          gender: 'female',
          birth_date: '2022-03-15',
          color: '黄白花',
          weight: 450.50,
          health_status: 'healthy',
          status: 'active',
          farm_location: '锡林浩特市第一牧场',
          created_at: '2024-01-01 00:00:00'
        },
        {
          id: 2,
          ear_tag: 'XL002',
          name: '壮壮',
          breed: '安格斯牛',
          gender: 'male',
          birth_date: '2021-08-20',
          color: '黑色',
          weight: 580.75,
          health_status: 'healthy',
          status: 'active',
          farm_location: '锡林浩特市第一牧场',
          created_at: '2024-01-01 01:00:00'
        },
        {
          id: 3,
          ear_tag: 'XL003',
          name: '美美',
          breed: '夏洛莱牛',
          gender: 'female',
          birth_date: '2022-05-10',
          color: '白色',
          weight: 420.30,
          health_status: 'healthy',
          status: 'active',
          farm_location: '东乌旗牧场A',
          created_at: '2024-01-01 02:00:00'
        }
      ];

      return res.json({
        success: true,
        data: {
          cattle: mockCattle,
          pagination: {
            total: mockCattle.length,
            page: parseInt(page),
            limit: parseInt(limit),
            pages: Math.ceil(mockCattle.length / limit)
          }
        }
      });
    }

    // 检查数据库连接
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      const mockCattle = [
        {
          id: 1,
          ear_tag: 'XL001',
          name: '小花',
          breed: '西门塔尔牛',
          gender: 'female',
          birth_date: '2022-03-15',
          color: '黄白花',
          weight: 450.50,
          health_status: 'healthy',
          status: 'active',
          farm_location: '锡林浩特市第一牧场',
          created_at: '2024-01-01 00:00:00'
        }
      ];

      return res.json({
        success: true,
        message: '数据库连接不可用，返回模拟数据',
        data: {
          cattle: mockCattle,
          pagination: {
            total: mockCattle.length,
            page: parseInt(page),
            limit: parseInt(limit),
            pages: Math.ceil(mockCattle.length / limit)
          }
        }
      });
    }

    // 构建查询条件
    let whereClause = '1=1';
    let queryParams = [];

    if (owner_id) {
      whereClause += ' AND owner_id = ?';
      queryParams.push(owner_id);
    }

    if (breed) {
      whereClause += ' AND breed = ?';
      queryParams.push(breed);
    }

    if (status) {
      whereClause += ' AND status = ?';
      queryParams.push(status);
    }

    if (health_status) {
      whereClause += ' AND health_status = ?';
      queryParams.push(health_status);
    }

    if (search) {
      whereClause += ' AND (ear_tag LIKE ? OR name LIKE ? OR breed LIKE ?)';
      const searchTerm = `%${search}%`;
      queryParams.push(searchTerm, searchTerm, searchTerm);
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM cattle WHERE ${whereClause}`,
      queryParams
    );
    const total = countResult[0].total;

    // 获取牛只列表
    const [cattle] = await pool.execute(
      `SELECT c.*, u.real_name as owner_name 
       FROM cattle c 
       LEFT JOIN users u ON c.owner_id = u.id 
       WHERE ${whereClause} 
       ORDER BY c.created_at DESC 
       LIMIT ? OFFSET ?`,
      [...queryParams, parseInt(limit), offset]
    );

    res.json({
      success: true,
      data: {
        cattle,
        pagination: {
          total,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(total / limit)
        }
      }
    });

  } catch (error) {
    console.error('获取牛只列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取牛只列表失败',
      code: 'GET_CATTLE_ERROR'
    });
  }
});

// 获取单个牛只信息（无需认证的测试版本）
router.get('/:id', async (req, res) => {
  try {
    const cattleId = req.params.id;

    if (!pool) {
      return res.status(500).json({
        success: false,
        message: '数据库连接不可用',
        code: 'DB_UNAVAILABLE'
      });
    }

    // 检查数据库连接
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      return res.status(500).json({
        success: false,
        message: '数据库连接不可用',
        code: 'DB_UNAVAILABLE'
      });
    }

    // 获取牛只基本信息
    const [cattle] = await pool.execute(
      `SELECT c.*, u.real_name as owner_name, u.phone as owner_phone 
       FROM cattle c 
       LEFT JOIN users u ON c.owner_id = u.id 
       WHERE c.id = ?`,
      [cattleId]
    );

    if (cattle.length === 0) {
      return res.status(404).json({
        success: false,
        message: '牛只不存在',
        code: 'CATTLE_NOT_FOUND'
      });
    }

    // 获取最近的饲养记录
    const [feedingRecords] = await pool.execute(
      `SELECT * FROM feeding_records 
       WHERE cattle_id = ? 
       ORDER BY record_date DESC 
       LIMIT 10`,
      [cattleId]
    );

    // 获取繁殖记录
    const [breedingRecords] = await pool.execute(
      `SELECT * FROM breeding_records 
       WHERE cattle_id = ? 
       ORDER BY breeding_date DESC 
       LIMIT 5`,
      [cattleId]
    );

    res.json({
      success: true,
      data: {
        cattle: cattle[0],
        feeding_records: feedingRecords,
        breeding_records: breedingRecords
      }
    });

  } catch (error) {
    console.error('获取牛只详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取牛只详情失败',
      code: 'GET_CATTLE_DETAIL_ERROR'
    });
  }
});

// 添加新牛只
router.post('/', async (req, res) => {
  try {
    const {
      ear_tag,
      name,
      breed,
      gender,
      birth_date,
      color,
      weight,
      height,
      owner_id,
      farm_location,
      parent_male_id,
      parent_female_id,
      vaccination_records,
      health_records,
      images,
      notes
    } = req.body;

    // 验证必填字段
    if (!ear_tag || !breed || !gender || !owner_id) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段：ear_tag, breed, gender, owner_id',
        code: 'MISSING_REQUIRED_FIELDS'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟响应
      return res.status(201).json({
        success: true,
        message: '牛只添加成功（模拟）',
        data: {
          id: Math.floor(Math.random() * 1000) + 100,
          ear_tag,
          name,
          breed,
          gender,
          birth_date,
          color,
          weight,
          height,
          health_status: 'healthy',
          status: 'active',
          owner_id,
          farm_location,
          created_at: new Date().toISOString()
        }
      });
    }

    // 检查数据库连接
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      return res.status(500).json({
        success: false,
        message: '数据库连接不可用',
        code: 'DB_UNAVAILABLE'
      });
    }

    // 检查耳标是否已存在
    const [existingCattle] = await pool.execute(
      'SELECT id FROM cattle WHERE ear_tag = ? AND deleted_at IS NULL',
      [ear_tag]
    );

    if (existingCattle.length > 0) {
      return res.status(400).json({
        success: false,
        message: '耳标号已存在',
        code: 'EAR_TAG_EXISTS'
      });
    }

    // 插入新牛只记录
    const insertQuery = `
      INSERT INTO cattle (
        ear_tag, name, breed, gender, birth_date, color, weight, height,
        owner_id, farm_location, parent_male_id, parent_female_id,
        vaccination_records, health_records, images, notes
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;

    const [result] = await pool.execute(insertQuery, [
      ear_tag, name, breed, gender, birth_date, color, weight, height,
      owner_id, farm_location, parent_male_id, parent_female_id,
      JSON.stringify(vaccination_records || []),
      JSON.stringify(health_records || []),
      JSON.stringify(images || []),
      notes
    ]);

    // 获取新创建的牛只信息
    const [newCattle] = await pool.execute(
      'SELECT * FROM cattle WHERE id = ?',
      [result.insertId]
    );

    res.status(201).json({
      success: true,
      message: '牛只添加成功',
      data: {
        ...newCattle[0],
        vaccination_records: JSON.parse(newCattle[0].vaccination_records || '[]'),
        health_records: JSON.parse(newCattle[0].health_records || '[]'),
        images: JSON.parse(newCattle[0].images || '[]')
      }
    });
  } catch (error) {
    console.error('添加牛只失败:', error);
    res.status(500).json({
      success: false,
      message: '添加牛只失败',
      code: 'CREATE_CATTLE_ERROR'
    });
  }
});

// 更新牛只信息
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      ear_tag,
      breed,
      gender,
      age_months,
      weight_kg,
      health_status,
      vaccination_records,
      location,
      notes,
      price,
      is_for_sale
    } = req.body;

    if (!pool) {
      // 数据库不可用时返回模拟响应
      return res.json({
        success: true,
        message: '牛只信息更新成功（模拟）',
        data: {
          id: parseInt(id),
          ear_tag,
          breed,
          gender,
          age_months,
          weight_kg,
          health_status,
          location,
          updated_at: new Date().toISOString()
        }
      });
    }

    // 检查牛只是否存在
    const [existing] = await pool.execute(
      'SELECT id, owner_id FROM cattle WHERE id = ? AND deleted_at IS NULL',
      [id]
    );

    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: '牛只不存在',
        code: 'CATTLE_NOT_FOUND'
      });
    }

    // 如果更新耳标，检查是否重复
    if (ear_tag) {
      const [duplicateEarTag] = await pool.execute(
        'SELECT id FROM cattle WHERE ear_tag = ? AND id != ? AND deleted_at IS NULL',
        [ear_tag, id]
      );

      if (duplicateEarTag.length > 0) {
        return res.status(400).json({
          success: false,
          message: '耳标号已存在',
          code: 'EAR_TAG_EXISTS'
        });
      }
    }

    // 数据验证
    if (age_months && (age_months < 0 || age_months > 300)) {
      return res.status(400).json({
        success: false,
        message: '年龄必须在0-300个月之间',
        code: 'INVALID_AGE'
      });
    }

    if (weight_kg && (weight_kg < 0 || weight_kg > 2000)) {
      return res.status(400).json({
        success: false,
        message: '体重必须在0-2000公斤之间',
        code: 'INVALID_WEIGHT'
      });
    }

    if (gender && !['male', 'female'].includes(gender)) {
      return res.status(400).json({
        success: false,
        message: '性别只能是male或female',
        code: 'INVALID_GENDER'
      });
    }

    if (health_status && !['healthy', 'sick', 'quarantine', 'treatment'].includes(health_status)) {
      return res.status(400).json({
        success: false,
        message: '健康状态值无效',
        code: 'INVALID_HEALTH_STATUS'
      });
    }

    // 构建更新字段
    const updateFields = [];
    const updateValues = [];
    
    const fieldMappings = {
      ear_tag,
      breed,
      gender,
      age_months,
      weight_kg,
      health_status,
      vaccination_records: vaccination_records ? JSON.stringify(vaccination_records) : undefined,
      location,
      notes,
      price,
      is_for_sale: is_for_sale !== undefined ? (is_for_sale ? 1 : 0) : undefined
    };

    Object.entries(fieldMappings).forEach(([field, value]) => {
      if (value !== undefined) {
        updateFields.push(`${field} = ?`);
        updateValues.push(value);
      }
    });

    if (updateFields.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的字段',
        code: 'NO_UPDATE_FIELDS'
      });
    }

    updateFields.push('updated_at = CURRENT_TIMESTAMP');
    updateValues.push(id);

    // 执行更新
    await pool.execute(
      `UPDATE cattle SET ${updateFields.join(', ')} WHERE id = ?`,
      updateValues
    );

    // 获取更新后的牛只信息
    const [updated] = await pool.execute(
      `SELECT 
        id, ear_tag, breed, gender, age_months, weight_kg, 
        health_status, vaccination_records, location, notes, 
        price, is_for_sale, owner_id, created_at, updated_at
      FROM cattle WHERE id = ?`,
      [id]
    );

    // 解析vaccination_records JSON字段
    const cattleData = updated[0];
    if (cattleData.vaccination_records) {
      try {
        cattleData.vaccination_records = JSON.parse(cattleData.vaccination_records);
      } catch (e) {
        cattleData.vaccination_records = [];
      }
    }

    res.json({
      success: true,
      message: '牛只信息更新成功',
      data: cattleData
    });
  } catch (error) {
    console.error('更新牛只信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新牛只信息失败',
      code: 'UPDATE_CATTLE_ERROR'
    });
  }
});


// 删除牛只（软删除）
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;

    if (!pool) {
      // 数据库不可用时返回模拟响应
      return res.json({
        success: true,
        message: '牛只删除成功（模拟）'
      });
    }

    // 检查牛只是否存在
    const [existing] = await pool.execute(
      'SELECT id, owner_id FROM cattle WHERE id = ? AND deleted_at IS NULL',
      [id]
    );

    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: '牛只不存在',
        code: 'CATTLE_NOT_FOUND'
      });
    }

    // 软删除牛只
    await pool.execute(
      'UPDATE cattle SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?',
      [id]
    );

    res.json({
      success: true,
      message: '牛只删除成功'
    });
  } catch (error) {
    console.error('删除牛只失败:', error);
    res.status(500).json({
      success: false,
      message: '删除牛只失败',
      code: 'DELETE_CATTLE_ERROR'
    });
  }
});

// 获取牛只统计信息
router.get('/stats/overview', async (req, res) => {
  try {
    const { owner_id } = req.query;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      return res.json({
        success: true,
        data: {
          total_cattle: 1250,
          healthy_cattle: 1180,
          sick_cattle: 45,
          quarantine_cattle: 25,
          for_sale_cattle: 320,
          male_cattle: 580,
          female_cattle: 670,
          avg_age_months: 24.5,
          avg_weight_kg: 485.2
        }
      });
    }

    // 构建查询条件
    let whereClause = 'WHERE deleted_at IS NULL';
    const queryParams = [];

    if (owner_id) {
      whereClause += ' AND owner_id = ?';
      queryParams.push(owner_id);
    }

    // 查询牛只统计信息
    const [stats] = await pool.execute(`
      SELECT 
        COUNT(*) as total_cattle,
        SUM(CASE WHEN health_status = 'healthy' THEN 1 ELSE 0 END) as healthy_cattle,
        SUM(CASE WHEN health_status = 'sick' THEN 1 ELSE 0 END) as sick_cattle,
        SUM(CASE WHEN health_status = 'quarantine' THEN 1 ELSE 0 END) as quarantine_cattle,
        SUM(CASE WHEN is_for_sale = 1 THEN 1 ELSE 0 END) as for_sale_cattle,
        SUM(CASE WHEN gender = 'male' THEN 1 ELSE 0 END) as male_cattle,
        SUM(CASE WHEN gender = 'female' THEN 1 ELSE 0 END) as female_cattle,
        AVG(age_months) as avg_age_months,
        AVG(weight_kg) as avg_weight_kg
      FROM cattle 
      ${whereClause}
    `, queryParams);

    res.json({
      success: true,
      data: stats[0]
    });
  } catch (error) {
    console.error('获取牛只统计信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取牛只统计信息失败',
      code: 'GET_CATTLE_STATS_ERROR'
    });
  }
});
router.post('/batch-import', async (req, res) => {
  try {
    const { cattle_list, owner_id } = req.body;

    if (!cattle_list || !Array.isArray(cattle_list) || cattle_list.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的牛只列表',
        code: 'INVALID_CATTLE_LIST'
      });
    }

    if (!owner_id) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段：owner_id',
        code: 'MISSING_OWNER_ID'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟响应
      return res.status(201).json({
        success: true,
        message: `批量导入${cattle_list.length}头牛只成功（模拟）`,
        data: {
          imported_count: cattle_list.length,
          failed_count: 0,
          success_ids: cattle_list.map((_, index) => index + 1000)
        }
      });
    }

    const results = {
      imported_count: 0,
      failed_count: 0,
      success_ids: [],
      failed_items: []
    };

    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      for (let i = 0; i < cattle_list.length; i++) {
        const cattle = cattle_list[i];
        
        try {
          // 验证必填字段
          if (!cattle.ear_tag || !cattle.breed) {
            results.failed_count++;
            results.failed_items.push({
              index: i,
              ear_tag: cattle.ear_tag,
              error: '缺少必填字段：ear_tag, breed'
            });
            continue;
          }

          // 检查耳标是否重复
          const [existing] = await connection.execute(
            'SELECT id FROM cattle WHERE ear_tag = ? AND deleted_at IS NULL',
            [cattle.ear_tag]
          );

          if (existing.length > 0) {
            results.failed_count++;
            results.failed_items.push({
              index: i,
              ear_tag: cattle.ear_tag,
              error: '耳标号已存在'
            });
            continue;
          }

          // 插入牛只数据
          const insertQuery = `
            INSERT INTO cattle (
              ear_tag, breed, gender, age_months, weight_kg, 
              health_status, vaccination_records, location, notes, 
              price, is_for_sale, owner_id
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
          `;

          const [result] = await connection.execute(insertQuery, [
            cattle.ear_tag,
            cattle.breed,
            cattle.gender || 'male',
            cattle.age_months || 0,
            cattle.weight_kg || 0,
            cattle.health_status || 'healthy',
            cattle.vaccination_records ? JSON.stringify(cattle.vaccination_records) : null,
            cattle.location || '',
            cattle.notes || '',
            cattle.price || null,
            cattle.is_for_sale ? 1 : 0,
            owner_id
          ]);

          results.imported_count++;
          results.success_ids.push(result.insertId);

        } catch (itemError) {
          console.error(`导入第${i}项失败:`, itemError);
          results.failed_count++;
          results.failed_items.push({
            index: i,
            ear_tag: cattle.ear_tag,
            error: itemError.message
          });
        }
      }

      await connection.commit();
      connection.release();

      res.status(201).json({
        success: true,
        message: `批量导入完成，成功${results.imported_count}头，失败${results.failed_count}头`,
        data: results
      });

    } catch (error) {
      await connection.rollback();
      connection.release();
      throw error;
    }

  } catch (error) {
    console.error('批量导入牛只失败:', error);
    res.status(500).json({
      success: false,
      message: '批量导入牛只失败',
      code: 'BATCH_IMPORT_ERROR'
    });
  }
});

// 获取牛只饲养记录（无需认证的测试版本）
router.get('/:id/feeding-records', async (req, res) => {
  try {
    const cattleId = req.params.id;
    const { page = 1, limit = 10, record_type } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      return res.status(500).json({
        success: false,
        message: '数据库连接不可用',
        code: 'DB_UNAVAILABLE'
      });
    }

    // 检查数据库连接
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      return res.status(500).json({
        success: false,
        message: '数据库连接不可用',
        code: 'DB_UNAVAILABLE'
      });
    }

    // 构建查询条件
    let whereClause = 'cattle_id = ?';
    let queryParams = [cattleId];

    if (record_type) {
      whereClause += ' AND record_type = ?';
      queryParams.push(record_type);
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM feeding_records WHERE ${whereClause}`,
      queryParams
    );
    const total = countResult[0].total;

    // 获取饲养记录
    const [records] = await pool.execute(
      `SELECT fr.*, u.real_name as operator_name 
       FROM feeding_records fr 
       LEFT JOIN users u ON fr.operator_id = u.id 
       WHERE ${whereClause} 
       ORDER BY fr.record_date DESC 
       LIMIT ? OFFSET ?`,
      [...queryParams, parseInt(limit), offset]
    );

    res.json({
      success: true,
      data: {
        records,
        pagination: {
          total,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(total / limit)
        }
      }
    });

  } catch (error) {
    console.error('获取饲养记录错误:', error);
    res.status(500).json({
      success: false,
      message: '获取饲养记录失败',
      code: 'GET_FEEDING_RECORDS_ERROR'
    });
  }
});

// 新增饲养记录（无需认证的测试版本）
router.post('/:id/feeding-records', async (req, res) => {
  try {
    const cattleId = req.params.id;
    const {
      record_type,
      feed_type,
      feed_amount,
      vaccine_name,
      treatment_desc,
      medicine_name,
      dosage,
      veterinarian,
      cost,
      record_date,
      notes
    } = req.body;

    // 输入验证
    if (!record_type || !record_date) {
      return res.status(400).json({
        success: false,
        message: '记录类型和记录日期为必填项',
        code: 'MISSING_REQUIRED_FIELDS'
      });
    }

    if (!pool) {
      return res.status(500).json({
        success: false,
        message: '数据库连接不可用',
        code: 'DB_UNAVAILABLE'
      });
    }

    // 检查数据库连接
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      return res.status(500).json({
        success: false,
        message: '数据库连接不可用',
        code: 'DB_UNAVAILABLE'
      });
    }

    // 检查牛只是否存在
    const [cattle] = await pool.execute('SELECT id FROM cattle WHERE id = ?', [cattleId]);
    if (cattle.length === 0) {
      return res.status(404).json({
        success: false,
        message: '牛只不存在',
        code: 'CATTLE_NOT_FOUND'
      });
    }

    // 插入饲养记录
    const [result] = await pool.execute(
      `INSERT INTO feeding_records 
       (cattle_id, record_type, feed_type, feed_amount, vaccine_name, treatment_desc, 
        medicine_name, dosage, veterinarian, cost, record_date, notes, operator_id) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        cattleId, 
        record_type, 
        feed_type || null, 
        feed_amount || null, 
        vaccine_name || null, 
        treatment_desc || null, 
        medicine_name || null, 
        dosage || null, 
        veterinarian || null, 
        cost || null, 
        record_date, 
        notes || null, 
        req.user.userId
      ]
    );

    res.status(201).json({
      success: true,
      message: '饲养记录添加成功',
      data: {
        record_id: result.insertId,
        record_type,
        record_date
      }
    });

  } catch (error) {
    console.error('添加饲养记录错误:', error);
    res.status(500).json({
      success: false,
      message: '添加饲养记录失败',
      code: 'CREATE_FEEDING_RECORD_ERROR'
    });
  }
});

// 获取牛只统计概览（无需认证的测试版本）
router.get('/stats/overview', async (req, res) => {
  try {
    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockStats = {
        total_cattle: 156,
        healthy_cattle: 148,
        sick_cattle: 8,
        by_breed: [
          { breed: '西门塔尔牛', count: 68 },
          { breed: '安格斯牛', count: 45 },
          { breed: '夏洛莱牛', count: 43 }
        ],
        by_status: [
          { status: 'active', count: 142 },
          { status: 'sold', count: 12 },
          { status: 'quarantine', count: 2 }
        ]
      };

      return res.json({
        success: true,
        data: mockStats
      });
    }

    // 检查数据库连接
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      const mockStats = {
        total_cattle: 156,
        healthy_cattle: 148,
        sick_cattle: 8,
        by_breed: [
          { breed: '西门塔尔牛', count: 68 },
          { breed: '安格斯牛', count: 45 },
          { breed: '夏洛莱牛', count: 43 }
        ],
        by_status: [
          { status: 'active', count: 142 },
          { status: 'sold', count: 12 },
          { status: 'quarantine', count: 2 }
        ]
      };

      return res.json({
        success: true,
        message: '数据库连接不可用，返回模拟数据',
        data: mockStats
      });
    }

    // 获取总体统计
    const [totalResult] = await pool.execute('SELECT COUNT(*) as total FROM cattle');
    const [healthyResult] = await pool.execute('SELECT COUNT(*) as healthy FROM cattle WHERE health_status = "healthy"');
    const [sickResult] = await pool.execute('SELECT COUNT(*) as sick FROM cattle WHERE health_status IN ("sick", "quarantine")');

    // 按品种统计
    const [breedStats] = await pool.execute(
      'SELECT breed, COUNT(*) as count FROM cattle GROUP BY breed ORDER BY count DESC LIMIT 10'
    );

    // 按状态统计
    const [statusStats] = await pool.execute(
      'SELECT status, COUNT(*) as count FROM cattle GROUP BY status'
    );

    res.json({
      success: true,
      data: {
        total_cattle: totalResult[0].total,
        healthy_cattle: healthyResult[0].healthy,
        sick_cattle: sickResult[0].sick,
        by_breed: breedStats,
        by_status: statusStats
      }
    });

  } catch (error) {
    console.error('获取牛只统计错误:', error);
    res.status(500).json({
      success: false,
      message: '获取牛只统计失败',
      code: 'GET_CATTLE_STATS_ERROR'
    });
  }
});

module.exports = {
  router,
  setMiddleware
};