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('/products', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      category,
      status,
      seller_id,
      price_min,
      price_max,
      search,
      sort_by = 'created_at',
      sort_order = 'desc'
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockProducts = [
        {
          id: 1,
          name: '优质牛肉礼盒装',
          category: 'beef',
          description: '来自锡林浩特优质牧场的新鲜牛肉，肉质鲜美，营养丰富',
          price: 268.00,
          original_price: 298.00,
          stock: 45,
          sales_count: 128,
          status: 'active',
          seller_id: 2,
          seller_name: '张三牧场直营店',
          images: [
            '/uploads/products/beef_box_1.jpg',
            '/uploads/products/beef_box_2.jpg'
          ],
          specifications: {
            weight: '2kg',
            packaging: '礼盒装',
            storage: '冷冻保存',
            shelf_life: '30天'
          },
          origin: '锡林浩特市第一牧场',
          rating: 4.8,
          review_count: 56,
          created_at: '2024-01-15 10:30:00',
          updated_at: '2024-01-20 14:15:00'
        },
        {
          id: 2,
          name: '有机牛奶',
          category: 'dairy',
          description: '纯天然有机牛奶，无添加剂，营养价值高',
          price: 35.00,
          original_price: 35.00,
          stock: 120,
          sales_count: 89,
          status: 'active',
          seller_id: 3,
          seller_name: '草原乳业',
          images: [
            '/uploads/products/milk_1.jpg'
          ],
          specifications: {
            volume: '1L',
            packaging: '利乐包装',
            storage: '冷藏保存',
            shelf_life: '7天'
          },
          origin: '东乌旗生态牧场',
          rating: 4.6,
          review_count: 32,
          created_at: '2024-01-18 09:45:00',
          updated_at: '2024-01-22 16:30:00'
        },
        {
          id: 3,
          name: '牛肉干',
          category: 'snacks',
          description: '传统工艺制作的牛肉干，口感醇香，营养丰富',
          price: 68.00,
          original_price: 78.00,
          stock: 0,
          sales_count: 245,
          status: 'out_of_stock',
          seller_id: 4,
          seller_name: '草原食品厂',
          images: [
            '/uploads/products/jerky_1.jpg',
            '/uploads/products/jerky_2.jpg'
          ],
          specifications: {
            weight: '500g',
            packaging: '真空包装',
            storage: '常温保存',
            shelf_life: '180天'
          },
          origin: '西乌旗牧场',
          rating: 4.9,
          review_count: 78,
          created_at: '2024-01-10 14:20:00',
          updated_at: '2024-01-25 11:40:00'
        }
      ];

      // 根据查询条件过滤
      let filteredProducts = mockProducts;
      
      if (category) {
        filteredProducts = filteredProducts.filter(p => p.category === category);
      }
      
      if (status) {
        filteredProducts = filteredProducts.filter(p => p.status === status);
      }
      
      if (search) {
        const searchLower = search.toLowerCase();
        filteredProducts = filteredProducts.filter(p => 
          p.name.toLowerCase().includes(searchLower) || 
          p.description.toLowerCase().includes(searchLower)
        );
      }

      return res.json({
        success: true,
        data: {
          products: filteredProducts.slice(offset, offset + parseInt(limit)),
          pagination: {
            total: filteredProducts.length,
            page: parseInt(page),
            limit: parseInt(limit),
            pages: Math.ceil(filteredProducts.length / limit)
          }
        }
      });
    }

    // 数据库可用时的实际查询逻辑
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      const mockProducts = [
        {
          id: 1,
          name: '优质牛肉礼盒装',
          category: 'beef',
          price: 268.00,
          stock: 45,
          status: 'active',
          seller_name: '张三牧场直营店',
          created_at: '2024-01-15 10:30:00'
        }
      ];

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

    res.json({
      success: true,
      message: '商品列表功能开发中',
      data: { products: [], 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('/products/:id', async (req, res) => {
  try {
    const { id } = req.params;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockProduct = {
        id: parseInt(id),
        name: '优质牛肉礼盒装',
        category: 'beef',
        description: '来自锡林浩特优质牧场的新鲜牛肉，采用传统草饲方式饲养，肉质鲜美，营养丰富，是您餐桌上的不二选择。',
        price: 268.00,
        original_price: 298.00,
        stock: 45,
        sales_count: 128,
        status: 'active',
        seller_id: 2,
        seller_name: '张三牧场直营店',
        seller_rating: 4.7,
        images: [
          '/uploads/products/beef_box_1.jpg',
          '/uploads/products/beef_box_2.jpg',
          '/uploads/products/beef_box_3.jpg'
        ],
        specifications: {
          weight: '2kg',
          packaging: '礼盒装',
          storage: '冷冻保存',
          shelf_life: '30天',
          certification: ['有机认证', '质量安全认证']
        },
        origin_detail: {
          farm_name: '锡林浩特市第一牧场',
          farm_address: '锡林浩特市郊区',
          cattle_breed: '西门塔尔牛',
          feeding_method: '天然草饲',
          slaughter_date: '2024-01-12'
        },
        nutritional_info: {
          protein: '20.1g/100g',
          fat: '15.2g/100g',
          calories: '210kcal/100g',
          iron: '3.2mg/100g'
        },
        rating: 4.8,
        review_count: 56,
        reviews: [
          {
            id: 1,
            user_name: '李女士',
            rating: 5,
            content: '肉质非常好，很新鲜，包装也很精美，送人很有面子！',
            images: ['/uploads/reviews/review_1.jpg'],
            created_at: '2024-01-22 10:30:00'
          },
          {
            id: 2,
            user_name: '王先生',
            rating: 5,
            content: '味道正宗，口感很好，下次还会再买的',
            images: [],
            created_at: '2024-01-20 15:45:00'
          }
        ],
        shipping_info: {
          free_shipping_threshold: 200,
          shipping_fee: 0,
          estimated_delivery: '2-3个工作日',
          shipping_areas: ['锡林郭勒盟', '呼和浩特市', '包头市']
        },
        return_policy: {
          return_days: 7,
          return_conditions: '商品质量问题支持退换货',
          return_fee: '免费'
        },
        created_at: '2024-01-15 10:30:00',
        updated_at: '2024-01-20 14:15:00'
      };

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

    // 数据库可用时的实际查询逻辑
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      return res.json({
        success: true,
        message: '数据库连接不可用，返回模拟数据',
        data: {
          id: parseInt(id),
          name: '优质牛肉礼盒装',
          price: 268.00,
          status: 'active'
        }
      });
    }

    res.json({
      success: true,
      message: '商品详情功能开发中',
      data: { id: parseInt(id), message: '开发中' }
    });

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

// 创建商品（商家）
router.post('/products', authenticateToken, checkPermission('product_create'), async (req, res) => {
  try {
    const {
      name,
      category,
      description,
      price,
      original_price,
      stock,
      images,
      specifications,
      origin
    } = req.body;

    // 验证必需字段
    if (!name || !category || !price || !stock) {
      return res.status(400).json({
        success: false,
        message: '缺少必需的字段'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟响应
      const mockProduct = {
        id: Math.floor(Math.random() * 1000) + 100,
        name,
        category,
        description,
        price,
        original_price: original_price || price,
        stock,
        sales_count: 0,
        status: 'pending_review',
        seller_id: req.user?.id || 1,
        seller_name: req.user?.real_name || '商家',
        images: images || [],
        specifications: specifications || {},
        origin,
        rating: 0,
        review_count: 0,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };

      return res.status(201).json({
        success: true,
        message: '商品创建成功，等待审核（模拟数据）',
        data: mockProduct
      });
    }

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

    res.status(201).json({
      success: true,
      message: '商品创建功能开发中'
    });

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

// ======================================
// 订单管理相关接口
// ======================================

// 获取订单列表
router.get('/orders', authenticateToken, checkPermission('order_view'), async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status,
      user_id,
      start_date,
      end_date,
      search
    } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockOrders = [
        {
          id: 1,
          order_number: 'ORD202401001',
          user_id: 5,
          user_name: '赵六',
          total_amount: 536.00,
          discount_amount: 30.00,
          shipping_fee: 0.00,
          final_amount: 506.00,
          status: 'delivered',
          payment_status: 'paid',
          payment_method: 'wechat_pay',
          shipping_address: '呼和浩特市新城区xxx街道xxx号',
          shipping_phone: '13900000005',
          tracking_number: 'SF1234567890',
          items: [
            {
              product_id: 1,
              product_name: '优质牛肉礼盒装',
              quantity: 2,
              unit_price: 268.00,
              total_price: 536.00
            }
          ],
          order_date: '2024-01-20 10:30:00',
          payment_date: '2024-01-20 10:35:00',
          shipping_date: '2024-01-21 08:00:00',
          delivery_date: '2024-01-23 15:30:00',
          created_at: '2024-01-20 10:30:00'
        },
        {
          id: 2,
          order_number: 'ORD202401002',
          user_id: 6,
          user_name: '钱七',
          total_amount: 210.00,
          discount_amount: 0.00,
          shipping_fee: 15.00,
          final_amount: 225.00,
          status: 'shipping',
          payment_status: 'paid',
          payment_method: 'alipay',
          shipping_address: '包头市昆都仑区xxx路xxx号',
          shipping_phone: '13900000006',
          tracking_number: 'YTO0987654321',
          items: [
            {
              product_id: 2,
              product_name: '有机牛奶',
              quantity: 6,
              unit_price: 35.00,
              total_price: 210.00
            }
          ],
          order_date: '2024-01-22 14:20:00',
          payment_date: '2024-01-22 14:25:00',
          shipping_date: '2024-01-23 09:15:00',
          delivery_date: null,
          created_at: '2024-01-22 14:20:00'
        }
      ];

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

    // 数据库可用时的实际查询逻辑
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      const mockOrders = [
        {
          id: 1,
          order_number: 'ORD202401001',
          user_name: '赵六',
          total_amount: 506.00,
          status: 'delivered',
          created_at: '2024-01-20 10:30:00'
        }
      ];

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

    res.json({
      success: true,
      message: '订单列表功能开发中',
      data: { orders: [], 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.post('/orders', authenticateToken, async (req, res) => {
  try {
    const {
      items,
      shipping_address,
      shipping_phone,
      shipping_name,
      payment_method,
      coupon_code,
      notes
    } = req.body;

    // 验证必需字段
    if (!items || !Array.isArray(items) || items.length === 0) {
      return res.status(400).json({
        success: false,
        message: '订单商品不能为空'
      });
    }

    if (!shipping_address || !shipping_phone || !shipping_name) {
      return res.status(400).json({
        success: false,
        message: '收货信息不完整'
      });
    }

    if (!pool) {
      // 数据库不可用时返回模拟响应
      const mockOrder = {
        id: Math.floor(Math.random() * 1000) + 100,
        order_number: `ORD${new Date().getFullYear()}${String(Date.now()).slice(-8)}`,
        user_id: req.user?.id || 1,
        items,
        total_amount: items.reduce((sum, item) => sum + (item.quantity * item.unit_price), 0),
        discount_amount: 0,
        shipping_fee: 0,
        final_amount: items.reduce((sum, item) => sum + (item.quantity * item.unit_price), 0),
        status: 'pending_payment',
        payment_status: 'pending',
        payment_method,
        shipping_address,
        shipping_phone,
        shipping_name,
        notes,
        created_at: new Date().toISOString()
      };

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

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

    res.status(201).json({
      success: true,
      message: '订单创建功能开发中'
    });

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

// ======================================
// 商品评价相关接口
// ======================================

// 获取商品评价列表
router.get('/products/:product_id/reviews', async (req, res) => {
  try {
    const { product_id } = req.params;
    const { page = 1, limit = 10, rating } = req.query;
    const offset = (page - 1) * limit;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockReviews = [
        {
          id: 1,
          product_id: parseInt(product_id),
          user_id: 5,
          user_name: '赵六',
          user_avatar: '/uploads/avatars/user5.jpg',
          order_id: 1,
          rating: 5,
          content: '肉质非常好，很新鲜，包装也很精美，送人很有面子！家人都很满意，下次还会购买的。',
          images: [
            '/uploads/reviews/review_1_1.jpg',
            '/uploads/reviews/review_1_2.jpg'
          ],
          helpful_count: 12,
          reply: {
            content: '感谢您的好评，我们会继续努力提供优质的产品！',
            reply_date: '2024-01-23 09:15:00'
          },
          created_at: '2024-01-22 10:30:00'
        },
        {
          id: 2,
          product_id: parseInt(product_id),
          user_id: 6,
          user_name: '钱七',
          user_avatar: '/uploads/avatars/user6.jpg',
          order_id: 2,
          rating: 4,
          content: '味道正宗，口感很好，就是价格稍微有点贵',
          images: [],
          helpful_count: 8,
          reply: null,
          created_at: '2024-01-20 15:45:00'
        }
      ];

      return res.json({
        success: true,
        data: {
          reviews: mockReviews,
          pagination: {
            total: mockReviews.length,
            page: parseInt(page),
            limit: parseInt(limit),
            pages: Math.ceil(mockReviews.length / limit)
          },
          summary: {
            average_rating: 4.8,
            total_reviews: mockReviews.length,
            rating_distribution: {
              5: 56,
              4: 12,
              3: 3,
              2: 1,
              1: 0
            }
          }
        }
      });
    }

    // 数据库可用时的实际查询逻辑
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      const mockReviews = [
        {
          id: 1,
          user_name: '赵六',
          rating: 5,
          content: '肉质非常好，很新鲜',
          created_at: '2024-01-22 10:30:00'
        }
      ];

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

    res.json({
      success: true,
      message: '商品评价功能开发中',
      data: { reviews: [], 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('mall_statistics'), async (req, res) => {
  try {
    const { period = 'month' } = req.query;

    if (!pool) {
      // 数据库不可用时返回模拟数据
      const mockStats = {
        overview: {
          total_products: 156,
          active_products: 142,
          total_orders: 1284,
          total_revenue: 2580000.00,
          total_users: 8456,
          active_sellers: 28
        },
        sales_trend: [
          { date: '2024-01-15', orders: 45, revenue: 28500.00 },
          { date: '2024-01-16', orders: 52, revenue: 31200.00 },
          { date: '2024-01-17', orders: 48, revenue: 29800.00 },
          { date: '2024-01-18', orders: 61, revenue: 38200.00 },
          { date: '2024-01-19', orders: 55, revenue: 33500.00 },
          { date: '2024-01-20', orders: 68, revenue: 42600.00 },
          { date: '2024-01-21', orders: 73, revenue: 45800.00 }
        ],
        category_distribution: {
          beef: { count: 45, revenue: 1250000.00 },
          dairy: { count: 32, revenue: 680000.00 },
          snacks: { count: 28, revenue: 420000.00 },
          processed: { count: 35, revenue: 890000.00 },
          other: { count: 16, revenue: 340000.00 }
        },
        top_products: [
          { id: 1, name: '优质牛肉礼盒装', sales: 245, revenue: 65660.00 },
          { id: 3, name: '牛肉干', sales: 189, revenue: 12852.00 },
          { id: 2, name: '有机牛奶', sales: 156, revenue: 5460.00 }
        ],
        top_sellers: [
          { id: 2, name: '张三牧场直营店', orders: 128, revenue: 185600.00 },
          { id: 4, name: '草原食品厂', orders: 95, revenue: 142800.00 },
          { id: 3, name: '草原乳业', orders: 76, revenue: 98500.00 }
        ]
      };

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

    // 数据库可用时的实际统计查询逻辑
    try {
      await pool.execute('SELECT 1');
    } catch (dbError) {
      // 数据库连接失败，返回模拟数据
      const mockStats = {
        overview: {
          total_products: 156,
          total_orders: 1284,
          total_revenue: 2580000.00
        }
      };

      return res.json({
        success: true,
        message: '数据库连接不可用，返回模拟数据',
        data: mockStats
      });
    }

    res.json({
      success: true,
      message: '商城统计功能开发中',
      data: { overview: { total_products: 0, total_orders: 0 } }
    });

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

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