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('/farms/supervision', authenticateToken, checkPermission('government_supervision'), async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      region,
      compliance_status,
      inspection_status,
      search
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockFarms = [
        {
          id: 1,
          farm_name: '锡林浩特市第一牧场',
          owner_name: '张三',
          owner_phone: '13900000002',
          region: '锡林浩特市',
          registration_number: 'REG2024001',
          cattle_count: 240,
          farm_area: 150.5,
          compliance_status: 'compliant',
          last_inspection_date: '2024-01-15',
          next_inspection_date: '2024-04-15',
          inspector_name: '政府检查员A',
          compliance_score: 95,
          violation_count: 0,
          environmental_rating: 'A',
          safety_rating: 'A',
          notes: '管理规范，设施完善',
          created_at: '2023-06-15 10:00:00'
        },
        {
          id: 2,
          farm_name: '东乌旗牧场A',
          owner_name: '李四',
          owner_phone: '13900000003',
          region: '东乌旗',
          registration_number: 'REG2024002',
          cattle_count: 180,
          farm_area: 120.3,
          compliance_status: 'warning',
          last_inspection_date: '2024-01-10',
          next_inspection_date: '2024-03-10',
          inspector_name: '政府检查员B',
          compliance_score: 78,
          violation_count: 2,
          environmental_rating: 'B',
          safety_rating: 'A',
          notes: '存在轻微环境问题，需要改进',
          created_at: '2023-08-20 14:30:00'
        },
        {
          id: 3,
          farm_name: '西乌旗生态牧场',
          owner_name: '王五',
          owner_phone: '13900000004',
          region: '西乌旗',
          registration_number: 'REG2024003',
          cattle_count: 320,
          farm_area: 200.8,
          compliance_status: 'excellent',
          last_inspection_date: '2024-01-20',
          next_inspection_date: '2024-07-20',
          inspector_name: '政府检查员C',
          compliance_score: 98,
          violation_count: 0,
          environmental_rating: 'A+',
          safety_rating: 'A+',
          notes: '示范牧场，各项指标优秀',
          created_at: '2023-05-10 09:15:00'
        }
      ];

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

    // 数据库可用时的实际查询逻辑...
    res.json({
      success: true,
      message: '政府监管功能开发中',
      data: { farms: [], pagination: { total: 0, page: parseInt(page), limit: parseInt(limit), pages: 0 } }
    });

  } catch (error) {
    console.error('获取牧场监管信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取牧场监管信息失败',
      error: error.message
    });
  }
});

// 获取检查记录
router.get('/inspections', authenticateToken, checkPermission('government_supervision'), async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      farm_id,
      inspector_id,
      inspection_type,
      result,
      start_date,
      end_date
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockInspections = [
        {
          id: 1,
          farm_id: 1,
          farm_name: '锡林浩特市第一牧场',
          inspector_id: 10,
          inspector_name: '政府检查员A',
          inspection_type: 'routine',
          inspection_date: '2024-01-15',
          result: 'passed',
          score: 95,
          violations: [],
          improvements: [
            '建议加强饲料储存管理',
            '完善消毒记录台账'
          ],
          next_inspection_date: '2024-04-15',
          report_url: '/uploads/inspection_reports/INS001.pdf',
          notes: '整体情况良好，管理规范',
          created_at: '2024-01-15 14:30:00'
        },
        {
          id: 2,
          farm_id: 2,
          farm_name: '东乌旗牧场A',
          inspector_id: 11,
          inspector_name: '政府检查员B',
          inspection_type: 'follow_up',
          inspection_date: '2024-01-10',
          result: 'conditional_pass',
          score: 78,
          violations: [
            {
              type: 'environmental',
              description: '粪污处理不够及时',
              severity: 'minor',
              deadline: '2024-02-10'
            },
            {
              type: 'safety',
              description: '部分围栏需要维修',
              severity: 'minor',
              deadline: '2024-01-25'
            }
          ],
          improvements: [
            '加强粪污处理设施维护',
            '定期检查围栏安全性',
            '建立更完善的清洁制度'
          ],
          next_inspection_date: '2024-03-10',
          report_url: '/uploads/inspection_reports/INS002.pdf',
          notes: '存在轻微问题，需要限期整改',
          created_at: '2024-01-10 16:45:00'
        }
      ];

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

    // 数据库可用时的实际查询逻辑...
    res.json({
      success: true,
      message: '检查记录功能开发中',
      data: { inspections: [], pagination: { total: 0, page: parseInt(page), limit: parseInt(limit), pages: 0 } }
    });

  } catch (error) {
    console.error('获取检查记录失败:', error);
    res.status(500).json({
      success: false,
      message: '获取检查记录失败',
      error: error.message
    });
  }
});

// 创建检查记录
router.post('/inspections', authenticateToken, checkPermission('government_inspection'), async (req, res) => {
  try {
    const {
      farm_id,
      inspection_type,
      inspection_date,
      score,
      result,
      violations,
      improvements,
      next_inspection_date,
      notes
    } = req.body;

    // 验证必需字段
    if (!farm_id || !inspection_type || !inspection_date || !result) {
      return res.status(400).json({
        success: false,
        message: '缺少必需的字段'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟响应
      const mockInspection = {
        id: Math.floor(Math.random() * 1000) + 100,
        farm_id,
        inspector_id: req.user.id,
        inspector_name: req.user.real_name || '检查员',
        inspection_type,
        inspection_date,
        result,
        score,
        violations: violations || [],
        improvements: improvements || [],
        next_inspection_date,
        notes,
        created_at: new Date().toISOString()
      };

      return res.status(201).json({
        success: true,
        message: '检查记录创建成功（模拟数据）',
        data: mockInspection
      });
    }

    // 数据库可用时的实际创建逻辑...
    res.status(201).json({
      success: true,
      message: '检查记录创建功能开发中'
    });

  } catch (error) {
    console.error('创建检查记录失败:', error);
    res.status(500).json({
      success: false,
      message: '创建检查记录失败',
      error: error.message
    });
  }
});

// ======================================
// 质量追溯相关接口
// ======================================

// 获取产品追溯信息
router.get('/traceability/:product_id', authenticateToken, checkPermission('quality_trace'), async (req, res) => {
  try {
    const { product_id } = req.params;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockTraceability = {
        product_id,
        product_name: '优质牛肉',
        batch_number: 'BATCH2024001',
        production_date: '2024-01-20',
        expiry_date: '2024-01-27',
        origin_info: {
          farm_id: 1,
          farm_name: '锡林浩特市第一牧场',
          farmer_name: '张三',
          region: '锡林浩特市',
          coordinates: { lat: 43.946, lng: 116.093 }
        },
        cattle_info: {
          cattle_id: 1,
          tag_number: 'C001',
          breed: '西门塔尔牛',
          birth_date: '2022-01-15',
          slaughter_date: '2024-01-18',
          weight: 450,
          health_records: [
            {
              date: '2023-06-15',
              type: 'vaccination',
              description: '口蹄疫疫苗接种',
              veterinarian: '兽医A'
            },
            {
              date: '2023-12-10',
              type: 'health_check',
              description: '定期健康检查',
              result: '健康状况良好',
              veterinarian: '兽医B'
            }
          ]
        },
        processing_info: {
          slaughterhouse: '锡林郭勒肉类加工厂',
          slaughter_date: '2024-01-18',
          processing_date: '2024-01-19',
          packaging_date: '2024-01-20',
          inspector: '质检员A',
          quality_grade: 'A级',
          certificates: [
            '动物检疫合格证',
            '肉品品质检验合格证',
            '食品安全检测报告'
          ]
        },
        transportation_info: {
          transport_company: '冷链物流A',
          departure_time: '2024-01-20 08:00:00',
          arrival_time: '2024-01-20 14:30:00',
          temperature_records: [
            { time: '08:00', temperature: -2 },
            { time: '10:00', temperature: -1.8 },
            { time: '12:00', temperature: -2.1 },
            { time: '14:00', temperature: -1.9 }
          ],
          driver: '司机A',
          vehicle_number: '蒙H12345'
        },
        retail_info: {
          retailer: '锡林浩特超市A',
          receipt_date: '2024-01-20 15:00:00',
          sale_date: '2024-01-22 10:30:00',
          price: 68.00,
          customer_info: '已匿名化'
        },
        quality_reports: [
          {
            test_date: '2024-01-19',
            test_type: '微生物检测',
            result: '合格',
            lab: '第三方检测机构A'
          },
          {
            test_date: '2024-01-19',
            test_type: '重金属检测',
            result: '合格',
            lab: '第三方检测机构A'
          }
        ]
      };

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

    // 数据库可用时的实际查询逻辑...
    res.json({
      success: true,
      message: '产品追溯功能开发中',
      data: { product_id, message: '开发中' }
    });

  } catch (error) {
    console.error('获取产品追溯信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取产品追溯信息失败',
      error: error.message
    });
  }
});

// ======================================
// 政策法规相关接口
// ======================================

// 获取政策法规列表
router.get('/policies', authenticateToken, checkPermission('policy_view'), async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      category,
      status,
      search
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockPolicies = [
        {
          id: 1,
          title: '锡林郭勒盟畜牧业发展扶持政策',
          category: 'support_policy',
          content_summary: '为促进畜牧业健康发展，对符合条件的养殖户给予资金补贴和技术支持',
          publish_date: '2024-01-01',
          effective_date: '2024-01-01',
          expiry_date: '2024-12-31',
          status: 'active',
          authority: '锡林郭勒盟农牧局',
          document_url: '/uploads/policies/policy001.pdf',
          created_at: '2024-01-01 10:00:00'
        },
        {
          id: 2,
          title: '动物疫病防控管理办法',
          category: 'regulation',
          content_summary: '规范动物疫病防控工作，确保畜牧业生产安全和公共卫生安全',
          publish_date: '2023-12-15',
          effective_date: '2024-01-01',
          expiry_date: null,
          status: 'active',
          authority: '锡林郭勒盟兽医局',
          document_url: '/uploads/policies/policy002.pdf',
          created_at: '2023-12-15 14:30:00'
        },
        {
          id: 3,
          title: '草原生态保护补助奖励政策',
          category: 'subsidy',
          content_summary: '对实施草原禁牧、草畜平衡的牧户给予生态保护补助奖励',
          publish_date: '2024-01-10',
          effective_date: '2024-01-15',
          expiry_date: '2024-12-31',
          status: 'active',
          authority: '锡林郭勒盟林草局',
          document_url: '/uploads/policies/policy003.pdf',
          created_at: '2024-01-10 09:15:00'
        }
      ];

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

    // 数据库可用时的实际查询逻辑...
    res.json({
      success: true,
      message: '政策法规功能开发中',
      data: { policies: [], pagination: { total: 0, page: parseInt(page), limit: parseInt(limit), pages: 0 } }
    });

  } catch (error) {
    console.error('获取政策法规列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取政策法规列表失败',
      error: error.message
    });
  }
});

// ======================================
// 统计报告相关接口
// ======================================

// 获取监管统计数据
router.get('/statistics', authenticateToken, checkPermission('government_statistics'), async (req, res) => {
  try {
    const { period = 'month', region } = req.query;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockStats = {
        overview: {
          total_farms: 156,
          total_cattle: 12850,
          compliant_farms: 142,
          warning_farms: 11,
          violation_farms: 3,
          compliance_rate: 91.0
        },
        regional_distribution: {
          '锡林浩特市': { farms: 45, cattle: 4200, compliance_rate: 93.3 },
          '东乌旗': { farms: 38, cattle: 3100, compliance_rate: 89.5 },
          '西乌旗': { farms: 42, cattle: 3800, compliance_rate: 92.9 },
          '阿巴嘎旗': { farms: 31, cattle: 1750, compliance_rate: 87.1 }
        },
        inspection_summary: {
          total_inspections: 89,
          passed: 76,
          conditional_pass: 8,
          failed: 5,
          pending: 0
        },
        violation_categories: {
          environmental: 15,
          safety: 8,
          health: 5,
          documentation: 12
        },
        monthly_trend: [
          { month: '2023-11', compliance_rate: 88.5, inspections: 28 },
          { month: '2023-12', compliance_rate: 89.2, inspections: 32 },
          { month: '2024-01', compliance_rate: 91.0, inspections: 29 }
        ]
      };

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

    // 数据库可用时的实际统计查询逻辑...
    res.json({
      success: true,
      message: '监管统计功能开发中',
      data: { overview: { total_farms: 0, total_cattle: 0 } }
    });

  } catch (error) {
    console.error('获取监管统计数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取监管统计数据失败',
      error: error.message
    });
  }
});

// 生成监管报告
router.post('/reports', authenticateToken, checkPermission('government_report'), async (req, res) => {
  try {
    const {
      report_type,
      period,
      region,
      start_date,
      end_date,
      format = 'pdf'
    } = req.body;

    // 验证必需字段
    if (!report_type || !period) {
      return res.status(400).json({
        success: false,
        message: '缺少必需的字段'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟响应
      const mockReport = {
        id: Math.floor(Math.random() * 1000) + 100,
        report_type,
        period,
        region,
        start_date,
        end_date,
        format,
        status: 'generating',
        created_by: req.user.id,
        created_at: new Date().toISOString(),
        download_url: null,
        estimated_completion: new Date(Date.now() + 5 * 60 * 1000).toISOString() // 5分钟后
      };

      return res.status(201).json({
        success: true,
        message: '报告生成任务已创建（模拟数据）',
        data: mockReport
      });
    }

    // 数据库可用时的实际报告生成逻辑...
    res.status(201).json({
      success: true,
      message: '报告生成功能开发中'
    });

  } catch (error) {
    console.error('生成监管报告失败:', error);
    res.status(500).json({
      success: false,
      message: '生成监管报告失败',
      error: error.message
    });
  }
});

// 导出模块
module.exports = {
  router,
  setMiddleware
};