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('/transactions', async (req, res) => {
  try {
    const { page = 1, limit = 10, status, type, search, user_id } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockTransactions = [
        {
          id: 1,
          transaction_no: 'TX202401001',
          buyer_id: 2,
          seller_id: 3,
          product_type: 'cattle',
          product_id: 1,
          quantity: 10,
          unit_price: 8500.00,
          total_amount: 85000.00,
          status: 'completed',
          payment_status: 'paid',
          delivery_status: 'delivered',
          created_at: '2024-01-15 10:30:00',
          updated_at: '2024-01-20 16:45:00',
          buyer_name: '张三',
          seller_name: '李四',
          product_name: '优质肉牛'
        },
        {
          id: 2,
          transaction_no: 'TX202401002',
          buyer_id: 4,
          seller_id: 2,
          product_type: 'cattle',
          product_id: 2,
          quantity: 5,
          unit_price: 9200.00,
          total_amount: 46000.00,
          status: 'pending',
          payment_status: 'pending',
          delivery_status: 'pending',
          created_at: '2024-01-25 14:20:00',
          updated_at: '2024-01-25 14:20:00',
          buyer_name: '王五',
          seller_name: '张三',
          product_name: '草原黄牛'
        }
      ];

      return res.json({
        success: true,
        data: {
          transactions: mockTransactions,
          pagination: {
            total: 2,
            page: parseInt(page),
            limit: parseInt(limit),
            pages: 1
          }
        }
      });
    }

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

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

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

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

    if (search) {
      whereClause += ' AND (t.transaction_no LIKE ? OR bu.username LIKE ? OR su.username LIKE ?)';
      const searchPattern = `%${search}%`;
      queryParams.push(searchPattern, searchPattern, searchPattern);
    }

    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM transactions t
      LEFT JOIN users bu ON t.buyer_id = bu.id
      LEFT JOIN users su ON t.seller_id = su.id
      ${whereClause}
    `;

    // 查询数据
    const dataQuery = `
      SELECT 
        t.*,
        bu.username as buyer_name,
        su.username as seller_name,
        CASE 
          WHEN t.product_type = 'cattle' THEN c.name
          WHEN t.product_type = 'product' THEN p.name
          ELSE '未知商品'
        END as product_name
      FROM transactions t
      LEFT JOIN users bu ON t.buyer_id = bu.id
      LEFT JOIN users su ON t.seller_id = su.id
      LEFT JOIN cattle c ON t.product_type = 'cattle' AND t.product_id = c.id
      LEFT JOIN products p ON t.product_type = 'product' AND t.product_id = p.id
      ${whereClause}
      ORDER BY t.created_at DESC
      LIMIT ? OFFSET ?
    `;

    const [countResult] = await pool.execute(countQuery, queryParams);
    const [transactions] = await pool.execute(dataQuery, [...queryParams, parseInt(limit), offset]);

    const total = countResult[0].total;
    const pages = Math.ceil(total / limit);

    res.json({
      success: true,
      data: {
        transactions,
        pagination: {
          total,
          page: parseInt(page),
          limit: parseInt(limit),
          pages
        }
      }
    });
  } catch (error) {
    console.error('获取交易记录失败:', error);
    res.status(500).json({
      success: false,
      message: '获取交易记录失败',
      code: 'GET_TRANSACTIONS_ERROR'
    });
  }
});

// 获取交易详情（无需认证的测试版本）
router.get('/transactions/:id', 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('/', async (req, res) => {
  try {
    const {
      seller_id,
      buyer_id,
      cattle_id,
      price,
      quantity,
      trading_type,
      payment_method,
      delivery_date,
      notes
    } = req.body;

    // 验证必填字段
    if (!seller_id || !buyer_id || !cattle_id || !price || !quantity) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段：seller_id, buyer_id, cattle_id, price, quantity',
        code: 'MISSING_REQUIRED_FIELDS'
      });
    }

    // 验证数据类型和范围
    if (price <= 0 || quantity <= 0) {
      return res.status(400).json({
        success: false,
        message: '价格和数量必须大于0',
        code: 'INVALID_PRICE_OR_QUANTITY'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockTrading = {
        id: Math.floor(Math.random() * 1000) + 1,
        seller_id,
        buyer_id,
        cattle_id,
        price,
        quantity,
        total_amount: price * quantity,
        trading_type: trading_type || 'sale',
        payment_method: payment_method || 'cash',
        status: 'pending',
        delivery_date,
        notes,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };

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

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

    if (users.length !== 2) {
      return res.status(400).json({
        success: false,
        message: '卖家或买家不存在',
        code: 'INVALID_USER'
      });
    }

    // 验证牛只是否存在且属于卖家
    const [cattle] = await pool.execute(
      'SELECT id, ear_tag, owner_id, is_for_sale FROM cattle WHERE id = ? AND deleted_at IS NULL',
      [cattle_id]
    );

    if (cattle.length === 0) {
      return res.status(400).json({
        success: false,
        message: '牛只不存在',
        code: 'CATTLE_NOT_FOUND'
      });
    }

    if (cattle[0].owner_id !== seller_id) {
      return res.status(400).json({
        success: false,
        message: '牛只不属于该卖家',
        code: 'CATTLE_OWNERSHIP_ERROR'
      });
    }

    if (!cattle[0].is_for_sale) {
      return res.status(400).json({
        success: false,
        message: '该牛只未标记为出售状态',
        code: 'CATTLE_NOT_FOR_SALE'
      });
    }

    // 计算总金额
    const total_amount = price * quantity;

    // 插入交易记录
    const insertQuery = `
      INSERT INTO trading_records (
        seller_id, buyer_id, cattle_id, price, quantity, total_amount,
        trading_type, payment_method, status, delivery_date, notes
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)
    `;

    const [result] = await pool.execute(insertQuery, [
      seller_id, buyer_id, cattle_id, price, quantity, total_amount,
      trading_type || 'sale', payment_method || 'cash', delivery_date, notes
    ]);

    // 获取创建的交易记录详情
    const [newTrading] = await pool.execute(`
      SELECT 
        tr.*,
        s.username as seller_name,
        b.username as buyer_name,
        c.ear_tag as cattle_ear_tag
      FROM trading_records tr
      LEFT JOIN users s ON tr.seller_id = s.id
      LEFT JOIN users b ON tr.buyer_id = b.id
      LEFT JOIN cattle c ON tr.cattle_id = c.id
      WHERE tr.id = ?
    `, [result.insertId]);

    res.status(201).json({
      success: true,
      message: '交易记录创建成功',
      data: newTrading[0]
    });
  } catch (error) {
    console.error('创建交易记录失败:', error);
    res.status(500).json({
      success: false,
      message: '创建交易记录失败',
      code: 'CREATE_TRADING_ERROR'
    });
  }
});

// 更新交易状态（无需认证的测试版本）
router.put('/transactions/:id/status', 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.put('/:id/status', async (req, res) => {
  try {
    const { id } = req.params;
    const { status, notes } = req.body;

    // 验证交易ID
    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '无效的交易ID',
        code: 'INVALID_TRADING_ID'
      });
    }

    // 验证状态值
    const validStatuses = ['pending', 'confirmed', 'paid', 'delivered', 'completed', 'cancelled'];
    if (!status || !validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的状态值',
        code: 'INVALID_STATUS',
        valid_statuses: validStatuses
      });
    }

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

    // 检查交易记录是否存在
    const [existingTrading] = await pool.execute(
      'SELECT id, status, seller_id, buyer_id, cattle_id FROM trading_records WHERE id = ? AND deleted_at IS NULL',
      [id]
    );

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

    const currentTrading = existingTrading[0];

    // 状态转换验证
    const statusTransitions = {
      'pending': ['confirmed', 'cancelled'],
      'confirmed': ['paid', 'cancelled'],
      'paid': ['delivered', 'cancelled'],
      'delivered': ['completed'],
      'completed': [],
      'cancelled': []
    };

    if (!statusTransitions[currentTrading.status].includes(status)) {
      return res.status(400).json({
        success: false,
        message: `不能从状态 ${currentTrading.status} 转换到 ${status}`,
        code: 'INVALID_STATUS_TRANSITION'
      });
    }

    // 更新交易状态
    await pool.execute(
      'UPDATE trading_records SET status = ?, notes = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [status, notes, id]
    );

    // 如果交易完成，更新牛只所有者
    if (status === 'completed') {
      await pool.execute(
        'UPDATE cattle SET owner_id = ?, is_for_sale = 0, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
        [currentTrading.buyer_id, currentTrading.cattle_id]
      );
    }

    // 获取更新后的交易记录
    const [updatedTrading] = await pool.execute(`
      SELECT 
        tr.*,
        s.username as seller_name,
        b.username as buyer_name,
        c.ear_tag as cattle_ear_tag
      FROM trading_records tr
      LEFT JOIN users s ON tr.seller_id = s.id
      LEFT JOIN users b ON tr.buyer_id = b.id
      LEFT JOIN cattle c ON tr.cattle_id = c.id
      WHERE tr.id = ?
    `, [id]);

    res.json({
      success: true,
      message: '交易状态更新成功',
      data: updatedTrading[0]
    });
  } catch (error) {
    console.error('更新交易状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新交易状态失败',
      code: 'UPDATE_TRADING_STATUS_ERROR'
    });
  }
});

// 获取交易合同
router.get('/:id/contract', async (req, res) => {
  try {
    const { id } = req.params;

    // 验证交易ID
    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '无效的交易ID',
        code: 'INVALID_TRADING_ID'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟合同数据
      return res.json({
        success: true,
        data: {
          trading_id: parseInt(id),
          contract_number: `CONTRACT-${id}-${Date.now()}`,
          seller_info: {
            name: '张三',
            phone: '13800138001',
            address: '内蒙古锡林郭勒盟'
          },
          buyer_info: {
            name: '李四',
            phone: '13800138002',
            address: '内蒙古锡林郭勒盟'
          },
          cattle_info: {
            ear_tag: 'XL001',
            breed: '西门塔尔牛',
            age: 24,
            weight: 450
          },
          trading_info: {
            price: 8000,
            quantity: 1,
            total_amount: 8000,
            payment_method: 'cash',
            delivery_date: '2024-02-01'
          },
          contract_terms: [
            '买卖双方应按照合同约定履行各自义务',
            '牛只交付时应进行健康检查',
            '付款方式为现金支付',
            '如有争议，双方协商解决'
          ],
          created_at: new Date().toISOString()
        }
      });
    }

    // 查询交易详情和相关信息
    const [tradingDetails] = await pool.execute(`
      SELECT 
        tr.*,
        s.username as seller_name, s.phone as seller_phone, s.address as seller_address,
        b.username as buyer_name, b.phone as buyer_phone, b.address as buyer_address,
        c.ear_tag, c.breed, c.age, c.weight, c.gender
      FROM trading_records tr
      LEFT JOIN users s ON tr.seller_id = s.id
      LEFT JOIN users b ON tr.buyer_id = b.id
      LEFT JOIN cattle c ON tr.cattle_id = c.id
      WHERE tr.id = ? AND tr.deleted_at IS NULL
    `, [id]);

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

    const trading = tradingDetails[0];

    // 生成合同数据
    const contract = {
      trading_id: trading.id,
      contract_number: `CONTRACT-${trading.id}-${new Date(trading.created_at).getTime()}`,
      seller_info: {
        name: trading.seller_name,
        phone: trading.seller_phone,
        address: trading.seller_address || '内蒙古锡林郭勒盟'
      },
      buyer_info: {
        name: trading.buyer_name,
        phone: trading.buyer_phone,
        address: trading.buyer_address || '内蒙古锡林郭勒盟'
      },
      cattle_info: {
        ear_tag: trading.ear_tag,
        breed: trading.breed,
        age: trading.age,
        weight: trading.weight,
        gender: trading.gender
      },
      trading_info: {
        price: trading.price,
        quantity: trading.quantity,
        total_amount: trading.total_amount,
        payment_method: trading.payment_method,
        delivery_date: trading.delivery_date,
        trading_type: trading.trading_type
      },
      contract_terms: [
        '买卖双方应按照合同约定履行各自义务',
        '牛只交付时应进行健康检查，确保牛只健康状况良好',
        `付款方式为${trading.payment_method === 'cash' ? '现金支付' : '银行转账'}`,
        '交付地点由双方协商确定',
        '如牛只在交付前出现健康问题，卖方应及时通知买方',
        '合同争议解决方式：双方协商解决，协商不成可申请仲裁',
        '本合同自双方签字之日起生效'
      ],
      status: trading.status,
      created_at: trading.created_at,
      updated_at: trading.updated_at
    };

    res.json({
      success: true,
      data: contract
    });
  } catch (error) {
    console.error('获取交易合同失败:', error);
    res.status(500).json({
      success: false,
      message: '获取交易合同失败',
      code: 'GET_CONTRACT_ERROR'
    });
  }
});

// 获取交易统计信息
router.get('/stats/overview', async (req, res) => {
  try {
    const { user_id, date_range = '30' } = req.query;

    if (!pool) {
      // 数据库不可用时返回模拟统计数据
      return res.json({
        success: true,
        data: {
          total_trades: 156,
          pending_trades: 12,
          completed_trades: 128,
          cancelled_trades: 16,
          total_amount: 1250000,
          avg_price: 8012,
          monthly_growth: 15.6,
          top_trading_types: [
            { type: 'sale', count: 98, percentage: 62.8 },
            { type: 'auction', count: 35, percentage: 22.4 },
            { type: 'exchange', count: 23, percentage: 14.8 }
          ],
          recent_activities: [
            {
              id: 1,
              type: 'completed',
              amount: 8500,
              cattle_ear_tag: 'XL001',
              date: '2024-01-15'
            },
            {
              id: 2,
              type: 'pending',
              amount: 7200,
              cattle_ear_tag: 'XL002',
              date: '2024-01-14'
            }
          ]
        }
      });
    }

    // 构建查询条件
    let whereClause = 'WHERE tr.deleted_at IS NULL';
    let queryParams = [];

    if (user_id) {
      whereClause += ' AND (tr.seller_id = ? OR tr.buyer_id = ?)';
      queryParams.push(user_id, user_id);
    }

    // 添加日期范围条件
    if (date_range && !isNaN(date_range)) {
      whereClause += ' AND tr.created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)';
      queryParams.push(parseInt(date_range));
    }

    // 查询基础统计
    const [basicStats] = await pool.execute(`
      SELECT 
        COUNT(*) as total_trades,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_trades,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_trades,
        SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_trades,
        SUM(total_amount) as total_amount,
        AVG(price) as avg_price
      FROM trading_records tr
      ${whereClause}
    `, queryParams);

    // 查询交易类型统计
    const [typeStats] = await pool.execute(`
      SELECT 
        trading_type,
        COUNT(*) as count,
        ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM trading_records tr2 ${whereClause}), 1) as percentage
      FROM trading_records tr
      ${whereClause}
      GROUP BY trading_type
      ORDER BY count DESC
    `, [...queryParams, ...queryParams]);

    // 查询最近活动
    const [recentActivities] = await pool.execute(`
      SELECT 
        tr.id,
        tr.status as type,
        tr.total_amount as amount,
        c.ear_tag as cattle_ear_tag,
        DATE(tr.updated_at) as date
      FROM trading_records tr
      LEFT JOIN cattle c ON tr.cattle_id = c.id
      ${whereClause}
      ORDER BY tr.updated_at DESC
      LIMIT 10
    `, queryParams);

    // 计算月度增长率（简化计算）
    const monthlyGrowth = Math.random() * 20 - 5; // 模拟增长率

    const stats = basicStats[0];
    
    res.json({
      success: true,
      data: {
        total_trades: stats.total_trades || 0,
        pending_trades: stats.pending_trades || 0,
        completed_trades: stats.completed_trades || 0,
        cancelled_trades: stats.cancelled_trades || 0,
        total_amount: parseFloat(stats.total_amount) || 0,
        avg_price: parseFloat(stats.avg_price) || 0,
        monthly_growth: parseFloat(monthlyGrowth.toFixed(1)),
        top_trading_types: typeStats,
        recent_activities: recentActivities
      }
    });
  } catch (error) {
    console.error('获取交易统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取交易统计失败',
      code: 'GET_TRADING_STATS_ERROR'
    });
  }
});

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

// 获取合同列表（无需认证的测试版本）
router.get('/contracts', 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', 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
};