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

// 中间件将在服务器启动时设置
let authenticateToken = (req, res, next) => {
  return res.status(500).json({
    success: false,
    message: '认证中间件未初始化',
    code: 'AUTH_NOT_INITIALIZED'
  });
};

let checkPermission = (permission) => {
  return (req, res, next) => {
    return res.status(500).json({
      success: false,
      message: '权限中间件未初始化',
      code: 'PERMISSION_NOT_INITIALIZED'
    });
  };
};

let pool = null;

// 设置中间件和数据库连接（从主服务器导入）
function setMiddleware(auth, permission, dbPool) {
  authenticateToken = auth;
  checkPermission = permission;
  pool = dbPool;
}

// 获取牛只列表
router.get('/', authenticateToken, checkPermission('cattle_manage'), 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', authenticateToken, checkPermission('cattle_manage'), 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('/', authenticateToken, checkPermission('cattle_manage'), async (req, res) => {
  try {
    const {
      ear_tag,
      name,
      breed,
      gender,
      birth_date,
      color,
      weight,
      owner_id,
      farm_location
    } = req.body;

    // 输入验证
    if (!ear_tag || !breed || !gender) {
      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 [existingCattle] = await pool.execute(
      'SELECT id FROM cattle WHERE ear_tag = ?',
      [ear_tag]
    );

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

    // 插入新牛只
    const [result] = await pool.execute(
      `INSERT INTO cattle (ear_tag, name, breed, gender, birth_date, color, weight, owner_id, farm_location) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [ear_tag, name || null, breed, gender, birth_date || null, color || null, weight || null, owner_id || null, farm_location || null]
    );

    res.status(201).json({
      success: true,
      message: '牛只档案创建成功',
      data: {
        cattle_id: result.insertId,
        ear_tag,
        name,
        breed
      }
    });

  } catch (error) {
    console.error('创建牛只档案错误:', error);
    res.status(500).json({
      success: false,
      message: '创建牛只档案失败',
      code: 'CREATE_CATTLE_ERROR'
    });
  }
});

// 更新牛只信息
router.put('/:id', authenticateToken, checkPermission('cattle_manage'), async (req, res) => {
  try {
    const cattleId = req.params.id;
    const {
      name,
      color,
      weight,
      health_status,
      status,
      farm_location,
      owner_id
    } = req.body;

    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'
      });
    }

    // 更新牛只信息
    await pool.execute(
      `UPDATE cattle 
       SET name = ?, color = ?, weight = ?, health_status = ?, status = ?, farm_location = ?, owner_id = ? 
       WHERE id = ?`,
      [
        name || null, 
        color || null, 
        weight || null, 
        health_status || 'healthy', 
        status || 'active', 
        farm_location || null, 
        owner_id || null, 
        cattleId
      ]
    );

    res.json({
      success: true,
      message: '牛只信息更新成功'
    });

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

// 删除牛只档案
router.delete('/:id', authenticateToken, checkPermission('cattle_manage'), 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 id FROM cattle WHERE id = ?', [cattleId]);
    if (cattle.length === 0) {
      return res.status(404).json({
        success: false,
        message: '牛只不存在',
        code: 'CATTLE_NOT_FOUND'
      });
    }

    // 删除牛只（级联删除相关记录）
    await pool.execute('DELETE FROM cattle WHERE id = ?', [cattleId]);

    res.json({
      success: true,
      message: '牛只档案删除成功'
    });

  } catch (error) {
    console.error('删除牛只档案错误:', error);
    res.status(500).json({
      success: false,
      message: '删除牛只档案失败',
      code: 'DELETE_CATTLE_ERROR'
    });
  }
});

// 获取饲养记录
router.get('/:id/feeding-records', authenticateToken, checkPermission('cattle_manage'), 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', authenticateToken, checkPermission('cattle_manage'), 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', authenticateToken, checkPermission('data_view'), 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
};