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('/transactions', authenticateToken, checkPermission('transaction_view'), async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status, 
      transaction_type,
      buyer_id,
      seller_id,
      search,
      start_date,
      end_date
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockTransactions = [
        {
          id: 1,
          transaction_type: 'cattle_sale',
          buyer_id: 3,
          seller_id: 2,
          buyer_name: '李四',
          seller_name: '张三',
          cattle_ids: '1,2,3',
          cattle_count: 3,
          unit_price: 15000.00,
          total_amount: 45000.00,
          status: 'completed',
          payment_method: 'bank_transfer',
          delivery_method: 'pickup',
          delivery_address: '锡林浩特市郊区牧场',
          delivery_date: '2024-01-25 09:00:00',
          notes: '优质西门塔尔牛，健康状况良好',
          created_at: '2024-01-20 14:30:00',
          updated_at: '2024-01-25 10:15:00'
        },
        {
          id: 2,
          transaction_type: 'feed_purchase',
          buyer_id: 2,
          seller_id: 5,
          buyer_name: '张三',
          seller_name: '饲料供应商A',
          product_name: '优质牧草饲料',
          quantity: 5000,
          unit: 'kg',
          unit_price: 3.50,
          total_amount: 17500.00,
          status: 'pending',
          payment_method: 'cash',
          delivery_method: 'delivery',
          delivery_address: '张三牧场',
          delivery_date: '2024-01-28 08:00:00',
          notes: '定期饲料采购',
          created_at: '2024-01-22 16:45:00',
          updated_at: '2024-01-22 16:45:00'
        },
        {
          id: 3,
          transaction_type: 'equipment_sale',
          buyer_id: 4,
          seller_id: 6,
          buyer_name: '王五',
          seller_name: '设备供应商B',
          product_name: '自动饮水设备',
          quantity: 2,
          unit: '套',
          unit_price: 8500.00,
          total_amount: 17000.00,
          status: 'in_progress',
          payment_method: 'installment',
          delivery_method: 'installation',
          delivery_address: '王五牧场',
          delivery_date: '2024-01-30 10:00:00',
          notes: '包安装调试',
          created_at: '2024-01-19 11:20:00',
          updated_at: '2024-01-24 15:30:00'
        }
      ];

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

    // 数据库可用时的实际查询逻辑
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      const mockTransactions = [
        {
          id: 1,
          transaction_type: 'cattle_sale',
          buyer_name: '李四',
          seller_name: '张三',
          total_amount: 45000.00,
          status: 'completed',
          created_at: '2024-01-20 14:30:00'
        }
      ];

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

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

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

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

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

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

    if (start_date) {
      whereClause += ' AND t.created_at >= ?';
      queryParams.push(start_date);
    }

    if (end_date) {
      whereClause += ' AND t.created_at <= ?';
      queryParams.push(end_date);
    }

    if (search) {
      whereClause += ' AND (buyer.real_name LIKE ? OR seller.real_name LIKE ? OR t.notes LIKE ?)';
      const searchTerm = `%${search}%`;
      queryParams.push(searchTerm, searchTerm, searchTerm);
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total 
       FROM transactions t 
       LEFT JOIN users buyer ON t.buyer_id = buyer.id 
       LEFT JOIN users seller ON t.seller_id = seller.id 
       WHERE ${whereClause}`,
      queryParams
    );
    const total = countResult[0].total;

    // 获取交易记录列表
    const [transactions] = await pool.execute(
      `SELECT t.*, 
              buyer.real_name as buyer_name, buyer.phone as buyer_phone,
              seller.real_name as seller_name, seller.phone as seller_phone
       FROM transactions t 
       LEFT JOIN users buyer ON t.buyer_id = buyer.id 
       LEFT JOIN users seller ON t.seller_id = seller.id
       WHERE ${whereClause} 
       ORDER BY t.created_at DESC 
       LIMIT ? OFFSET ?`,
      [...queryParams, parseInt(limit), offset]
    );

    res.json({
      success: true,
      data: {
        transactions,
        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: '获取交易记录失败',
      error: error.message
    });
  }
});

// 获取交易详情
router.get('/transactions/:id', authenticateToken, checkPermission('transaction_view'), async (req, res) => {
  try {
    const { id } = req.params;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockTransaction = {
        id: parseInt(id),
        transaction_type: 'cattle_sale',
        buyer_id: 3,
        seller_id: 2,
        buyer_name: '李四',
        seller_name: '张三',
        buyer_phone: '13900000003',
        seller_phone: '13900000002',
        cattle_ids: '1,2,3',
        cattle_count: 3,
        cattle_details: [
          { id: 1, tag_number: 'C001', breed: '西门塔尔牛', age_months: 24, weight: 450, price: 15000 },
          { id: 2, tag_number: 'C002', breed: '西门塔尔牛', age_months: 30, weight: 520, price: 15000 },
          { id: 3, tag_number: 'C003', breed: '安格斯牛', age_months: 28, weight: 480, price: 15000 }
        ],
        unit_price: 15000.00,
        total_amount: 45000.00,
        status: 'completed',
        payment_method: 'bank_transfer',
        payment_status: 'paid',
        delivery_method: 'pickup',
        delivery_address: '锡林浩特市郊区牧场',
        delivery_date: '2024-01-25 09:00:00',
        delivery_status: 'delivered',
        contract_id: 'CON001',
        contract_url: '/uploads/contracts/CON001.pdf',
        notes: '优质西门塔尔牛，健康状况良好，已完成检疫',
        created_at: '2024-01-20 14:30:00',
        updated_at: '2024-01-25 10:15:00'
      };

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

    // 数据库可用时的实际查询逻辑
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      return res.json({
        success: true,
        message: '数据库连接不可用，返回模拟数据',
        data: {
          id: parseInt(id),
          transaction_type: 'cattle_sale',
          buyer_name: '李四',
          seller_name: '张三',
          total_amount: 45000.00,
          status: 'completed'
        }
      });
    }

    // 获取交易详情
    const [transactions] = await pool.execute(
      `SELECT t.*, 
              buyer.real_name as buyer_name, buyer.phone as buyer_phone, buyer.email as buyer_email,
              seller.real_name as seller_name, seller.phone as seller_phone, seller.email as seller_email,
              c.contract_number, c.contract_url
       FROM transactions t 
       LEFT JOIN users buyer ON t.buyer_id = buyer.id 
       LEFT JOIN users seller ON t.seller_id = seller.id
       LEFT JOIN contracts c ON t.contract_id = c.id
       WHERE t.id = ?`,
      [id]
    );

    if (transactions.length === 0) {
      return res.status(404).json({
        success: false,
        message: '交易记录不存在'
      });
    }

    const transaction = transactions[0];

    // 如果是牛只交易，获取相关牛只信息
    if (transaction.transaction_type === 'cattle_sale' && transaction.cattle_ids) {
      const cattleIds = transaction.cattle_ids.split(',');
      const [cattleList] = await pool.execute(
        `SELECT id, tag_number, breed, age_months, weight, health_status 
         FROM cattle WHERE id IN (${cattleIds.map(() => '?').join(',')})`,
        cattleIds
      );
      transaction.cattle_details = cattleList;
    }

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

  } catch (error) {
    console.error('获取交易详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取交易详情失败',
      error: error.message
    });
  }
});

// 创建新交易
router.post('/transactions', authenticateToken, checkPermission('transaction_create'), async (req, res) => {
  try {
    const {
      transaction_type,
      buyer_id,
      seller_id,
      cattle_ids,
      product_name,
      quantity,
      unit,
      unit_price,
      total_amount,
      payment_method,
      delivery_method,
      delivery_address,
      delivery_date,
      notes
    } = req.body;

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

    if (!pool) {
      // 数据库不可用时返回模拟响应
      const mockTransaction = {
        id: Math.floor(Math.random() * 1000) + 100,
        transaction_type,
        buyer_id,
        seller_id,
        total_amount,
        status: 'pending',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };

      return res.status(201).json({
        success: true,
        message: '交易创建成功（模拟数据）',
        data: mockTransaction
      });
    }

    // 数据库可用时的实际创建逻辑
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      return res.status(201).json({
        success: true,
        message: '数据库连接不可用，模拟创建成功',
        data: {
          id: Math.floor(Math.random() * 1000) + 100,
          transaction_type,
          status: 'pending',
          created_at: new Date().toISOString()
        }
      });
    }

    // 验证买家和卖家是否存在
    const [buyerCheck] = await pool.execute('SELECT id FROM users WHERE id = ?', [buyer_id]);
    const [sellerCheck] = await pool.execute('SELECT id FROM users WHERE id = ?', [seller_id]);

    if (buyerCheck.length === 0) {
      return res.status(400).json({
        success: false,
        message: '买家不存在'
      });
    }

    if (sellerCheck.length === 0) {
      return res.status(400).json({
        success: false,
        message: '卖家不存在'
      });
    }

    // 创建交易记录
    const [result] = await pool.execute(
      `INSERT INTO transactions (
        transaction_type, buyer_id, seller_id, cattle_ids, product_name,
        quantity, unit, unit_price, total_amount, payment_method,
        delivery_method, delivery_address, delivery_date, notes, status
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')`,
      [
        transaction_type, buyer_id, seller_id, cattle_ids, product_name,
        quantity, unit, unit_price, total_amount, payment_method,
        delivery_method, delivery_address, delivery_date, notes
      ]
    );

    // 获取创建的交易记录
    const [newTransaction] = await pool.execute(
      `SELECT t.*, 
              buyer.real_name as buyer_name,
              seller.real_name as seller_name
       FROM transactions t 
       LEFT JOIN users buyer ON t.buyer_id = buyer.id 
       LEFT JOIN users seller ON t.seller_id = seller.id
       WHERE t.id = ?`,
      [result.insertId]
    );

    res.status(201).json({
      success: true,
      message: '交易创建成功',
      data: newTransaction[0]
    });

  } catch (error) {
    console.error('创建交易失败:', error);
    res.status(500).json({
      success: false,
      message: '创建交易失败',
      error: error.message
    });
  }
});

// 更新交易状态
router.put('/transactions/:id/status', authenticateToken, checkPermission('transaction_manage'), async (req, res) => {
  try {
    const { id } = req.params;
    const { status, notes } = req.body;

    if (!status) {
      return res.status(400).json({
        success: false,
        message: '状态不能为空'
      });
    }

    const validStatuses = ['pending', 'confirmed', 'in_progress', 'completed', 'cancelled', 'refunded'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的状态值'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟响应
      return res.json({
        success: true,
        message: '交易状态更新成功（模拟数据）',
        data: {
          id: parseInt(id),
          status,
          updated_at: new Date().toISOString()
        }
      });
    }

    // 数据库可用时的实际更新逻辑
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      return res.json({
        success: true,
        message: '数据库连接不可用，模拟更新成功',
        data: {
          id: parseInt(id),
          status,
          updated_at: new Date().toISOString()
        }
      });
    }

    // 检查交易是否存在
    const [existingTransaction] = await pool.execute(
      'SELECT id, status FROM transactions WHERE id = ?',
      [id]
    );

    if (existingTransaction.length === 0) {
      return res.status(404).json({
        success: false,
        message: '交易记录不存在'
      });
    }

    // 更新交易状态
    const updateData = [status, id];
    let updateQuery = 'UPDATE transactions SET status = ?, updated_at = CURRENT_TIMESTAMP';
    
    if (notes) {
      updateQuery += ', notes = ?';
      updateData.splice(1, 0, notes);
    }
    
    updateQuery += ' WHERE id = ?';

    await pool.execute(updateQuery, updateData);

    // 获取更新后的交易记录
    const [updatedTransaction] = await pool.execute(
      `SELECT t.*, 
              buyer.real_name as buyer_name,
              seller.real_name as seller_name
       FROM transactions t 
       LEFT JOIN users buyer ON t.buyer_id = buyer.id 
       LEFT JOIN users seller ON t.seller_id = seller.id
       WHERE t.id = ?`,
      [id]
    );

    res.json({
      success: true,
      message: '交易状态更新成功',
      data: updatedTransaction[0]
    });

  } catch (error) {
    console.error('更新交易状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新交易状态失败',
      error: error.message
    });
  }
});

// ======================================
// 合同管理相关接口
// ======================================

// 获取合同列表
router.get('/contracts', authenticateToken, checkPermission('contract_view'), async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status,
      contract_type,
      party_a_id,
      party_b_id,
      search
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockContracts = [
        {
          id: 1,
          contract_number: 'CON2024001',
          contract_type: 'cattle_sale',
          party_a_id: 2,
          party_b_id: 3,
          party_a_name: '张三',
          party_b_name: '李四',
          contract_amount: 45000.00,
          signing_date: '2024-01-20',
          effective_date: '2024-01-20',
          expiry_date: '2024-01-30',
          status: 'active',
          contract_url: '/uploads/contracts/CON2024001.pdf',
          notes: '牛只买卖合同',
          created_at: '2024-01-20 14:30:00'
        },
        {
          id: 2,
          contract_number: 'CON2024002',
          contract_type: 'feed_supply',
          party_a_id: 5,
          party_b_id: 2,
          party_a_name: '饲料供应商A',
          party_b_name: '张三',
          contract_amount: 52500.00,
          signing_date: '2024-01-22',
          effective_date: '2024-01-22',
          expiry_date: '2024-12-31',
          status: 'active',
          contract_url: '/uploads/contracts/CON2024002.pdf',
          notes: '饲料长期供应合同',
          created_at: '2024-01-22 16:45:00'
        }
      ];

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

    // 实际的数据库查询逻辑...
    res.json({
      success: true,
      message: '合同管理功能开发中',
      data: { contracts: [], 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('transaction_view'), async (req, res) => {
  try {
    const { period = 'month', start_date, end_date } = req.query;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockStats = {
        total_transactions: 156,
        total_amount: 2450000.00,
        completed_transactions: 134,
        pending_transactions: 15,
        cancelled_transactions: 7,
        average_transaction_amount: 15705.13,
        transaction_types: {
          cattle_sale: { count: 89, amount: 1850000.00 },
          feed_purchase: { count: 45, amount: 420000.00 },
          equipment_sale: { count: 22, amount: 180000.00 }
        },
        monthly_trend: [
          { month: '2023-11', transactions: 12, amount: 195000.00 },
          { month: '2023-12', transactions: 18, amount: 285000.00 },
          { month: '2024-01', transactions: 24, amount: 385000.00 }
        ],
        top_buyers: [
          { user_id: 3, name: '李四', transaction_count: 8, total_amount: 125000.00 },
          { user_id: 4, name: '王五', transaction_count: 6, total_amount: 98000.00 }
        ],
        top_sellers: [
          { user_id: 2, name: '张三', transaction_count: 12, total_amount: 185000.00 },
          { user_id: 5, name: '饲料供应商A', transaction_count: 15, total_amount: 142000.00 }
        ]
      };

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

    // 实际的统计查询逻辑...
    res.json({
      success: true,
      message: '交易统计功能开发中',
      data: { total_transactions: 0, total_amount: 0 }
    });

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

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