const express = require('express');
const router = express.Router();
const { get, run, all } = require('../utils/db');
const { success, page } = require('../utils/response');

// 商品列表
router.get('/list', (req, res) => {
  const { page: p = 1, pageSize = 20, category_id, keyword, is_recommend, is_new, is_hot, sort, order } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(100, Math.max(1, +pageSize));
  let where = 'WHERE p.status=1';
  const params = [];

  if (category_id) { where += ' AND p.category_id=?'; params.push(category_id); }
  if (keyword) { where += ' AND p.name LIKE ?'; params.push(`%${keyword}%`); }
  if (is_recommend) { where += ' AND p.is_recommend=1'; }
  if (is_new) { where += ' AND p.is_new=1'; }
  if (is_hot) { where += ' AND p.is_hot=1'; }
  // ===== SEO 搜索词埋点：记录用户真实搜索长尾词 =====
  if (keyword && typeof keyword === 'string') {
    const kw = keyword.trim();
    if (kw.length >= 2 && kw.length <= 30) {
      try {
        run(`INSERT INTO search_keywords(keyword, count, last_seen) VALUES(?, 1, datetime('now','localtime'))
             ON CONFLICT(keyword) DO UPDATE SET count=count+1, last_seen=datetime('now','localtime')`,
          [kw]);
      } catch (e) { /* 表未建或写失败则静默 */ }
    }
  }


  // 白名单校验排序参数，防止 ORDER BY 注入
  const SORT_FIELDS = { price: 'p.price', sales: 'p.sales', new: 'p.created_at' };
  const ASC_OPTS = { asc: 'ASC', desc: 'DESC' };
  let orderBy = 'p.sort ASC, p.id DESC';
  if (SORT_FIELDS[sort]) {
    const dir = ASC_OPTS[order] || 'DESC';
    orderBy = `${SORT_FIELDS[sort]} ${dir}`;
  }

  const total = get(`SELECT COUNT(*) as c FROM products p ${where}`, params).c;
  const list = all(
    `SELECT p.id,p.name,p.image,p.price,p.original_price,p.sales,p.stock,p.unit,p.subtitle 
     FROM products p ${where} ORDER BY ${orderBy} LIMIT ? OFFSET ?`,
    [...params, size, (pageNum - 1) * size]
  );

  return res.json(page(list, total, pageNum, size));
});

// 商品详情
router.get('/detail/:id', (req, res) => {
  const product = get('SELECT * FROM products WHERE id=?', [req.params.id]);
  if (!product) return res.json({ code: 1, message: '商品不存在' });

  product.images = (() => { 
    const v = product.images;
    if (!v || v === '') return [];
    try { const p = JSON.parse(v); return Array.isArray(p) ? p : [v]; }
    catch(e) { return v.split(',').filter(Boolean); }
  })();
  product.skus = all('SELECT * FROM product_skus WHERE product_id=? ORDER BY sort ASC', [product.id]);
  product.specs = all('SELECT * FROM product_specs WHERE product_id=? ORDER BY sort ASC', [product.id]);
  product.specs.forEach(s => { s.values = (s.spec_values && s.spec_values !== '') ? JSON.parse(s.spec_values) : []; });

  return res.json(success(product));
});

// 热销商品
router.get('/hot', (req, res) => {
  const list = all('SELECT id,name,image,price,sales FROM products WHERE status=1 AND is_hot=1 ORDER BY sales DESC LIMIT 10');
  return res.json(success(list));
});

// 新品推荐
router.get('/new', (req, res) => {
  const list = all('SELECT id,name,image,price FROM products WHERE status=1 AND is_new=1 ORDER BY id DESC LIMIT 10');
  return res.json(success(list));
});

// 推荐商品
router.get('/recommend', (req, res) => {
  const list = all('SELECT id,name,image,price,sales FROM products WHERE status=1 AND is_recommend=1 ORDER BY sort ASC LIMIT 10');
  return res.json(success(list));
});

// 分类下商品
router.get('/category/:id', (req, res) => {
  const { page: p = 1, pageSize = 20 } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(100, Math.max(1, +pageSize));
  const total = get('SELECT COUNT(*) as c FROM products WHERE category_id=? AND status=1', [req.params.id]).c;
  const list = all('SELECT id,name,image,price,sales FROM products WHERE category_id=? AND status=1 ORDER BY sort ASC LIMIT ? OFFSET ?',
    [req.params.id, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

// 批量获取
router.post('/list-by-ids', (req, res) => {
  const { ids } = req.body;
  if (!ids || !ids.length) return res.json(success([]));
  const placeholders = ids.map(() => '?').join(',');
  const list = all(`SELECT id,name,image,price FROM products WHERE id IN (${placeholders})`, ids);
  return res.json(success(list));
});

// 获取商品评价列表
router.get('/reviews/:id', (req, res) => {
  try {
    const productId = req.params.id;
    const { page: p = 1, pageSize = 10 } = req.query;
    const pageNum = Math.max(1, +p);
    const size = Math.min(50, Math.max(1, +pageSize));

    const total = get('SELECT COUNT(*) as c FROM product_reviews WHERE product_id=? AND status=1', [productId]).c;
    const list = all(`SELECT pr.*, u.nickname, u.avatar FROM product_reviews pr 
      LEFT JOIN users u ON pr.user_id=u.id 
      WHERE pr.product_id=? AND pr.status=1 
      ORDER BY pr.id DESC LIMIT ? OFFSET ?`,
      [productId, size, (pageNum - 1) * size]);

    list.forEach(r => { r.images = (() => { if (!r.images || r.images === '') return []; try { const p = JSON.parse(r.images); return Array.isArray(p) ? p : [r.images]; } catch(e) { return r.images.split(',').filter(Boolean); } })(); });

    const stats = get('SELECT COUNT(*) as total, AVG(rating) as avg_rating, SUM(CASE WHEN rating=5 THEN 1 ELSE 0 END) as f5, SUM(CASE WHEN rating=4 THEN 1 ELSE 0 END) as f4, SUM(CASE WHEN rating=3 THEN 1 ELSE 0 END) as f3, SUM(CASE WHEN rating=2 THEN 1 ELSE 0 END) as f2, SUM(CASE WHEN rating=1 THEN 1 ELSE 0 END) as f1 FROM product_reviews WHERE product_id=? AND status=1', [productId]);

    return res.json(success({
      list,
      total,
      page: pageNum,
      pageSize: size,
      stats: {
        total: stats.total,
        avg_rating: stats.avg_rating ? Math.round(stats.avg_rating * 10) / 10 : 0,
        distribution: {
          5: stats.f5 || 0, 4: stats.f4 || 0, 3: stats.f3 || 0, 2: stats.f2 || 0, 1: stats.f1 || 0
        }
      }
    }));
  } catch (e) {
    return res.json({ code: 1, message: '获取评价失败' });
  }
});

module.exports = router;
