const OrderService = require('../../services/order');

/**
 * 创建订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function createOrder(req, res, next) {
  try {
    const orderData = req.body;
    const userId = req.user.id;

    // 验证必要字段
    if (!orderData.animal_id || !orderData.merchant_id || !orderData.total_amount) {
      return res.status(400).json({
        success: false,
        message: '缺少必要字段: animal_id, merchant_id, total_amount'
      });
    }

    const order = await OrderService.createOrder(orderData, userId);

    res.status(201).json({
      success: true,
      data: {
        order,
        message: '订单创建成功'
      }
    });
  } catch (error) {
    console.error('创建订单控制器错误:', error);
    next(error);
  }
}

/**
 * 获取订单详情
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getOrder(req, res, next) {
  try {
    const { orderId } = req.params;
    const userId = req.user.id;

    const order = await OrderService.getOrderById(orderId);

    // 检查权限：用户只能查看自己的订单，商家只能查看自己店铺的订单
    if (req.user.role === 'user' && order.user_id !== userId) {
      return res.status(403).json({
        success: false,
        message: '无权访问此订单'
      });
    }

    if (req.user.role === 'merchant' && order.merchant_id !== req.user.merchant_id) {
      return res.status(403).json({
        success: false,
        message: '无权访问此订单'
      });
    }

    res.json({
      success: true,
      data: order
    });
  } catch (error) {
    console.error('获取订单详情控制器错误:', error);
    if (error.message === '订单不存在') {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    res.status(500).json({
      success: false,
      message: error.message || '获取订单详情失败'
    });
  }
}

/**
 * 获取用户订单列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getUserOrders(req, res, next) {
  try {
    const userId = req.user.id;
    const filters = {
      page: req.query.page,
      limit: req.query.limit,
      status: req.query.status
    };

    const result = await OrderService.getUserOrders(userId, filters);

    res.json({
      success: true,
      data: result.orders,
      pagination: result.pagination
    });
  } catch (error) {
    console.error('获取用户订单列表控制器错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取订单列表失败'
    });
  }
}

/**
 * 获取商家订单列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getMerchantOrders(req, res, next) {
  try {
    const merchantId = req.user.merchant_id;
    const filters = {
      page: req.query.page,
      limit: req.query.limit,
      status: req.query.status
    };

    const result = await OrderService.getMerchantOrders(merchantId, filters);

    res.json({
      success: true,
      data: result.orders,
      pagination: result.pagination
    });
  } catch (error) {
    console.error('获取商家订单列表控制器错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取订单列表失败'
    });
  }
}

/**
 * 取消订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function cancelOrder(req, res, next) {
  try {
    const { orderId } = req.params;
    const userId = req.user.id;

    const order = await OrderService.cancelOrder(orderId, userId);

    res.json({
      success: true,
      message: '订单取消成功',
      data: order
    });
  } catch (error) {
    console.error('取消订单控制器错误:', error);
    if (error.message === '订单不存在') {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    if (error.message === '无权操作此订单') {
      return res.status(403).json({
        success: false,
        message: '无权操作此订单'
      });
    }
    if (error.message === '订单状态不允许取消') {
      return res.status(400).json({
        success: false,
        message: '订单状态不允许取消'
      });
    }
    res.status(500).json({
      success: false,
      message: error.message || '取消订单失败'
    });
  }
}

/**
 * 支付订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function payOrder(req, res, next) {
  try {
    const { orderId } = req.params;
    const paymentData = req.body;
    const userId = req.user.id;

    // 验证必要字段
    if (!paymentData.payment_method || !paymentData.amount) {
      return res.status(400).json({
        success: false,
        message: '缺少必要字段: payment_method, amount'
      });
    }

    // 获取订单并验证权限
    const order = await OrderService.getOrderById(orderId);
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    // 检查权限：用户只能支付自己的订单
    if (req.user.role === 'user' && order.user_id !== userId) {
      return res.status(403).json({
        success: false,
        message: '无权操作此订单'
      });
    }

    const result = await OrderService.payOrder(orderId, paymentData);

    res.json({
      success: true,
      message: '支付订单创建成功',
      data: result
    });
  } catch (error) {
    console.error('支付订单控制器错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '支付订单失败'
    });
  }
}

/**
 * 获取订单统计信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getOrderStatistics(req, res, next) {
  try {
    const userId = req.user.id;
    const statistics = await OrderService.getOrderStatistics(userId);

    res.json({
      success: true,
      data: statistics
    });
  } catch (error) {
    console.error('获取订单统计信息控制器错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取统计信息失败'
    });
  }
}

/**
 * 获取所有订单（管理员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getAllOrders(req, res, next) {
  try {
    const filters = {
      page: req.query.page,
      limit: req.query.limit,
      status: req.query.status
    };

    const result = await OrderService.getAllOrders(filters);

    res.json({
      success: true,
      data: result.orders,
      pagination: result.pagination
    });
  } catch (error) {
    console.error('获取所有订单控制器错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取所有订单失败'
    });
  }
}

/**
 * 更新订单状态
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateOrderStatus(req, res, next) {
  try {
    const { orderId } = req.params;
    const { status } = req.body;
    const userId = req.user.id;

    const order = await OrderService.updateOrderStatus(orderId, status, userId);

    res.json({
      success: true,
      message: '订单状态更新成功',
      data: order
    });
  } catch (error) {
    console.error('更新订单状态控制器错误:', error);
    if (error.message === '订单不存在') {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    if (error.message === '无权操作此订单') {
      return res.status(403).json({
        success: false,
        message: '无权操作此订单'
      });
    }
    res.status(500).json({
      success: false,
      message: error.message || '更新订单状态失败'
    });
  }
}

/**
 * 删除订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function deleteOrder(req, res, next) {
  try {
    const { orderId } = req.params;
    const userId = req.user.id;

    await OrderService.deleteOrder(orderId, userId);

    res.json({
      success: true,
      message: '订单删除成功'
    });
  } catch (error) {
    console.error('删除订单控制器错误:', error);
    if (error.message === '订单不存在') {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    if (error.message === '无权操作此订单') {
      return res.status(403).json({
        success: false,
        message: '无权操作此订单'
      });
    }
    res.status(500).json({
      success: false,
      message: error.message || '删除订单失败'
    });
  }
}

/**
 * 获取商家统计信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getMerchantStats(req, res, next) {
  try {
    const merchantId = req.user.merchant_id;
    const stats = await OrderService.getMerchantStats(merchantId);

    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    console.error('获取商家统计信息控制器错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取统计信息失败'
    });
  }
}

module.exports = {
  createOrder,
  getOrder,
  getUserOrders,
  getMerchantOrders,
  cancelOrder,
  payOrder,
  getOrderStatistics,
  getAllOrders,
  updateOrderStatus,
  deleteOrder,
  getMerchantStats
};