const express = require('express');
const router = express.Router();
const { get, run, all, transaction } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authUser, authAdmin } = require('../middleware/auth');

// 用于区分管理端和前端请求
    // NOTE: isAdmin 通过 baseUrl 判断路由前缀，已覆盖管理端/前端两种场景

function isAdmin(req) {
  return req.baseUrl && req.baseUrl.indexOf('/admin/') !== -1;
}

// ===================================================================
// 积分商品 API
// ===================================================================

// GET /products - 列表（前端公开 / 管理端分页+authAdmin）
router.get('/products', (req, res, next) => {
  if (isAdmin(req)) return authAdmin(req, res, next);
  next();
}, (req, res) => {
  try {
    if (isAdmin(req)) {
      // 管理端：分页
      const { page: p = 1, pageSize = 20, keyword } = req.query;
      const pageNum = Math.max(1, +p);
      const size = Math.min(100, Math.max(1, +pageSize));
      let where = 'WHERE 1=1';
      const params = [];
      if (keyword) { where += ' AND name LIKE ?'; params.push('%' + keyword + '%'); }
      const total = get(`SELECT COUNT(*) as c FROM exchange_products ${where}`, params).c;
      const list = all(`SELECT * FROM exchange_products ${where} ORDER BY sort ASC, id DESC LIMIT ? OFFSET ?`,
        [...params, size, (pageNum - 1) * size]);
      return res.json(page(list, total, pageNum, size));
    } else {
      // 前端：仅返回上架且有库存的商品
      const list = all("SELECT * FROM exchange_products WHERE status=1 AND stock>0 ORDER BY sort ASC, id DESC");
      return res.json(success(list));
    }
  } catch (e) {
    return res.json(fail('获取积分商品列表失败'));
  }
});

// GET /products/:id - 商品详情（前端公开）
router.get('/products/:id', (req, res, next) => {
  if (isAdmin(req)) return authAdmin(req, res, next);
  next();
}, (req, res) => {
  try {
    if (isAdmin(req)) {
      // 管理端：可查全部
      const p = get('SELECT * FROM exchange_products WHERE id=?', [req.params.id]);
      if (!p) return res.json(fail('商品不存在'));
      return res.json(success(p));
    } else {
      const p = get('SELECT * FROM exchange_products WHERE id=? AND status=1', [req.params.id]);
      if (!p) return res.json(fail('商品不存在'));
      return res.json(success(p));
    }
  } catch (e) {
    return res.json(fail('获取商品详情失败'));
  }
});

// POST /products - 新增积分商品（仅管理端）
router.post('/products', authAdmin, (req, res) => {
  try {
    const { name, image, points, price, stock, limit_count, description, sort } = req.body;
    if (!name) return res.json(fail('商品名称不能为空'));
    if (!points || points <= 0) return res.json(fail('兑换积分必须大于0'));

    const r = run(`INSERT INTO exchange_products(name,image,points,price,stock,limit_count,description,sort)
      VALUES(?,?,?,?,?,?,?,?)`,
      [name, image||'', points, price||0, stock||0, limit_count||0, description||'', sort||0]);
    return res.json(success({ id: r.lastInsertRowid }, '添加成功'));
  } catch (e) {
    return res.json(fail('添加失败'));
  }
});

// PUT /products/:id - 更新积分商品（仅管理端）
router.put('/products/:id', authAdmin, (req, res) => {
  try {
    const { name, image, points, price, stock, limit_count, description, sort, status } = req.body;
    if (!name) return res.json(fail('商品名称不能为空'));
    let params;
    if (points !== undefined) {
      // 🔒 防免费兑换：更新时不允许把积分改为 0 或负数
      const p = Math.floor(Number(points));
      if (!Number.isFinite(p) || p <= 0) return res.json(fail('兑换积分必须大于0'));
      params = [name, image||'', p, price||0, stock||0, limit_count||0, description||'', sort||0, status||1, req.params.id];
      run(`UPDATE exchange_products SET name=?,image=?,points=?,price=?,stock=?,limit_count=?,description=?,sort=?,status=?,
        updated_at=datetime('now','localtime') WHERE id=?`, params);
    } else {
      // 未传积分则保持原值
      params = [name, image||'', price||0, stock||0, limit_count||0, description||'', sort||0, status||1, req.params.id];
      run(`UPDATE exchange_products SET name=?,image=?,price=?,stock=?,limit_count=?,description=?,sort=?,status=?,
        updated_at=datetime('now','localtime') WHERE id=?`, params);
    }
    return res.json(success(null, '更新成功'));
  } catch (e) {
    return res.json(fail('更新失败'));
  }
});

// DELETE /products/:id - 删除积分商品（仅管理端）
router.delete('/products/:id', authAdmin, (req, res) => {
  try {
    run('DELETE FROM exchange_products WHERE id=?', [req.params.id]);
    return res.json(success(null, '已删除'));
  } catch (e) {
    return res.json(fail('删除失败'));
  }
});

// PUT /products/:id/toggle - 上下架（仅管理端）
router.put('/products/:id/toggle', authAdmin, (req, res) => {
  try {
    const p = get('SELECT status FROM exchange_products WHERE id=?', [req.params.id]);
    if (!p) return res.json(fail('商品不存在'));
    const newStatus = p.status === 1 ? 0 : 1;
    run('UPDATE exchange_products SET status=?,updated_at=datetime(\'now\',\'localtime\') WHERE id=?', [newStatus, req.params.id]);
    return res.json(success({ status: newStatus }, newStatus ? '已上架' : '已下架'));
  } catch (e) {
    return res.json(fail('操作失败'));
  }
});

// ===================================================================
// 兑换订单 API
// ===================================================================

// POST /order - 创建兑换订单（前端需登录）
router.post('/order', authUser, (req, res) => {
  try {
    const { product_id, quantity, recipient_name, recipient_phone, recipient_address, remark } = req.body;
    const qty = Math.max(1, Math.min(999, parseInt(quantity) || 1));

    // 查商品
    const product = get('SELECT * FROM exchange_products WHERE id=? AND status=1', [product_id]);
    if (!product) return res.json(fail('商品不存在或已下架'));
    if (product.stock < qty) return res.json(fail('库存不足'));

    // 查用户积分（独立积分字段 points，与经验值/会员等级解耦）
    const { getBalance } = require('../lib/points');
    const bal = getBalance(req.userId);
    const totalPoints = product.points * qty;
    if (bal.points < totalPoints) return res.json(fail('积分不足，当前积分: ' + bal.points));

    // 每人限兑检查
    if (product.limit_count > 0) {
      const used = get('SELECT COALESCE(SUM(quantity),0) as c FROM exchange_orders WHERE user_id=? AND product_id=? AND status NOT IN (\'cancelled\')',
        [req.userId, product_id]);
      if ((used.c || 0) + qty > product.limit_count) {
        return res.json(fail('每人限兑' + product.limit_count + '件，已兑' + used.c));
      }
    }

    // 生成单号
    const orderNo = 'EX' + Date.now() + String(Math.floor(Math.random() * 900) + 100);

    // 事务：扣积分、扣库存、创建订单
    transaction(() => {
      // 扣用户积分（独立积分，不再扣 experience，避免兑换导致会员降级）
      const { deductPoints } = require('../lib/points');
      const d = deductPoints(req.userId, totalPoints, 'redeem', orderNo, '积分兑换:' + product.name);
      if (!d.ok) throw new Error(d.reason || '积分扣减失败');

      // 扣库存
      const updStock = run('UPDATE exchange_products SET stock=stock-? WHERE id=? AND stock>=?', [qty, product_id, qty]);
      if (updStock.changes === 0) throw new Error('库存扣减失败');

      // 创建订单
      run(`INSERT INTO exchange_orders(order_no,user_id,product_id,product_name,product_image,points,price,quantity,
        recipient_name,recipient_phone,recipient_address,remark)
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`,
        [orderNo, req.userId, product_id, product.name, product.image||'', product.points, product.price||0,
         qty, recipient_name||'', recipient_phone||'', recipient_address||'', remark||'']);
    });

    return res.json(success({ order_no: orderNo }, '兑换成功'));
  } catch (e) {
    console.error('兑换失败:', e);
    return res.json(fail(e.message || '兑换失败'));
  }
});

// GET /orders - 订单列表（前端需登录 / 管理端带分页）
router.get('/orders', (req, res, next) => {
  if (isAdmin(req)) return authAdmin(req, res, next);
  return authUser(req, res, next);
}, (req, res) => {
  try {
    if (isAdmin(req)) {
      // 管理端
      const { page: p = 1, pageSize = 20, status, keyword } = req.query;
      const pageNum = Math.max(1, +p);
      const size = Math.min(100, Math.max(1, +pageSize));
      let where = 'WHERE 1=1';
      const params = [];
      if (status) { where += ' AND eo.status=?'; params.push(status); }
      if (keyword) { where += ' AND (eo.order_no LIKE ? OR eo.recipient_name LIKE ? OR eo.recipient_phone LIKE ?)';
        params.push('%' + keyword + '%', '%' + keyword + '%', '%' + keyword + '%'); }

      const total = get(`SELECT COUNT(*) as c FROM exchange_orders eo ${where}`, params).c;
      const list = all(`SELECT eo.*, u.nickname, u.phone FROM exchange_orders eo LEFT JOIN users u ON eo.user_id=u.id ${where} ORDER BY eo.id DESC LIMIT ? OFFSET ?`,
        [...params, size, (pageNum - 1) * size]);
      return res.json(page(list, total, pageNum, size));
    } else {
      // 前端：我的兑换记录
      const list = all('SELECT * FROM exchange_orders WHERE user_id=? ORDER BY id DESC', [req.userId]);
      return res.json(success(list));
    }
  } catch (e) {
    return res.json(fail('获取订单列表失败'));
  }
});

// GET /orders/:id - 订单详情（前端需登录 / 管理端也可查看）
router.get('/orders/:id', (req, res, next) => {
  if (isAdmin(req)) return authAdmin(req, res, next);
  return authUser(req, res, next);
}, (req, res) => {
  try {
    let order;
    if (isAdmin(req)) {
      order = get('SELECT eo.*, u.nickname, u.phone FROM exchange_orders eo LEFT JOIN users u ON eo.user_id=u.id WHERE eo.id=?', [req.params.id]);
    } else {
      order = get('SELECT * FROM exchange_orders WHERE id=? AND user_id=?', [req.params.id, req.userId]);
    }
    if (!order) return res.json(fail('订单不存在'));
    return res.json(success(order));
  } catch (e) {
    return res.json(fail('获取订单详情失败'));
  }
});

// POST /orders/:id/cancel - 取消兑换（前端需登录）
router.post('/orders/:id/cancel', authUser, (req, res) => {
  try {
    const order = get('SELECT * FROM exchange_orders WHERE id=? AND user_id=?', [req.params.id, req.userId]);
    if (!order) return res.json(fail('订单不存在'));
    if (order.status !== 'pending') return res.json(fail('仅待处理订单可取消'));

    transaction(() => {
      const totalPoints = order.points * order.quantity;
      // 返还积分（记流水, 不再加 experience）
      const { addPoints } = require('../lib/points');
      addPoints(order.user_id, totalPoints, 'refund', order.order_no || ('EX' + order.id), '兑换订单取消返还积分');
      run('UPDATE exchange_products SET stock=stock+? WHERE id=?', [order.quantity, order.product_id]);
      run("UPDATE exchange_orders SET status='cancelled' WHERE id=?", [order.id]);
    });

    return res.json(success(null, '已取消'));
  } catch (e) {
    return res.json(fail('取消失败'));
  }
});

// PUT /orders/:id/ship - 发货（仅管理端）
router.put('/orders/:id/ship', authAdmin, (req, res) => {
  try {
    const order = get('SELECT * FROM exchange_orders WHERE id=?', [req.params.id]);
    if (!order) return res.json(fail('订单不存在'));
    if (order.status !== 'pending') return res.json(fail('仅待处理订单可发货'));

    run("UPDATE exchange_orders SET status='shipped',shipped_at=datetime('now','localtime') WHERE id=?", [req.params.id]);
    return res.json(success(null, '发货成功'));
  } catch (e) {
    return res.json(fail('发货失败'));
  }
});

// PUT /orders/:id/receive - 确认收货（仅管理端）
router.put('/orders/:id/receive', authAdmin, (req, res) => {
  try {
    const order = get('SELECT * FROM exchange_orders WHERE id=?', [req.params.id]);
    if (!order) return res.json(fail('订单不存在'));
    if (order.status !== 'shipped') return res.json(fail('仅已发货订单可确认收货'));

    run("UPDATE exchange_orders SET status='received',received_at=datetime('now','localtime') WHERE id=?", [req.params.id]);
    return res.json(success(null, '已确认收货'));
  } catch (e) {
    return res.json(fail('操作失败'));
  }
});

module.exports = router;
