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('/loans', authenticateToken, checkPermission('loan_manage'), async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status, 
      loan_type,
      applicant_id,
      search 
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockLoans = [
        {
          id: 1,
          applicant_id: 2,
          applicant_name: '张三',
          loan_type: 'cattle',
          loan_amount: 500000.00,
          interest_rate: 0.0450,
          term_months: 24,
          status: 'approved',
          purpose: '购买西门塔尔牛30头，用于扩大养殖规模',
          approved_amount: 450000.00,
          approved_date: '2024-01-15 10:30:00',
          disbursement_date: '2024-01-20 14:00:00',
          created_at: '2024-01-10 09:00:00'
        },
        {
          id: 2,
          applicant_id: 3,
          applicant_name: '李四',
          loan_type: 'equipment',
          loan_amount: 300000.00,
          interest_rate: 0.0520,
          term_months: 36,
          status: 'under_review',
          purpose: '购买饲料加工设备和自动饮水系统',
          approved_amount: null,
          approved_date: null,
          disbursement_date: null,
          created_at: '2024-01-18 16:45:00'
        },
        {
          id: 3,
          applicant_id: 4,
          applicant_name: '王五',
          loan_type: 'operating',
          loan_amount: 200000.00,
          interest_rate: 0.0480,
          term_months: 12,
          status: 'disbursed',
          purpose: '购买饲料和兽药，维持日常运营',
          approved_amount: 200000.00,
          approved_date: '2024-01-12 11:20:00',
          disbursement_date: '2024-01-16 09:30:00',
          created_at: '2024-01-08 14:15:00'
        }
      ];

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

    // 数据库可用时的实际查询逻辑
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      const mockLoans = [
        {
          id: 1,
          applicant_name: '张三',
          loan_type: 'cattle',
          loan_amount: 500000.00,
          status: 'approved',
          purpose: '购买西门塔尔牛30头',
          created_at: '2024-01-10 09:00:00'
        }
      ];

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

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

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

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

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

    if (search) {
      whereClause += ' AND (u.real_name LIKE ? OR la.purpose LIKE ?)';
      const searchTerm = `%${search}%`;
      queryParams.push(searchTerm, searchTerm);
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total 
       FROM loan_applications la 
       LEFT JOIN users u ON la.applicant_id = u.id 
       WHERE ${whereClause}`,
      queryParams
    );
    const total = countResult[0].total;

    // 获取贷款申请列表
    const [loans] = await pool.execute(
      `SELECT la.*, u.real_name as applicant_name, u.phone as applicant_phone,
              rv.real_name as reviewer_name
       FROM loan_applications la 
       LEFT JOIN users u ON la.applicant_id = u.id 
       LEFT JOIN users rv ON la.reviewer_id = rv.id
       WHERE ${whereClause} 
       ORDER BY la.created_at DESC 
       LIMIT ? OFFSET ?`,
      [...queryParams, parseInt(limit), offset]
    );

    res.json({
      success: true,
      data: {
        loans,
        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_LOANS_ERROR'
    });
  }
});

// 获取贷款申请详情
router.get('/loans/:id', authenticateToken, checkPermission('loan_manage'), async (req, res) => {
  try {
    const loanId = 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 [loans] = await pool.execute(
      `SELECT la.*, u.real_name as applicant_name, u.phone as applicant_phone, u.email as applicant_email,
              rv.real_name as reviewer_name
       FROM loan_applications la 
       LEFT JOIN users u ON la.applicant_id = u.id 
       LEFT JOIN users rv ON la.reviewer_id = rv.id
       WHERE la.id = ?`,
      [loanId]
    );

    if (loans.length === 0) {
      return res.status(404).json({
        success: false,
        message: '贷款申请不存在',
        code: 'LOAN_NOT_FOUND'
      });
    }

    const loan = loans[0];

    // 如果有质押牛只，获取牛只信息
    let cattleInfo = [];
    if (loan.cattle_ids) {
      try {
        const cattleIds = JSON.parse(loan.cattle_ids);
        if (cattleIds && cattleIds.length > 0) {
          const [cattle] = await pool.execute(
            `SELECT id, ear_tag, name, breed, weight, health_status 
             FROM cattle 
             WHERE id IN (${cattleIds.map(() => '?').join(',')})`,
            cattleIds
          );
          cattleInfo = cattle;
        }
      } catch (parseError) {
        console.warn('解析质押牛只ID失败:', parseError);
      }
    }

    res.json({
      success: true,
      data: {
        loan,
        cattle_collateral: cattleInfo
      }
    });

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

// 创建贷款申请
router.post('/loans', authenticateToken, checkPermission('loan_manage'), async (req, res) => {
  try {
    const {
      applicant_id,
      loan_type,
      cattle_ids,
      loan_amount,
      interest_rate,
      term_months,
      purpose,
      repayment_method,
      guarantee_type
    } = req.body;

    // 输入验证
    if (!applicant_id || !loan_type || !loan_amount || !purpose) {
      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 [users] = await pool.execute('SELECT id FROM users WHERE id = ?', [applicant_id]);
    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '申请人不存在',
        code: 'APPLICANT_NOT_FOUND'
      });
    }

    // 插入贷款申请
    const [result] = await pool.execute(
      `INSERT INTO loan_applications 
       (applicant_id, loan_type, cattle_ids, loan_amount, interest_rate, term_months, 
        purpose, repayment_method, guarantee_type, status) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'submitted')`,
      [
        applicant_id,
        loan_type,
        cattle_ids ? JSON.stringify(cattle_ids) : null,
        loan_amount,
        interest_rate || null,
        term_months || null,
        purpose,
        repayment_method || null,
        guarantee_type || null
      ]
    );

    res.status(201).json({
      success: true,
      message: '贷款申请创建成功',
      data: {
        loan_id: result.insertId,
        applicant_id,
        loan_amount,
        status: 'submitted'
      }
    });

  } catch (error) {
    console.error('创建贷款申请错误:', error);
    res.status(500).json({
      success: false,
      message: '创建贷款申请失败',
      code: 'CREATE_LOAN_ERROR'
    });
  }
});

// 审批贷款申请
router.put('/loans/:id/review', authenticateToken, checkPermission('loan_manage'), async (req, res) => {
  try {
    const loanId = req.params.id;
    const {
      status,
      approved_amount,
      review_notes
    } = req.body;

    // 输入验证
    if (!status || !['approved', 'rejected'].includes(status)) {
      return res.status(400).json({
        success: false,
        message: '审批状态必须是 approved 或 rejected',
        code: 'INVALID_STATUS'
      });
    }

    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 [loans] = await pool.execute('SELECT id, status FROM loan_applications WHERE id = ?', [loanId]);
    if (loans.length === 0) {
      return res.status(404).json({
        success: false,
        message: '贷款申请不存在',
        code: 'LOAN_NOT_FOUND'
      });
    }

    // 检查当前状态是否允许审批
    if (!['submitted', 'under_review'].includes(loans[0].status)) {
      return res.status(400).json({
        success: false,
        message: '当前状态不允许审批',
        code: 'INVALID_CURRENT_STATUS'
      });
    }

    // 更新审批结果
    await pool.execute(
      `UPDATE loan_applications 
       SET status = ?, approved_amount = ?, review_notes = ?, reviewer_id = ?, approved_date = CURRENT_TIMESTAMP 
       WHERE id = ?`,
      [status, approved_amount || null, review_notes || null, req.user.userId, loanId]
    );

    res.json({
      success: true,
      message: `贷款申请${status === 'approved' ? '批准' : '拒绝'}成功`,
      data: {
        loan_id: loanId,
        status,
        approved_amount: approved_amount || null
      }
    });

  } catch (error) {
    console.error('审批贷款申请错误:', error);
    res.status(500).json({
      success: false,
      message: '审批贷款申请失败',
      code: 'REVIEW_LOAN_ERROR'
    });
  }
});

// ======================================
// 保险管理相关接口
// ======================================

// 获取保险申请列表
router.get('/insurance', authenticateToken, checkPermission('insurance_manage'), async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status, 
      insurance_type,
      applicant_id,
      search 
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockInsurance = [
        {
          id: 1,
          applicant_id: 2,
          applicant_name: '张三',
          insurance_type: 'cattle_death',
          policy_number: 'INS202401001',
          insured_amount: 300000.00,
          premium: 12000.00,
          start_date: '2024-02-01',
          end_date: '2025-01-31',
          status: 'active',
          created_at: '2024-01-20 10:00:00'
        },
        {
          id: 2,
          applicant_id: 3,
          applicant_name: '李四',
          insurance_type: 'cattle_health',
          policy_number: 'INS202401002',
          insured_amount: 250000.00,
          premium: 8750.00,
          start_date: '2024-02-15',
          end_date: '2025-02-14',
          status: 'underwriting',
          created_at: '2024-01-25 14:30:00'
        },
        {
          id: 3,
          applicant_id: 4,
          applicant_name: '王五',
          insurance_type: 'cattle_theft',
          policy_number: null,
          insured_amount: 180000.00,
          premium: 5400.00,
          start_date: null,
          end_date: null,
          status: 'applied',
          created_at: '2024-01-28 09:15:00'
        }
      ];

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

    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      const mockInsurance = [
        {
          id: 1,
          applicant_name: '张三',
          insurance_type: 'cattle_death',
          insured_amount: 300000.00,
          status: 'active',
          created_at: '2024-01-20 10:00:00'
        }
      ];

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

    // 实际数据库查询逻辑
    let whereClause = '1=1';
    let queryParams = [];

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

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

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

    if (search) {
      whereClause += ' AND (u.real_name LIKE ? OR ia.policy_number LIKE ?)';
      const searchTerm = `%${search}%`;
      queryParams.push(searchTerm, searchTerm);
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total 
       FROM insurance_applications ia 
       LEFT JOIN users u ON ia.applicant_id = u.id 
       WHERE ${whereClause}`,
      queryParams
    );
    const total = countResult[0].total;

    // 获取保险申请列表
    const [insurance] = await pool.execute(
      `SELECT ia.*, u.real_name as applicant_name, u.phone as applicant_phone,
              uw.real_name as underwriter_name
       FROM insurance_applications ia 
       LEFT JOIN users u ON ia.applicant_id = u.id 
       LEFT JOIN users uw ON ia.underwriter_id = uw.id
       WHERE ${whereClause} 
       ORDER BY ia.created_at DESC 
       LIMIT ? OFFSET ?`,
      [...queryParams, parseInt(limit), offset]
    );

    res.json({
      success: true,
      data: {
        insurance,
        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_INSURANCE_ERROR'
    });
  }
});

// 获取理赔申请列表
router.get('/claims', authenticateToken, checkPermission('insurance_manage'), async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status, 
      incident_type,
      insurance_id 
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockClaims = [
        {
          id: 1,
          insurance_id: 1,
          policy_number: 'INS202401001',
          applicant_name: '张三',
          claim_amount: 50000.00,
          incident_date: '2024-01-30',
          incident_type: 'illness',
          description: '牛只突发疾病，经兽医诊断为传染性疾病',
          status: 'under_review',
          submitted_at: '2024-02-01 09:30:00'
        },
        {
          id: 2,
          insurance_id: 1,
          policy_number: 'INS202401001',
          applicant_name: '张三',
          claim_amount: 25000.00,
          incident_date: '2024-02-10',
          incident_type: 'accident',
          description: '牛只在放牧过程中意外受伤',
          status: 'approved',
          approved_amount: 22000.00,
          submitted_at: '2024-02-11 14:20:00',
          approved_at: '2024-02-15 10:45:00'
        }
      ];

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

    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      const mockClaims = [
        {
          id: 1,
          applicant_name: '张三',
          claim_amount: 50000.00,
          incident_type: 'illness',
          status: 'under_review'
        }
      ];

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

    // 实际数据库查询
    let whereClause = '1=1';
    let queryParams = [];

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

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

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

    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total 
       FROM claims c 
       LEFT JOIN insurance_applications ia ON c.insurance_id = ia.id 
       LEFT JOIN users u ON c.applicant_id = u.id 
       WHERE ${whereClause}`,
      queryParams
    );
    const total = countResult[0].total;

    const [claims] = await pool.execute(
      `SELECT c.*, ia.policy_number, u.real_name as applicant_name,
              rv.real_name as reviewer_name
       FROM claims c 
       LEFT JOIN insurance_applications ia ON c.insurance_id = ia.id 
       LEFT JOIN users u ON c.applicant_id = u.id 
       LEFT JOIN users rv ON c.reviewer_id = rv.id
       WHERE ${whereClause} 
       ORDER BY c.submitted_at DESC 
       LIMIT ? OFFSET ?`,
      [...queryParams, parseInt(limit), offset]
    );

    res.json({
      success: true,
      data: {
        claims,
        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_CLAIMS_ERROR'
    });
  }
});

// 获取金融服务统计信息
router.get('/stats/overview', authenticateToken, checkPermission('data_view'), async (req, res) => {
  try {
    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockStats = {
        loans: {
          total_applications: 156,
          approved_loans: 89,
          pending_review: 23,
          total_amount: 45600000.00,
          approved_amount: 32800000.00
        },
        insurance: {
          total_policies: 234,
          active_policies: 198,
          total_coverage: 78500000.00,
          total_claims: 45,
          paid_claims: 32,
          pending_claims: 8
        },
        risk_analysis: {
          default_rate: 0.025,
          claim_rate: 0.165,
          average_loan_amount: 368539.32,
          average_premium: 15420.50
        }
      };

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

    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      const mockStats = {
        loans: {
          total_applications: 156,
          approved_loans: 89,
          pending_review: 23,
          total_amount: 45600000.00,
          approved_amount: 32800000.00
        },
        insurance: {
          total_policies: 234,
          active_policies: 198,
          total_coverage: 78500000.00
        }
      };

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

    // 贷款统计
    const [loanStats] = await pool.execute(`
      SELECT 
        COUNT(*) as total_applications,
        COUNT(CASE WHEN status = 'approved' THEN 1 END) as approved_loans,
        COUNT(CASE WHEN status IN ('submitted', 'under_review') THEN 1 END) as pending_review,
        SUM(loan_amount) as total_amount,
        SUM(CASE WHEN status = 'approved' THEN approved_amount ELSE 0 END) as approved_amount
      FROM loan_applications
    `);

    // 保险统计
    const [insuranceStats] = await pool.execute(`
      SELECT 
        COUNT(*) as total_policies,
        COUNT(CASE WHEN status = 'active' THEN 1 END) as active_policies,
        SUM(insured_amount) as total_coverage
      FROM insurance_applications
    `);

    // 理赔统计
    const [claimStats] = await pool.execute(`
      SELECT 
        COUNT(*) as total_claims,
        COUNT(CASE WHEN status = 'paid' THEN 1 END) as paid_claims,
        COUNT(CASE WHEN status IN ('submitted', 'under_review') THEN 1 END) as pending_claims
      FROM claims
    `);

    res.json({
      success: true,
      data: {
        loans: loanStats[0],
        insurance: {
          ...insuranceStats[0],
          ...claimStats[0]
        },
        risk_analysis: {
          default_rate: 0.025, // 这里可以添加更复杂的计算逻辑
          claim_rate: claimStats[0].total_claims / (insuranceStats[0].total_policies || 1),
          average_loan_amount: loanStats[0].total_amount / (loanStats[0].total_applications || 1),
          average_premium: 15420.50 // 可以从数据库计算
        }
      }
    });

  } catch (error) {
    console.error('获取金融服务统计错误:', error);
    res.status(500).json({
      success: false,
      message: '获取金融服务统计失败',
      code: 'GET_FINANCE_STATS_ERROR'
    });
  }
});

module.exports = {
  router,
  setMiddleware
};