const database = require('../../config/database');

class OrderService {
  /**
   * 创建订单
   * @param {Object} orderData - 订单数据
   * @param {number} userId - 用户ID
   * @returns {Promise<Object>} 创建的订单
   */
  async createOrder(orderData, userId) {
    try {
      const {
        animal_id,
        merchant_id,
        total_amount,
        payment_method,
        shipping_address,
        contact_info
      } = orderData;

      const query = `
        INSERT INTO orders (
          user_id, animal_id, merchant_id, total_amount, 
          payment_method, shipping_address, contact_info, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
      `;

      const params = [
        userId, animal_id, merchant_id, total_amount,
        payment_method, shipping_address, contact_info
      ];

      const result = await database.query(query, params);
      
      // 获取创建的订单详情
      const order = await this.getOrderById(result.insertId);
      return order;
    } catch (error) {
      console.error('创建订单失败:', error);
      throw new Error('创建订单失败');
    }
  }

  /**
   * 根据ID获取订单
   * @param {number} orderId - 订单ID
   * @returns {Promise<Object>} 订单信息
   */
  async getOrderById(orderId) {
    try {
      const query = `
        SELECT 
          o.*,
          a.name as animal_name,
          a.species as animal_species,
          a.price as animal_price,
          u.username as user_name,
          m.business_name as merchant_name
        FROM orders o
        LEFT JOIN animals a ON o.animal_id = a.id
        LEFT JOIN users u ON o.user_id = u.id
        LEFT JOIN merchants m ON o.merchant_id = m.id
        WHERE o.id = ? AND o.is_deleted = 0
      `;

      const [order] = await database.query(query, [orderId]);
      
      if (!order) {
        throw new Error('订单不存在');
      }

      return order;
    } catch (error) {
      console.error('获取订单失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户订单列表
   * @param {number} userId - 用户ID
   * @param {Object} filters - 筛选条件
   * @returns {Promise<Array>} 订单列表
   */
  async getUserOrders(userId, filters = {}) {
    try {
      const { page = 1, pageSize = 10, status } = filters;
      const offset = (page - 1) * pageSize;

      let query = `
        SELECT 
          o.*,
          a.name as animal_name,
          a.species as animal_species,
          a.price as animal_price,
          m.business_name as merchant_name
        FROM orders o
        LEFT JOIN animals a ON o.animal_id = a.id
        LEFT JOIN merchants m ON o.merchant_id = m.id
        WHERE o.user_id = ? AND o.is_deleted = 0
      `;

      let countQuery = `
        SELECT COUNT(*) as total
        FROM orders o
        WHERE o.user_id = ? AND o.is_deleted = 0
      `;

      const params = [userId];
      const countParams = [userId];

      if (status) {
        query += ' AND o.status = ?';
        countQuery += ' AND o.status = ?';
        params.push(status);
        countParams.push(status);
      }

      query += ' ORDER BY o.created_at DESC LIMIT ? OFFSET ?';
      params.push(pageSize, offset);

      const [orders] = await database.query(query, params);
      const [totalResult] = await database.query(countQuery, countParams);

      return {
        orders,
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total: totalResult.total,
          totalPages: Math.ceil(totalResult.total / pageSize)
        }
      };
    } catch (error) {
      console.error('获取用户订单失败:', error);
      throw new Error('获取用户订单失败');
    }
  }

  /**
   * 获取商家订单列表
   * @param {number} merchantId - 商家ID
   * @param {Object} filters - 筛选条件
   * @returns {Promise<Array>} 订单列表
   */
  async getMerchantOrders(merchantId, filters = {}) {
    try {
      const { page = 1, pageSize = 10, status } = filters;
      const offset = (page - 1) * pageSize;

      let query = `
        SELECT 
          o.*,
          a.name as animal_name,
          a.species as animal_species,
          a.price as animal_price,
          u.username as user_name
        FROM orders o
        LEFT JOIN animals a ON o.animal_id = a.id
        LEFT JOIN users u ON o.user_id = u.id
        WHERE o.merchant_id = ? AND o.is_deleted = 0
      `;

      let countQuery = `
        SELECT COUNT(*) as total
        FROM orders o
        WHERE o.merchant_id = ? AND o.is_deleted = 0
      `;

      const params = [merchantId];
      const countParams = [merchantId];

      if (status) {
        query += ' AND o.status = ?';
        countQuery += ' AND o.status = ?';
        params.push(status);
        countParams.push(status);
      }

      query += ' ORDER BY o.created_at DESC LIMIT ? OFFSET ?';
      params.push(pageSize, offset);

      const [orders] = await database.query(query, params);
      const [totalResult] = await database.query(countQuery, countParams);

      return {
        orders,
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total: totalResult.total,
          totalPages: Math.ceil(totalResult.total / pageSize)
        }
      };
    } catch (error) {
      console.error('获取商家订单失败:', error);
      throw new Error('获取商家订单失败');
    }
  }

  /**
   * 更新订单状态
   * @param {number} orderId - 订单ID
   * @param {string} status - 新状态
   * @param {number} userId - 操作人ID
   * @returns {Promise<Object>} 更新后的订单
   */
  async updateOrderStatus(orderId, status, userId) {
    try {
      const validStatuses = ['pending', 'confirmed', 'shipped', 'delivered', 'cancelled'];
      if (!validStatuses.includes(status)) {
        throw new Error('无效的订单状态');
      }

      const query = `
        UPDATE orders 
        SET status = ?, updated_by = ?, updated_at = CURRENT_TIMESTAMP
        WHERE id = ? AND is_deleted = 0
      `;

      const result = await database.query(query, [status, userId, orderId]);
      
      if (result.affectedRows === 0) {
        throw new Error('订单不存在或已被删除');
      }

      return await this.getOrderById(orderId);
    } catch (error) {
      console.error('更新订单状态失败:', error);
      throw error;
    }
  }

  /**
   * 删除订单（软删除）
   * @param {number} orderId - 订单ID
   * @param {number} userId - 用户ID
   * @returns {Promise<boolean>} 是否删除成功
   */
  async deleteOrder(orderId, userId) {
    try {
      const query = `
        UPDATE orders 
        SET is_deleted = 1, deleted_by = ?, deleted_at = CURRENT_TIMESTAMP
        WHERE id = ? AND is_deleted = 0
      `;

      const result = await database.query(query, [userId, orderId]);
      
      return result.affectedRows > 0;
    } catch (error) {
      console.error('删除订单失败:', error);
      throw new Error('删除订单失败');
    }
  }

  /**
   * 支付订单
   * @param {number} orderId - 订单ID
   * @param {Object} paymentData - 支付数据
   * @returns {Object} 支付结果
   */
  async payOrder(orderId, paymentData) {
    try {
      // 获取订单信息
      const order = await this.getOrderById(orderId);
      if (!order) {
        throw new Error('订单不存在');
      }

      // 检查订单状态
      if (order.status !== 'pending') {
        throw new Error('订单状态不允许支付');
      }

      // 检查订单金额
      if (order.total_amount !== paymentData.amount) {
        throw new Error('支付金额与订单金额不符');
      }

      // 创建支付订单
      const PaymentService = require('../payment');
      const payment = await PaymentService.createPayment({
        order_id: orderId,
        user_id: order.user_id,
        amount: order.total_amount,
        payment_method: paymentData.payment_method,
        return_url: paymentData.return_url
      });

      // 更新订单状态为支付中
      await this.updateOrderStatus(orderId, 'paying');

      return {
        payment,
        order: await this.getOrderById(orderId)
      };
    } catch (error) {
      console.error('支付订单服务错误:', error);
      throw error;
    }
  }

  /**
   * 获取订单统计信息
   * @param {number} merchantId - 商家ID
   * @returns {Promise<Object>} 统计信息
   */
  async getOrderStats(merchantId) {
    try {
      const query = `
        SELECT 
          COUNT(*) as total_orders,
          SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_orders,
          SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) as confirmed_orders,
          SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) as shipped_orders,
          SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) as delivered_orders,
          SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_orders,
          SUM(total_amount) as total_revenue
        FROM orders 
        WHERE merchant_id = ? AND is_deleted = 0
      `;

      const [stats] = await database.query(query, [merchantId]);
      
      return stats;
    } catch (error) {
      console.error('获取订单统计失败:', error);
      throw new Error('获取订单统计失败');
    }
  }

  /**
   * 获取所有订单（管理员）
   * @param {Object} filters - 筛选条件
   * @returns {Promise<Array>} 订单列表
   */
  async getAllOrders(filters = {}) {
    try {
      const { 
        page = 1, 
        pageSize = 10, 
        status, 
        merchantId, 
        userId 
      } = filters;
      const offset = (page - 1) * pageSize;

      let query = `
        SELECT 
          o.*,
          a.name as animal_name,
          a.species as animal_species,
          u.username as user_name,
          m.business_name as merchant_name
        FROM orders o
        LEFT JOIN animals a ON o.animal_id = a.id
        LEFT JOIN users u ON o.user_id = u.id
        LEFT JOIN merchants m ON o.merchant_id = m.id
        WHERE o.is_deleted = 0
      `;

      let countQuery = `
        SELECT COUNT(*) as total
        FROM orders o
        WHERE o.is_deleted = 0
      `;

      const params = [];
      const countParams = [];

      if (status) {
        query += ' AND o.status = ?';
        countQuery += ' AND o.status = ?';
        params.push(status);
        countParams.push(status);
      }

      if (merchantId) {
        query += ' AND o.merchant_id = ?';
        countQuery += ' AND o.merchant_id = ?';
        params.push(merchantId);
        countParams.push(merchantId);
      }

      if (userId) {
        query += ' AND o.user_id = ?';
        countQuery += ' AND o.user_id = ?';
        params.push(userId);
        countParams.push(userId);
      }

      query += ' ORDER BY o.created_at DESC LIMIT ? OFFSET ?';
      params.push(pageSize, offset);

      const [orders] = await database.query(query, params);
      const [totalResult] = await database.query(countQuery, countParams);

      return {
        orders,
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total: totalResult.total,
          totalPages: Math.ceil(totalResult.total / pageSize)
        }
      };
    } catch (error) {
      console.error('获取所有订单失败:', error);
      throw new Error('获取所有订单失败');
    }
  }
}

module.exports = new OrderService();