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 } = require('../middleware/auth');

// 可领优惠券
router.get('/coupons', (req, res) => {
  const now = new Date().toISOString();
  const list = all("SELECT * FROM coupons WHERE status=1 AND (end_time IS NULL OR end_time>=?) ORDER BY id DESC", [now]);
  return res.json(success(list));
});

// ===================== 促销中心聚合 =====================
// v1.5 顺序串行聚合 秒杀/拼团/砍价/预售/优惠券 进行中活动，统一归一化结构
router.get('/promotion-center', (req, res) => {
  try {
    const now = new Date().toISOString();
    // 软鉴权: 有 token 则解析出 userId(用于优惠券 claimed 按用户判断), 无 token 保持匿名公开
    let userId = req.userId || null;
    if (!userId) {
      try {
        const h = req.headers.authorization || '';
        if (h.indexOf('Bearer ') === 0) {
          const tk = h.slice(7);
          const cfg = require('../../config');
          const payload = require('jsonwebtoken').verify(tk, cfg.jwtSecret);
          if (payload && payload.userId) userId = payload.userId;
        }
      } catch (e) { userId = null; }
    }
    const list = [];
    const count = { seckill: 0, groupon: 0, bargain: 0, presale: 0, coupon: 0, total: 0 };

    // —— 1. 秒杀（进行中）——
    const seckills = all("SELECT sp.*, p.name, p.image, p.price AS original_price FROM seckill_products sp JOIN products p ON sp.product_id=p.id WHERE sp.status=1 AND sp.start_time<=? AND sp.end_time>=? ORDER BY sp.end_time ASC LIMIT 10", [now, now]);
    seckills.forEach(function(s){ count.seckill++; count.total++; list.push({ type:'seckill', title:'限时秒杀', icon:'⚡', id:s.id, name:s.name||'秒杀商品', image:s.image||'', origin_price:+(Number(s.original_price)).toFixed(2), price:+(+s.seckill_price/100).toFixed(2), stock:s.stock||0, sales:s.sales||0, end_at:s.end_time, link:'/seckill', ended:false }); });

    // —— 2. 拼团（进行中）——
    const groups = all("SELECT gb.*, p.name, p.image, p.price AS original_price FROM group_buy_products gb JOIN products p ON gb.product_id=p.id WHERE gb.status=1 AND gb.start_time<=? AND gb.end_time>=? ORDER BY gb.end_time ASC LIMIT 10", [now, now]);
    groups.forEach(function(g){ count.groupon++; count.total++; list.push({ type:'groupon', title:'多人拼团', icon:'🫂', id:g.id, name:g.name||'拼团商品', image:g.image||'', origin_price:+(Number(g.original_price)).toFixed(2), price:+(+g.group_price/100).toFixed(2), stock:g.stock||0, sales:g.sales||0, min_people:g.min_people||2, end_at:g.end_time, link:'/group-buy', ended:false }); });

    // —— 3. 砍价（进行中）——
    const bargains = all("SELECT ba.*, p.name AS product_name, p.image AS product_image, p.price AS product_price FROM bargain_activities ba LEFT JOIN products p ON ba.product_id=p.id WHERE ba.status=1 AND ba.start_time<=? AND ba.end_time>=? ORDER BY ba.end_time ASC LIMIT 10", [now, now]);
    bargains.forEach(function(b){ count.bargain++; count.total++; list.push({ type:'bargain', title:'好友砍价', icon:'🔪', id:b.id, name:b.name||b.product_name||'砍价商品', image:b.image||b.product_image||'', origin_price:b.original_price?+(+b.original_price/100).toFixed(2):+(+b.product_price/100).toFixed(2), price:b.floor_price?+(+b.floor_price/100).toFixed(2):0, stock:b.stock||0, sales:b.sales||0, end_at:b.end_time, link:'/bargain', ended:false }); });

    // —— 4. 预售（定金期内）——
    const presales = all("SELECT pp.*, p.name AS product_name, p.image AS product_image, p.price AS product_price FROM presale_products pp LEFT JOIN products p ON pp.product_id=p.id WHERE pp.status=1 ORDER BY pp.id DESC LIMIT 10");
    presales.forEach(function(pr){ count.presale++; count.total++; list.push({ type:'presale', title:'定金预售', icon:'🚀', id:pr.id, name:pr.name||pr.product_name||'预售商品', image:pr.image||pr.product_image||'', origin_price:pr.product_price?+(Number(pr.product_price)).toFixed(2):0, price:pr.deposit?+(+pr.deposit/100).toFixed(2):0, stock:pr.total_stock||0, sales:pr.sales||0, deposit:pr.deposit?+(+pr.deposit/100).toFixed(2):0, end_at:pr.final_end_time||'', link:'/presale', ended:false }); });

    // —— 5. 优惠券（可领取列表）——
    const coupons = all("SELECT * FROM coupons WHERE status=1 AND (end_time IS NULL OR end_time>=?) ORDER BY id DESC LIMIT 10", [now]);
    coupons.forEach(function(cp){
      let claimed = false;
      let remained = Math.max(0, cp.total_count - cp.used_count);
      if (userId) { const n = get('SELECT COUNT(*) as c FROM user_coupons WHERE user_id=? AND coupon_id=?', [userId, cp.id]); claimed = (n.c || 0) >= (cp.per_limit || 1); }
      count.coupon++; count.total++;
      list.push({ type:'coupon', title:'领券中心', icon:'🎫', id:cp.id, name:cp.name, image:'', origin_price:0, price:cp.value||0, min_amount:cp.min_amount||0, value:cp.value||0, valid_days:cp.valid_days||0, remained, claimed, end_at:cp.end_time||'', link:'/coupon', ended:false });
    });

    return res.json(success({ list, count }));
  } catch (e) {
    return res.json(fail('促销中心数据获取失败'));
  }
});

// 领券
router.post('/coupon/receive', authUser, (req, res) => {
  try {
    const { coupon_id } = req.body;
    const coupon = get('SELECT * FROM coupons WHERE id=? AND status=1', [coupon_id]);
    if (!coupon) return res.json(fail('优惠券不存在'));

    // 🔒 限量校验移入事务并原子化，防并发超发
    transaction(() => {
      const count = get('SELECT COUNT(*) as c FROM user_coupons WHERE user_id=? AND coupon_id=?', [req.userId, coupon_id]).c;
      if (count >= coupon.per_limit) throw new Error('已领完该优惠券');

      // 原子领取总量控制：CAS 判断 used_count < total_count 才累加
      const upd = run('UPDATE coupons SET used_count=used_count+1 WHERE id=? AND used_count<?', [coupon_id, coupon.total_count]);
      if (!upd.changes || upd.changes === 0) throw new Error('优惠券已被领完');

      const expired = new Date();
      if (coupon.valid_days) {
        expired.setDate(expired.getDate() + coupon.valid_days);
      } else if (coupon.end_time) {
        expired.setTime(new Date(coupon.end_time).getTime());
      } else {
        expired.setDate(expired.getDate() + 30);
      }

      run('INSERT INTO user_coupons(user_id,coupon_id,expired_time) VALUES(?,?,?)', [req.userId, coupon_id, expired.toISOString()]);
    });

    return res.json(success(null, '领券成功'));
  } catch (e) {
    return res.json(fail('领券失败'));
  }
});

// 我的优惠券
router.get('/my-coupons', authUser, (req, res) => {
  const { status } = req.query;
  let where = 'WHERE uc.user_id=?';
  const params = [req.userId];
  if (status === 'unused') { where += " AND uc.status='unused'"; }
  else if (status === 'used') { where += " AND uc.status='used'"; }
  else if (status === 'expired') { where += " AND uc.status='expired'"; }

  const list = all(`SELECT uc.*, c.name,c.type,c.value,c.min_amount,c.max_amount AS condition_text
    FROM user_coupons uc JOIN coupons c ON uc.coupon_id=c.id ${where} ORDER BY uc.id DESC`, params);
  return res.json(success(list));
});

// 用户优惠券别名（匹配移动端接口）
router.get('/coupon/user', authUser, (req, res) => {
  const { status } = req.query;
  let where = 'WHERE uc.user_id=?';
  const params = [req.userId];
  if (status === 'unused') { where += " AND uc.status='unused'"; }
  else if (status === 'used') { where += " AND uc.status='used'"; }
  else if (status === 'expired') { where += " AND uc.status='expired'"; }
  const list = all(`SELECT uc.*, c.name,c.type,c.value,c.min_amount,c.max_amount AS condition_text, uc.expired_time AS expire_at
    FROM user_coupons uc JOIN coupons c ON uc.coupon_id=c.id ${where} ORDER BY uc.id DESC`, params);
  return res.json(success(list));
});

// 秒杀列表
router.get('/seckill/list', (req, res) => {
  const now = new Date().toISOString();
  const list = all("SELECT sp.*, p.name,p.image,p.price as original_price FROM seckill_products sp JOIN products p ON sp.product_id=p.id WHERE sp.status=1 AND sp.start_time<=? AND sp.end_time>=? ORDER BY sp.id DESC", [now, now]);
  return res.json(success(list));
});

// 秒杀详情
router.get('/seckill/:id', (req, res) => {
  const item = get("SELECT sp.*, p.name,p.image,p.price as original_price,p.description FROM seckill_products sp JOIN products p ON sp.product_id=p.id WHERE sp.id=?", [req.params.id]);
  if (!item) return res.json(fail('秒杀活动不存在'));
  return res.json(success(item));
});

// 拼团列表
router.get('/group-buy/list', (req, res) => {
  const now = new Date().toISOString();
  const list = all("SELECT gb.*, p.name,p.image,p.price as original_price FROM group_buy_products gb JOIN products p ON gb.product_id=p.id WHERE gb.status=1 AND gb.start_time<=? AND gb.end_time>=? ORDER BY gb.id DESC", [now, now]);
  return res.json(success(list));
});

// 拼团详情
router.get('/group-buy/:id', (req, res) => {
  const item = get("SELECT gb.*, p.name,p.image,p.price as original_price,p.description FROM group_buy_products gb JOIN products p ON gb.product_id=p.id WHERE gb.id=?", [req.params.id]);
  if (!item) return res.json(fail('拼团活动不存在'));
  return res.json(success(item));
});

// 满减满送活动列表（H5端）
router.get('/promotions', (req, res) => {
  const now = new Date().toISOString().replace('T',' ').substring(0,19);
  const list = all(`SELECT * FROM promotions WHERE status=1 AND (is_forever=1 OR (start_time<=? AND end_time>=?)) ORDER BY sort ASC`,[now,now]);
  res.json(success(list.map(p=>({...p,rules:JSON.parse(p.rules||'[]'),scope_values:JSON.parse(p.scope_values||'[]')}))));
});

// 计算订单可用优惠
router.post('/promotions/calc', (req, res) => {
  try {
    const { total_amount, total_quantity, product_ids, category_ids } = req.body;
    const { calcBestPromotion } = require('../lib/promotion-engine');
    const result = calcBestPromotion(total_amount||0, total_quantity||0, product_ids||[], category_ids||[]);
    res.json(success(result));
  } catch(e) {
    res.json(fail('计算失败'));
  }
});

// ========== 秒杀购买 ==========
router.post('/seckill/buy', authUser, (req, res) => {
  try {
    const { seckill_id } = req.body;
    const now = new Date().toISOString();
    const item = get('SELECT sp.*, p.name, p.image, p.price as original_price FROM seckill_products sp JOIN products p ON sp.product_id=p.id WHERE sp.id=? AND sp.status=1', [seckill_id]);
    if (!item) return res.json(fail('秒杀活动不存在'));
    if (item.start_time > now || item.end_time < now) return res.json(fail('秒杀不在活动时间内'));
    if (item.stock <= 0) return res.json(fail('已抢光'));

    // 创建订单（限购检查移入事务，防并发超限购）
    const orderNo = 'MS' + Date.now() + Math.floor(Math.random() * 1000);
    const result = transaction(() => {
      // 🔒 原子扣库存(CAS)，并检查库存是否真的扣到（防秒杀超卖：stock已0时UPDATE影响0行）
      const upd = run('UPDATE seckill_products SET stock=stock-1, sales=sales+1 WHERE id=? AND stock>0', [seckill_id]);
      if (!upd.changes || upd.changes === 0) throw new Error('已抢光');
      // 每人限购（事务内重新校验，防并发超限购）
      const bought = get('SELECT COUNT(*) as c FROM orders o JOIN order_items oi ON o.id=oi.order_id WHERE o.user_id=? AND oi.product_id=? AND oi.price=?', [req.userId, item.product_id, item.seckill_price]);
      if (bought && bought.c >= item.per_limit) throw new Error(`每人限购${item.per_limit}件`);
      run('UPDATE products SET sales=sales+1 WHERE id=?', [item.product_id]);
      run(`INSERT INTO orders(order_no,user_id,total_amount,discount_amount,pay_amount,status,remark)
        VALUES(?,?,?,0,?,'pending_pay','秒杀订单')`,
        [orderNo, req.userId, item.seckill_price, item.seckill_price]);
      const order = get('SELECT id FROM orders WHERE order_no=?', [orderNo]);
      run(`INSERT INTO order_items(order_id,product_id,product_name,image,price,quantity,subtotal) VALUES(?,?,?,?,?,?,?)`,
        [order.id, item.product_id, item.name, item.image, item.seckill_price, 1, item.seckill_price]);
      return order;
    });

    return res.json(success({ order_no: orderNo, pay_amount: item.seckill_price }, '秒杀成功，请及时支付'));
  } catch(e) {
    return res.json(fail(e.message || '秒杀失败'));
  }
});

// ========== 每日签到 ==========
const CHECKIN_REWARDS = [
  { min_days: 60, points: 200 },
  { min_days: 30, points: 100 },
  { min_days: 15, points: 50 },
  { min_days: 7, points: 30 },
  { min_days: 3, points: 10 },
  { min_days: 1, points: 5 },
];

    // NOTE: CHECKIN_REWARDS 仅 6 项，遍历匹配足够简单清晰

function getCheckinReward(streak) {
  for (const r of CHECKIN_REWARDS) {
    if (streak >= r.min_days) return r.points;
  }
  return 5;
}

router.get('/checkin/status', authUser, (req, res) => {
  try {
    const today = new Date().toISOString().split('T')[0];
    const checkedToday = get("SELECT id FROM user_checkins WHERE user_id=? AND date(created_at)=?", [req.userId, today]);
    // 计算连续签到天数
    const recent = all("SELECT date(created_at) as d FROM user_checkins WHERE user_id=? ORDER BY d DESC LIMIT 60", [req.userId]);
    let streak = 0;
    if (recent.length > 0) {
      const todayDate = new Date(today);
      for (let i = 0; i < recent.length; i++) {
        const d = new Date(recent[i].d);
        const diff = Math.round((todayDate - d) / 86400000);
        if (diff === i || (i === 0 && diff <= 1)) {
          streak++;
        } else {
          break;
        }
      }
    }
    // 最近10条记录
    const records = all("SELECT * FROM user_checkins WHERE user_id=? ORDER BY id DESC LIMIT 10", [req.userId]);
    return res.json(success({
      streak,
      checked_today: !!checkedToday,
      records
    }));
  } catch(e) {
    return res.json(fail('获取签到状态失败'));
  }
});

router.post('/checkin', authUser, (req, res) => {
  try {
    const today = new Date().toISOString().split('T')[0];
    const checkedToday = get("SELECT id FROM user_checkins WHERE user_id=? AND date(created_at)=?", [req.userId, today]);
    if (checkedToday) return res.json(fail('今日已签到'));

    // 获取当前连续天数
    const statusRes = {};
    const recent = all("SELECT date(created_at) as d FROM user_checkins WHERE user_id=? ORDER BY d DESC LIMIT 60", [req.userId]);
    let streak = 0;
    if (recent.length > 0) {
      const todayDate = new Date(today);
      for (let i = 0; i < recent.length; i++) {
        const d = new Date(recent[i].d);
        const diff = Math.round((todayDate - d) / 86400000);
        if (diff === i + 1) { streak++; } else { break; }
      }
    }
    streak += 1; // 加上今天

    const points = getCheckinReward(streak);
    // 签到奖励：发独立积分(不再污染经验值/会员等级)，并记流水
    const reward = (() => {
      try {
        const { addPoints } = require('../lib/points');
        run('INSERT INTO user_checkins(user_id, points, streak) VALUES(?,?,?)', [req.userId, points, streak]);
        addPoints(req.userId, points, 'sign', 'sign-' + today, '每日签到');
        return { ok: true };
      } catch (e) { return { ok: false, reason: e.message }; }
    })();
    if (!reward.ok) return res.json(fail(reward.reason || '签到失败'));

    return res.json(success({ points, streak }, `签到成功！获得${points}积分`));
  } catch(e) {
    return res.json(fail(e.message || '签到失败'));
  }
});

module.exports = router;
