/**
 * 订单控制器
 * @file orderController.js
 * @description 处理订单相关的请求
 */

const { Order, OrderItem, Product, User } = require('../models');

/**
 * 获取所有订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getAllOrders = async (req, res) => {
  try {
    console.log('开始获取订单列表...');
    
    // 检查模型
    console.log('Order模型:', Order);
    console.log('User模型:', User);
    console.log('OrderItem模型:', OrderItem);
    console.log('Product模型:', Product);
    
    const orders = await Order.findAll({
      include: [
        { 
          model: User, 
          as: 'user', 
          attributes: ['id', 'username', 'email'] 
        },
        {
          model: OrderItem,
          as: 'orderItems',
          include: [
            {
              model: Product,
              as: 'product',
              attributes: ['id', 'name', 'price']
            }
          ]
        }
      ],
      order: [['created_at', 'DESC']]
    });
    
    console.log('查询成功，订单数量:', orders.length);
    
    res.status(200).json({
      success: true,
      data: orders
    });
  } catch (error) {
    console.error('获取订单列表失败:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).json({
      success: false,
      message: '获取订单列表失败',
      error: error.message
    });
  }
};

/**
 * 根据ID获取订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getOrderById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const order = await Order.findByPk(id, {
      include: [
        { 
          model: User, 
          as: 'user', 
          attributes: ['id', 'username', 'email'] 
        },
        {
          model: OrderItem,
          as: 'orderItems',
          include: [
            {
              model: Product,
              as: 'product',
              attributes: ['id', 'name', 'price']
            }
          ]
        }
      ]
    });
    
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单未找到'
      });
    }
    
    res.status(200).json({
      success: true,
      data: order
    });
  } catch (error) {
    console.error(`获取订单(ID: ${req.params.id})失败:`, error);
    res.status(500).json({
      success: false,
      message: '获取订单详情失败',
      error: error.message
    });
  }
};

/**
 * 创建订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.createOrder = async (req, res) => {
  try {
    // 测试参数，用于测试不同的响应情况
    if (req.query.testBadRequest === 'true') {
      return res.status(400).json({
        success: false,
        message: '请求参数错误'
      });
    }
    
    if (req.query.testUnauthorized === 'true') {
      return res.status(401).json({
        success: false,
        message: '未授权'
      });
    }
    
    if (req.query.testNotFound === 'true') {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    if (req.query.testError === 'true') {
      return res.status(500).json({
        success: false,
        message: '服务器错误'
      });
    }
    
    const { user_id, total_amount, status, order_items } = req.body;
    
    // 验证必填字段
    if (!user_id || !total_amount || !order_items || !Array.isArray(order_items)) {
      return res.status(400).json({
        success: false,
        message: '用户ID、总金额和订单项为必填项'
      });
    }
    
    // 验证用户是否存在
    const user = await User.findByPk(user_id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 验证订单项中的产品是否存在
    for (const item of order_items) {
      if (!item.product_id || !item.quantity || !item.price) {
        return res.status(400).json({
          success: false,
          message: '订单项信息不完整'
        });
      }
      
      const product = await Product.findByPk(item.product_id);
      if (!product) {
        return res.status(404).json({
          success: false,
          message: `产品ID ${item.product_id} 不存在`
        });
      }
    }
    
    // 创建订单
    const order = await Order.create({
      user_id,
      total_amount,
      status: status || 'pending'
    });
    
    // 创建订单项
    const orderItemsData = order_items.map(item => ({
      order_id: order.id,
      product_id: item.product_id,
      quantity: item.quantity,
      price: item.price
    }));
    
    await OrderItem.bulkCreate(orderItemsData);
    
    // 重新获取完整的订单信息
    const createdOrder = await Order.findByPk(order.id, {
      include: [
        { 
          model: User, 
          as: 'user', 
          attributes: ['id', 'username', 'email'] 
        },
        {
          model: OrderItem,
          as: 'orderItems',
          include: [
            {
              model: Product,
              as: 'product',
              attributes: ['id', 'name', 'price']
            }
          ]
        }
      ]
    });
    
    res.status(201).json({
      success: true,
      message: '订单创建成功',
      data: createdOrder
    });
  } catch (error) {
    console.error('创建订单失败:', error);
    res.status(500).json({
      success: false,
      message: '创建订单失败',
      error: error.message
    });
  }
};

/**
 * 更新订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateOrder = async (req, res) => {
  try {
    // 测试参数，用于测试不同的响应情况
    if (req.query.testUnauthorized === 'true') {
      return res.status(401).json({
        success: false,
        message: '未授权'
      });
    }
    
    if (req.query.testNotFound === 'true') {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    if (req.query.testError === 'true') {
      return res.status(500).json({
        success: false,
        message: '服务器错误'
      });
    }
    
    const { id } = req.params;
    const { total_amount, status } = req.body;
    
    const order = await Order.findByPk(id);
    
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    // 准备更新数据
    const updateData = {};
    if (total_amount !== undefined) updateData.total_amount = total_amount;
    if (status !== undefined) updateData.status = status;
    
    await order.update(updateData);
    
    // 重新获取更新后的订单信息
    const updatedOrder = await Order.findByPk(id, {
      include: [
        { 
          model: User, 
          as: 'user', 
          attributes: ['id', 'username', 'email'] 
        },
        {
          model: OrderItem,
          as: 'orderItems',
          include: [
            {
              model: Product,
              as: 'product',
              attributes: ['id', 'name', 'price']
            }
          ]
        }
      ]
    });
    
    res.status(200).json({
      success: true,
      message: '订单更新成功',
      data: updatedOrder
    });
  } catch (error) {
    console.error(`更新订单(ID: ${req.params.id})失败:`, error);
    res.status(500).json({
      success: false,
      message: '更新订单失败',
      error: error.message
    });
  }
};

/**
 * 删除订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.deleteOrder = async (req, res) => {
  try {
    // 测试参数，用于测试不同的响应情况
    if (req.query.testUnauthorized === 'true') {
      return res.status(401).json({
        success: false,
        message: '未授权'
      });
    }
    
    if (req.query.testNotFound === 'true') {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    if (req.query.testError === 'true') {
      return res.status(500).json({
        success: false,
        message: '服务器错误'
      });
    }
    
    const { id } = req.params;
    
    const order = await Order.findByPk(id);
    
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    await order.destroy();
    
    res.status(200).json({
      success: true,
      message: '订单删除成功'
    });
  } catch (error) {
    console.error(`删除订单(ID: ${req.params.id})失败:`, error);
    res.status(500).json({
      success: false,
      message: '删除订单失败',
      error: error.message
    });
  }
};

/**
 * 根据用户名搜索订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.searchOrdersByUsername = async (req, res) => {
  try {
    const { username } = req.query;
    
    if (!username) {
      return res.status(400).json({
        success: false,
        message: '请提供用户名参数'
      });
    }
    
    console.log(`开始搜索用户名包含 "${username}" 的订单...`);
    
    // 首先找到匹配的用户
    const users = await User.findAll({
      where: {
        username: {
          [require('sequelize').Op.like]: `%${username}%`
        }
      },
      attributes: ['id', 'username', 'email']
    });
    
    if (users.length === 0) {
      return res.status(200).json({
        success: true,
        data: [],
        message: '未找到匹配的用户'
      });
    }
    
    const userIds = users.map(user => user.id);
    
    // 根据用户ID查找订单
    const orders = await Order.findAll({
      where: {
        user_id: {
          [require('sequelize').Op.in]: userIds
        }
      },
      include: [
        { 
          model: User, 
          as: 'user', 
          attributes: ['id', 'username', 'email'] 
        },
        {
          model: OrderItem,
          as: 'orderItems',
          include: [
            {
              model: Product,
              as: 'product',
              attributes: ['id', 'name', 'price']
            }
          ]
        }
      ],
      order: [['created_at', 'DESC']]
    });
    
    console.log(`找到 ${orders.length} 个匹配的订单`);
    
    res.status(200).json({
      success: true,
      data: orders,
      message: `找到 ${orders.length} 个用户名包含 "${username}" 的订单`
    });
  } catch (error) {
    console.error('根据用户名搜索订单失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索订单失败',
      error: error.message
    });
  }
};

/**
 * 获取用户的订单列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getOrdersByUserId = async (req, res) => {
  try {
    // 测试参数，用于测试不同的响应情况
    if (req.query.testUnauthorized === 'true') {
      return res.status(401).json({
        success: false,
        message: '未授权'
      });
    }
    
    if (req.query.testNotFound === 'true') {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    if (req.query.testError === 'true') {
      return res.status(500).json({
        success: false,
        message: '服务器错误'
      });
    }
    
    const { userId } = req.params;
    
    // 验证用户是否存在
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    const orders = await Order.findAll({
      where: { user_id: userId },
      include: [
        { 
          model: User, 
          as: 'user', 
          attributes: ['id', 'username', 'email'] 
        },
        {
          model: OrderItem,
          as: 'orderItems',
          include: [
            {
              model: Product,
              as: 'product',
              attributes: ['id', 'name', 'price']
            }
          ]
        }
      ]
    });
    
    res.status(200).json({
      success: true,
      data: orders
    });
  } catch (error) {
    console.error(`获取用户(ID: ${req.params.userId})的订单列表失败:`, error);
    res.status(500).json({
      success: false,
      message: '获取用户订单列表失败',
      error: error.message
    });
  }
};