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

// ======================================
// 贷款管理相关接口
// ======================================

// 获取贷款申请列表（无需认证的测试版本）
router.get('/loans', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status, 
      loan_type,
      applicant_id,
      search 
    } = req.query;
    const offset = (page - 1) * limit;

    // 直接返回模拟数据（测试版本）
    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)
        }
      }
    });

  } catch (error) {
    console.error('获取贷款申请列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取贷款申请列表失败',
      code: 'GET_LOANS_ERROR'
    });
  }
});

// 获取贷款申请详情（无需认证的测试版本）
router.get('/loans/:id', 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', 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', 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', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status, 
      insurance_type,
      applicant_id,
      search 
    } = req.query;

    // 直接返回模拟数据（测试版本）
    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-02-01 16:20: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)
        }
      }
    });

  } catch (error) {
    console.error('获取保险申请列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取保险申请列表失败',
      code: 'GET_INSURANCE_ERROR'
    });
  }
});

// 获取理赔申请列表（无需认证的测试版本）
router.get('/claims', 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', async (req, res) => {
  try {
    // 直接返回模拟数据
    const mockStats = {
      loans: {
        total_applications: 156,
        approved: 89,
        pending: 34,
        rejected: 33,
        total_amount: 12500000,
        approved_amount: 8900000
      },
      insurance: {
        total_policies: 78,
        active: 45,
        expired: 23,
        pending: 10,
        total_coverage: 15600000,
        total_premium: 468000
      },
      monthly_trends: [
        { month: '2024-01', loans: 12, insurance: 8, amount: 980000 },
        { month: '2024-02', loans: 18, insurance: 12, amount: 1250000 },
        { month: '2024-03', loans: 15, insurance: 9, amount: 1100000 }
      ]
    };

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

module.exports = {
  router,
  setMiddleware
};