/**
 * ============================================================
 * 商品评价模块 - LiteMall 轻商城
 * 功能：评价创建 · 追评 · 点赞 · 商家回复 · 管理审核 · 评价列表
 * 著作权人：LiteMall 开发团队
 * ============================================================
 */
const express = require('express');

// [LiteMall_Copyright] fba28f00dae77aa2 LiteMall_Lobster_v1.0_2026


const router = express.Router();
const { get, run, all } = require('../utils/db');
const { success, fail } = require('../utils/response');
const { authUser, authAdmin, optionalAuth } = require('../middleware/auth');
// ================================================================
// 【自动建表/迁移逻辑】兼容现有 product_reviews 表，仅 ADD COLUMN
// ================================================================
(function migrate() {
  try {
    const { getDb } = require('../utils/db');
    const db = getDb();
    // ---------- 1. product_reviews 表新增字段 ----------
    const newColumns = [
      { name: 'follow_up_content', type: "TEXT DEFAULT ''" },
      { name: 'follow_up_images',  type: "TEXT DEFAULT '[]'" },
      { name: 'follow_up_time',    type: 'DATETIME' },
      { name: 'reply_time',        type: 'DATETIME' },
      { name: 'like_count',        type: 'INTEGER DEFAULT 0' },
      { name: 'is_hidden',         type: 'INTEGER DEFAULT 0' },
    ];
    const existing = db.prepare("PRAGMA table_info('product_reviews')").all();
    const existingNames = existing.map(r => r.name);
    for (const col of newColumns) {
      if (!existingNames.includes(col.name)) {
        try {
          db.exec(`ALTER TABLE product_reviews ADD COLUMN ${col.name} ${col.type}`);
          console.log(`✅ review迁移: 添加字段 ${col.name}`);
        } catch (e) {
          console.log(`ℹ️ review迁移: ${col.name} 跳过 (${e.message})`);
        }
      }
    }
    // ---------- 2. 创建 review_likes 表（评价点赞） ----------
    db.exec(`
      CREATE TABLE IF NOT EXISTS review_likes (
        id          INTEGER PRIMARY KEY AUTOINCREMENT,
        review_id   INTEGER NOT NULL REFERENCES product_reviews(id),
        user_id     INTEGER NOT NULL REFERENCES users(id),
        created_at  DATETIME DEFAULT (datetime('now','localtime')),
        UNIQUE(review_id, user_id)
      )
    `);
    console.log('✅ review迁移: review_likes 表已就绪');
    // ---------- 3. 创建 review_replies 表（商家多次回复） ----------
    db.exec(`
      CREATE TABLE IF NOT EXISTS review_replies (
        id          INTEGER PRIMARY KEY AUTOINCREMENT,
        review_id   INTEGER NOT NULL REFERENCES product_reviews(id),
        user_id     INTEGER NOT NULL REFERENCES users(id),
        content     TEXT DEFAULT '',
        created_at  DATETIME DEFAULT (datetime('now','localtime'))
      )
    `);
    console.log('✅ review迁移: review_replies 表已就绪');
    // ---------- 4. 创建索引 ----------
    db.exec(`
      CREATE INDEX IF NOT EXISTS idx_review_likes_review_id ON review_likes(review_id);
      CREATE INDEX IF NOT EXISTS idx_review_likes_user_id   ON review_likes(user_id);
      CREATE INDEX IF NOT EXISTS idx_review_replies_review_id ON review_replies(review_id);
    `);
    console.log('✅ review迁移: 索引已就绪');
  } catch (e) {
    console.error('❌ review迁移异常:', e.message);
  }
})();
// ================================================================
// 辅助函数：组装单条评价的完整数据（用户信息、点赞状态、商家回复）
// ================================================================
    // NOTE: assembleReview 每评价 3-4 次查询；极限场景(50条/页)约200次查询，对 SQLite 仍可接受；如需优化可批量合并 user/like/reply 查询
function assembleReview(review, currentUserId) {
  if (!review) return null;
  const item = { ...review };
  // 解析 JSON 字段
  item.images = JSON.parse(item.images || '[]');
  item.follow_up_images = JSON.parse(item.follow_up_images || '[]');
  // 获取用户信息
  const user = get('SELECT nickname, avatar FROM users WHERE id=?', [item.user_id]);
  item.nickname = user ? user.nickname : '匿名用户';
  item.avatar = user ? user.avatar : '';
  // 当前登录用户是否已点赞
  if (currentUserId) {
    const like = get('SELECT id FROM review_likes WHERE review_id=? AND user_id=?', [item.id, currentUserId]);
    item.is_liked = !!like;
  } else {
    item.is_liked = false;
  }
  // 获取商家回复列表（按时间升序）
  item.replies = all('SELECT rr.*, u.nickname AS user_nickname FROM review_replies rr LEFT JOIN users u ON rr.user_id=u.id WHERE rr.review_id=? ORDER BY rr.created_at ASC', [item.id]);
  // 兼容旧版 reply 字段（单条回复）
  if (item.reply && item.replies.length === 0) {
    item.replies.push({
      id: 0,
      review_id: item.id,
      user_id: 0,
      content: item.reply,
      created_at: item.reply_time || item.created_at,
      user_nickname: '商家'
    });
  }
  // 点赞数
  item.like_count = item.like_count || get('SELECT COUNT(*) AS c FROM review_likes WHERE review_id=?', [item.id]).c || 0;
  return item;
}
// ================================================================
// 【现有接口保持不动】创建评价
// ================================================================
router.post('/create', authUser, (req, res) => {
  try {
    const { product_id, order_id, rating, content, images } = req.body;
    if (!product_id || !order_id) return res.json(fail('参数错误'));
    if (!rating || rating < 1 || rating > 5) return res.json(fail('评分需在1-5之间'));
    // 检查订单是否属于该用户且已完成（received状态）
    const order = get('SELECT * FROM orders WHERE id=? AND user_id=? AND status=?', [order_id, req.userId, 'received']);
    if (!order) return res.json(fail('订单不存在或不可评价'));
    // 检查是否已评价
    const exist = get('SELECT id FROM product_reviews WHERE user_id=? AND order_id=? AND product_id=?', [req.userId, order_id, product_id]);
    if (exist) return res.json(fail('已评价过该商品'));
    const orderItem = get('SELECT sku_info FROM order_items WHERE order_id=? AND product_id=? LIMIT 1', [order_id, product_id]);
    run(
      'INSERT INTO product_reviews(product_id,order_id,user_id,sku_info,rating,content,images) VALUES(?,?,?,?,?,?,?)',
      [product_id, order_id, req.userId, orderItem?.sku_info || '', rating, content || '', JSON.stringify(images || [])]
    );
    return res.json(success(null, '评价成功'));
  } catch (e) {
    console.error('创建评价失败:', e);
    return res.json(fail('评价失败'));
  }
});
// ================================================================
// 【新增】追评 — 对已评价的商品补充评价内容
// ================================================================
router.post('/follow-up', authUser, (req, res) => {
  try {
    const { order_id, content, images } = req.body;
    if (!order_id) return res.json(fail('参数错误'));
    // 查询该用户该订单下的评价（取第一条）
    const review = get(
      'SELECT id, follow_up_content FROM product_reviews WHERE user_id=? AND order_id=?',
      [req.userId, order_id]
    );
    if (!review) return res.json(fail('请先评价该商品后再追评'));
    // 检查是否已追评过（只允许追评一次）
    if (review.follow_up_content) return res.json(fail('已追评过，不可重复追评'));
    // 幂等：仅未追评过的评价可写入，并发时只有第一个成功
    const upd = run(
      "UPDATE product_reviews SET follow_up_content=?, follow_up_images=?, follow_up_time=datetime('now','localtime') WHERE id=? AND (follow_up_content IS NULL OR follow_up_content='')",
      [content || '', JSON.stringify(images || []), review.id]
    );
    if (upd.changes === 0) return res.json(fail('已追评过，不可重复追评'));
    return res.json(success(null, '追评成功'));
  } catch (e) {
    console.error('追评失败:', e);
    return res.json(fail('追评失败'));
  }
});
// ================================================================
// 【新增】评价点赞 / 取消点赞
// ================================================================
router.post('/like', authUser, (req, res) => {
  try {
    const { review_id } = req.body;
    if (!review_id) return res.json(fail('参数错误'));
    // 检查评价是否存在
    const review = get('SELECT id FROM product_reviews WHERE id=?', [review_id]);
    if (!review) return res.json(fail('评价不存在'));
    // 查询是否已点赞
    const existing = get('SELECT id FROM review_likes WHERE review_id=? AND user_id=?', [review_id, req.userId]);
    if (existing) {
      // 取消点赞
      run('DELETE FROM review_likes WHERE id=?', [existing.id]);
      // 更新点赞计数
      const cnt = get('SELECT COUNT(*) AS c FROM review_likes WHERE review_id=?', [review_id]).c;
      run('UPDATE product_reviews SET like_count=? WHERE id=?', [cnt, review_id]);
      return res.json(success({ liked: false, like_count: cnt }, '取消点赞'));
    } else {
      // 添加点赞（不能给自己的评价点赞）
      const own = get('SELECT id FROM product_reviews WHERE id=? AND user_id=?', [review_id, req.userId]);
      if (own) return res.json(fail('不能给自己的评价点赞'));
      run('INSERT OR IGNORE INTO review_likes(review_id, user_id) VALUES(?,?)', [review_id, req.userId]);
      const cnt = get('SELECT COUNT(*) AS c FROM review_likes WHERE review_id=?', [review_id]).c;
      run('UPDATE product_reviews SET like_count=? WHERE id=?', [cnt, review_id]);
      return res.json(success({ liked: true, like_count: cnt }, '点赞成功'));
    }
  } catch (e) {
    console.error('点赞失败:', e);
    return res.json(fail('点赞失败'));
  }
});
// ================================================================
// 【新增】商家回复评价（支持多次回复，管理员权限）
// ================================================================
router.post('/reply', authAdmin, (req, res) => {
  try {
    const { review_id, content } = req.body;
    if (!review_id || !content) return res.json(fail('参数错误'));
    const review = get('SELECT id FROM product_reviews WHERE id=?', [review_id]);
    if (!review) return res.json(fail('评价不存在'));
    // 插入回复记录
    run(
      'INSERT INTO review_replies(review_id, user_id, content) VALUES(?,?,?)',
      [review_id, req.userId, content]
    );
    // 同步更新旧版 reply 和 reply_time 字段
    run(
      'UPDATE product_reviews SET reply=?, reply_time=datetime(\'now\',\'localtime\') WHERE id=?',
      [content, review_id]
    );
    return res.json(success(null, '回复成功'));
  } catch (e) {
    console.error('商家回复失败:', e);
    return res.json(fail('回复失败'));
  }
});
// ================================================================
// 【新增】商品评价列表（带筛选、排序）
// 排序规则：置顶(有商家回复) > 有图评价 > 时间倒序
// ================================================================
router.get('/list/:productId', optionalAuth, (req, res) => {
  try {
    const { productId } = req.params;
    const {
      page: p = 1,
      pageSize = 10,
      rating,          // 按评分筛选: 1-5
      has_image,       // 是否仅晒图: 0/1
      sort = 'newest', // 排序: newest | hottest
    } = req.query;
    const pageNum = Math.max(1, +p);
    const size = Math.min(50, Math.max(1, +pageSize));
    const params = [productId];
    // 构建 WHERE 条件
    let where = 'pr.product_id=? AND pr.status=1 AND pr.is_hidden=0';
    if (rating) {
      const s = String(rating);
      if (s === 'good' || s === '好评' || s === 'good_rate') {
        where += ' AND pr.rating >= 4';
      } else if (s === 'mid' || s === '中评') {
        where += ' AND pr.rating = 3';
      } else if (s === 'bad' || s === '差评') {
        where += ' AND pr.rating <= 2';
      } else {
        const r = +rating;
        if (r >= 1 && r <= 5) {
          if (r <= 2) {
            where += ' AND pr.rating <= 2';
          } else if (r === 3) {
            where += ' AND pr.rating = 3';
          } else {
            where += ' AND pr.rating >= 4';
          }
        }
      }
    }
    if (has_image === '1' || has_image === true) {
      where += " AND pr.images NOT IN ('[]', '')";
    }
    // 构建排序
    let orderBy;
    if (sort === 'hottest') {
      // 按热度：置顶(有回复) > 点赞数 > 时间倒序
      orderBy = `CASE WHEN (SELECT COUNT(*) FROM review_replies rr WHERE rr.review_id=pr.id) > 0 OR pr.reply != '' THEN 0 ELSE 1 END ASC, pr.like_count DESC, pr.created_at DESC`;
    } else {
      // 按时间排序（默认）：置顶(有回复) > 有图 > 时间倒序
      orderBy = `CASE WHEN (SELECT COUNT(*) FROM review_replies rr WHERE rr.review_id=pr.id) > 0 OR pr.reply != '' THEN 0 ELSE 1 END ASC, CASE WHEN pr.images NOT IN ('[]', '') THEN 0 ELSE 1 END ASC, pr.created_at DESC`;
    }
    // 查询总数
    const total = get(`SELECT COUNT(*) AS c FROM product_reviews pr WHERE ${where}`, params).c;
    // 查询列表
    const rows = all(
      `SELECT pr.* FROM product_reviews pr WHERE ${where} ORDER BY ${orderBy} LIMIT ? OFFSET ?`,
      [...params, size, (pageNum - 1) * size]
    );
    // 组装完整数据
    const list = rows.map(r => assembleReview(r, req.userId));
    // 统计数据：好评率/评分分布
    const stats = get(`
      SELECT
        COUNT(*) AS total,
        AVG(rating) AS avg_rating,
        SUM(CASE WHEN rating>=4 THEN 1 ELSE 0 END) AS good_count,
        SUM(CASE WHEN rating=3 THEN 1 ELSE 0 END) AS mid_count,
        SUM(CASE WHEN rating<=2 THEN 1 ELSE 0 END) AS bad_count,
        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 AND is_hidden=0
    `, [productId]);
    const totalCount = stats.total || 0;
    const goodRate = totalCount > 0 ? Math.round(((stats.good_count || 0) / totalCount) * 100) : 0;
    return res.json(success({
      list,
      total,
      page: pageNum,
      pageSize: size,
      stats: {
        total: totalCount,
        avg_rating: stats.avg_rating ? Math.round(stats.avg_rating * 10) / 10 : 0,
        good_rate: goodRate,
        good_count: stats.good_count || 0,
        mid_count: stats.mid_count || 0,
        bad_count: stats.bad_count || 0,
        distribution: {
          5: stats.f5 || 0, 4: stats.f4 || 0,
          3: stats.f3 || 0, 2: stats.f2 || 0, 1: stats.f1 || 0
        }
      }
    }));
  } catch (e) {
    console.error('获取评价列表失败:', e);
    return res.json(fail('获取评价列表失败'));
  }
});
// ================================================================
// 【新增】我的评价列表
// ================================================================
router.get('/my', authUser, (req, res) => {
  try {
    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 user_id=?', [req.userId]).c;
    const rows = all(
      'SELECT pr.*, p.name AS product_name, p.image AS product_image FROM product_reviews pr LEFT JOIN products p ON pr.product_id=p.id WHERE pr.user_id=? ORDER BY pr.created_at DESC LIMIT ? OFFSET ?',
      [req.userId, size, (pageNum - 1) * size]
    );
    const list = rows.map(r => assembleReview(r, req.userId));
    return res.json(success({
      list,
      total,
      page: pageNum,
      pageSize: size,
      totalPages: Math.ceil(total / size)
    }));
  } catch (e) {
    console.error('获取我的评价失败:', e);
    return res.json(fail('获取我的评价失败'));
  }
});
// ================================================================
// 【新增】管理端审核评价（显示/隐藏）
// ================================================================
router.post('/admin/verify', authAdmin, (req, res) => {
  try {
    const { review_id, action } = req.body; // action: 'show' 或 'hide'
    if (!review_id || !['show', 'hide'].includes(action)) {
      return res.json(fail('参数错误'));
    }
    const review = get('SELECT id FROM product_reviews WHERE id=?', [review_id]);
    if (!review) return res.json(fail('评价不存在'));
    const isHidden = action === 'hide' ? 1 : 0;
    run('UPDATE product_reviews SET is_hidden=? WHERE id=?', [isHidden, review_id]);
    const msg = action === 'hide' ? '已隐藏该评价' : '已显示该评价';
    return res.json(success(null, msg));
  } catch (e) {
    console.error('审核评价失败:', e);
    return res.json(fail('审核失败'));
  }
});
// ================================================================
// 【新增】管理端评价列表（含未审核、隐藏的）
// ================================================================
router.get('/admin/list', authAdmin, (req, res) => {
  try {
    const {
      page: p = 1, pageSize = 20, status, product_id, keyword
    } = req.query;
    const pageNum = Math.max(1, +p);
    const size = Math.min(100, Math.max(1, +pageSize));
    const params = [];
    let where = 'WHERE 1=1';
    if (status === 'hidden') {
      where += ' AND pr.is_hidden=1';
    } else if (status === 'visible') {
      where += ' AND pr.is_hidden=0';
    }
    // status=all 或不传则显示全部
    if (product_id) {
      where += ' AND pr.product_id=?';
      params.push(+product_id);
    }
    if (keyword) {
      where += ' AND (pr.content LIKE ? OR u.nickname LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`);
    }
    const total = get(`SELECT COUNT(*) AS c FROM product_reviews pr LEFT JOIN users u ON pr.user_id=u.id ${where}`, params).c;
    const rows = all(
      `SELECT pr.*, p.name AS product_name, p.image AS product_image FROM product_reviews pr
       LEFT JOIN users u ON pr.user_id=u.id
       LEFT JOIN products p ON pr.product_id=p.id
       ${where}
       ORDER BY pr.id DESC LIMIT ? OFFSET ?`,
      [...params, size, (pageNum - 1) * size]
    );
    const list = rows.map(r => assembleReview(r));
    return res.json(success({
      list,
      total,
      page: pageNum,
      pageSize: size,
      totalPages: Math.ceil(total / size)
    }));
  } catch (e) {
    console.error('获取管理端评价列表失败:', e);
    return res.json(fail('获取评价列表失败'));
  }
});
module.exports = router;