const express = require('express');

const presaleRouter = express.Router();
const bulkGroupRouter = express.Router();

const { get, run, all, transaction } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { mul, add, sub, toNum } = require('../utils/money');
const { authUser } = require('../middleware/auth');
const { authAdmin } = require('../middleware/auth');
const { isPremium } = require('../lib/limits');
const paymentSdk = require('../lib/payment');

    // NOTE: genOrderNo 前缀+日期+随机数，单日碰撞概率极低

function genOrderNo(prefix) {
  const now = new Date();
  const date = `${now.getFullYear()}${String(now.getMonth()+1).padStart(2,'0')}${String(now.getDate()).padStart(2,'0')}`;
  const rand = String(Math.floor(Math.random() * 1000000)).padStart(6, '0');
  return `${prefix}${date}${rand}`;
}

// ===================== 预售 API =====================

// 预售活动列表（前端公开）
presaleRouter.get('/list', (req, res) => {
  try {
    const { page: p = 1, pageSize = 20 } = 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 presale_products WHERE status=1').c;
    const list = 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 ? OFFSET ?`, [size, (pageNum - 1) * size]);
    return res.json(page(list, total, pageNum, size));
  } catch (e) {
    return res.json(fail('获取失败'));
  }
});

// ============ 预售辅助：生成支付流水 + 模拟确认 ============

// 生成支付流水（未支付/pending），返回可达的模拟支付地址；生产模式下由真实回调确认
function createPresalePayment(order, stage) {
  const tradeNo = (stage === 'deposit' ? 'DYS' : 'WYS') + Date.now() + Math.floor(Math.random()*900+100);
  const amount = stage === 'deposit' ? order.deposit : order.final_amount;
  const orderId = order.id;
  // 写 pending 支付流水；amount 用货币工具转分避免浮点误差
  const amountCents = Math.round(toNum(amount) * 100);
  run(`INSERT INTO payment_records(trade_no,order_id,user_id,amount,method,status,created_at)
       VALUES(?,?,?,?,?,?,datetime('now','localtime'))`,
    [tradeNo, orderId, order.user_id, toNum(amount), order.payment_method || 'wechat', 'pending']);
  run(`UPDATE presale_orders SET trade_no=?, payment_method=? WHERE order_no=?`,
    [tradeNo, order.payment_method || 'wechat', order.order_no]);
  // 模拟模式下返回可达的确认地址；生产模式返回空（真实支付回调）
  let payUrl = null;
  if (paymentSdk.isSimulateMode()) {
    payUrl = `/api/presale/mock-pay?trade_no=${tradeNo}&stage=${stage}&order_no=${order.order_no}`;
  }
  return { trade_no: tradeNo, amount: toNum(amount), stage, pay_url: payUrl, is_mock: paymentSdk.isSimulateMode() };
}

// 模拟支付确认入口（仅 simulate 模式可用，防伪造）
presaleRouter.get('/mock-pay', (req, res) => {
  if (!paymentSdk.isSimulateMode()) return res.status(403).json(fail('模拟支付已禁用'));
  const { trade_no, stage, order_no } = req.query;
  if (!trade_no || !stage || !order_no) return res.json(fail('参数缺失'));
  try {
    const pay = get('SELECT * FROM payment_records WHERE trade_no=?', [trade_no]);
    if (!pay || pay.status === 'success') {
      return res.json(fail(pay ? '该流水已支付' : '流水不存在'));
    }
    const order = get('SELECT * FROM presale_orders WHERE order_no=?', [order_no]);
    if (!order || String(order.id) !== String(pay.order_id)) return res.json(fail('订单与流水不匹配'));
    const expect = stage === 'deposit' ? order.deposit : order.final_amount;
    if (Math.abs(toNum(pay.amount) - toNum(expect)) > 0.001) return res.json(fail('支付金额校验失败'));

    transaction(() => {
      run(`UPDATE payment_records SET status='success',pay_time=datetime('now','localtime') WHERE trade_no=?`, [trade_no]);
      if (stage === 'deposit') {
        run(`UPDATE presale_orders SET status='deposit_paid',deposit_paid_at=datetime('now','localtime') WHERE order_no=?`, [order_no]);
      } else {
        run(`UPDATE presale_orders SET status='final_paid',final_paid_at=datetime('now','localtime') WHERE order_no=?`, [order_no]);
      }
    });
    return res.json(success(null, stage === 'deposit' ? '定金支付成功' : '尾款支付成功'));
  } catch (e) {
    return res.json(fail('确认失败'));
  }
});

// 预售详情（含商品图/描述）
presaleRouter.get('/:id', (req, res) => {
  try {
    const pp = get(`SELECT pp.*, p.name as product_name, p.image as product_image, p.images, p.description, p.price as product_price, p.stock as product_stock
      FROM presale_products pp LEFT JOIN products p ON pp.product_id=p.id WHERE pp.id=?`, [req.params.id]);
    if (!pp) return res.json(fail('预售活动不存在'));
    return res.json(success(pp));
  } catch (e) {
    return res.json(fail('获取失败'));
  }
});

// 预付定金（需登录）→ 创建待付定金订单，返回支付流水
presaleRouter.post('/order', authUser, (req, res) => {
  try {
    if (!isPremium()) return res.json(fail('付费版专属功能'));
    const { presale_id, product_id, quantity, payment_method } = req.body;
    // 🔒 数量钳制：仅允许 1-999 正整数，防 0/负数/浮点导致负金额或超卖
    const qty = Math.max(1, Math.min(999, Math.floor(Number(quantity)) || 1));
    const method = payment_method === 'alipay' ? 'alipay' : 'wechat';
    const pp = get('SELECT * FROM presale_products WHERE id=? AND status=1', [presale_id]);
    if (!pp) return res.json(fail('预售活动不存在或已结束'));
    let created;
    transaction(() => {
      if (pp.total_stock > 0) {
        const sold = get('SELECT COALESCE(SUM(quantity),0) as s FROM presale_orders WHERE presale_id=? AND status!=\'cancelled\'', [presale_id]).s;
        if (sold + qty > pp.total_stock) throw new Error('库存不足');
      }
      if (pp.limit_count > 0) {
        const userCount = get('SELECT COALESCE(SUM(quantity),0) as c FROM presale_orders WHERE presale_id=? AND user_id=? AND status!=\'cancelled\'', [presale_id, req.userId]).c;
        if (userCount + qty > pp.limit_count) throw new Error('超出限购数量');
      }
      const product = get('SELECT name, image, price FROM products WHERE id=?', [product_id]);
      if (!product) throw new Error('商品不存在');

      const deposit = mul(pp.deposit, qty);
      const depositExpand = mul(pp.deposit_expand, qty);
      const finalAmount = Math.max(0, sub(mul(product.price, qty), depositExpand));
      const totalAmount = add(deposit, finalAmount);
      const orderNo = genOrderNo('YS');

      run(`INSERT INTO presale_orders(order_no,user_id,presale_id,product_id,product_name,product_image,
        quantity,deposit,deposit_expand,final_amount,total_amount,status,payment_method)
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`,
        [orderNo, req.userId, presale_id, product_id, product.name, product.image||'',
         qty, deposit, depositExpand, finalAmount, totalAmount, 'deposit_pending', method]);
      const order = get('SELECT * FROM presale_orders WHERE order_no=?', [orderNo]);
      created = { order_no: orderNo, id: order.id, deposit, deposit_expand: depositExpand, final_amount: finalAmount, total_amount: totalAmount };
      // 生成定金支付流水
      const pay = createPresalePayment(order, 'deposit');
      Object.assign(created, pay);
    });
    return res.json(success(created, '定金订单已创建，请完成支付'));
  } catch (e) {
    return res.json(fail(e.message || '操作失败'));
  }
});

// 支付尾款 → 校验真实已付定金，发起尾款支付流水
presaleRouter.post('/order/:orderNo/pay-final', authUser, (req, res) => {
  try {
    const order = get('SELECT * FROM presale_orders WHERE order_no=? AND user_id=?', [req.params.orderNo, req.userId]);
    if (!order) return res.json(fail('订单不存在'));
    if (order.status !== 'deposit_paid') return res.json(fail('当前状态不可支付尾款（需先完成定金支付）'));

    const pp = get('SELECT * FROM presale_products WHERE id=?', [order.presale_id]);
    if (!pp) return res.json(fail('预售活动不存在'));
    if (pp.final_start_time && new Date(pp.final_start_time) > new Date()) return res.json(fail('尾款支付尚未开始'));
    if (pp.final_end_time && new Date(pp.final_end_time) < new Date()) return res.json(fail('尾款支付已截止'));

    // 校验定金是否真实支付成功（payment_records 有成功记录）
    const depositPay = get('SELECT * FROM payment_records WHERE order_id=? AND amount=? AND status=\'success\'', [order.id, toNum(order.deposit)]);
    if (!depositPay) return res.json(fail('定金支付状态异常，无法支付尾款'));

    const pay = createPresalePayment(order, 'final');
    return res.json(success(pay, '尾款支付已发起，请完成支付'));
  } catch (e) {
    return res.json(fail('操作失败'));
  }
});

// 我的预售订单
presaleRouter.get('/orders', 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 presale_orders WHERE user_id=?', [req.userId]).c;
    const list = all('SELECT * FROM presale_orders WHERE user_id=? ORDER BY id DESC LIMIT ? OFFSET ?', [req.userId, size, (pageNum - 1) * size]);
    return res.json(page(list, total, pageNum, size));
  } catch (e) {
    return res.json(fail('获取失败'));
  }
});

// ===================== 阶梯团购 API =====================

// 团购活动列表（前端公开）
bulkGroupRouter.get('/list', (req, res) => {
  try {
    const { page: p = 1, pageSize = 20 } = 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 bulk_group_products WHERE status=1').c;
    const list = all(`SELECT bg.*, p.name as product_name, p.image as product_image, p.price as product_price 
      FROM bulk_group_products bg LEFT JOIN products p ON bg.product_id=p.id 
      WHERE bg.status=1 ORDER BY bg.id DESC LIMIT ? OFFSET ?`, [size, (pageNum - 1) * size]);
    return res.json(page(list, total, pageNum, size));
  } catch (e) {
    return res.json(fail('获取失败'));
  }
});

// 团购详情
bulkGroupRouter.get('/:id', (req, res) => {
  try {
    const bg = get(`SELECT bg.*, p.name as product_name, p.image as product_image, p.price as product_price, 
      p.images, p.description, p.stock as product_stock 
      FROM bulk_group_products bg LEFT JOIN products p ON bg.product_id=p.id WHERE bg.id=?`, [req.params.id]);
    if (!bg) return res.json(fail('活动不存在'));
    bg.tiers = JSON.parse(bg.tiers || '[]');
    return res.json(success(bg));
  } catch (e) {
    return res.json(fail('获取失败'));
  }
});

// 下单（根据数量匹配阶梯价格）
bulkGroupRouter.post('/order', authUser, (req, res) => {
  try {
    if (!isPremium()) return res.json(fail('付费版专属功能'));

    const { bulk_id, product_id, quantity } = req.body;
    // 🔒 数量钳制：仅允许 1-999 正整数，防 0/负数/浮点导致负金额或超卖
    const qty = Math.max(1, Math.min(999, Math.floor(Number(quantity)) || 1));
    const bg = get('SELECT * FROM bulk_group_products WHERE id=? AND status=1', [bulk_id]);
    if (!bg) return res.json(fail('团购活动不存在或已结束'));
    
    const now = new Date();
    if (bg.start_time && new Date(bg.start_time) > now) return res.json(fail('活动尚未开始'));
    if (bg.end_time && new Date(bg.end_time) < now) return res.json(fail('活动已结束'));

    let result;
    transaction(() => {
      if (bg.total_stock > 0) {
        const sold = get('SELECT COALESCE(SUM(quantity),0) as s FROM bulk_group_orders WHERE bulk_id=? AND status=\'paid\'', [bulk_id]).s;
        if (sold + qty > bg.total_stock) throw new Error('库存不足');
      }
      if (bg.limit_count > 0) {
        const userCount = get('SELECT COALESCE(SUM(quantity),0) as c FROM bulk_group_orders WHERE bulk_id=? AND user_id=? AND status=\'paid\'', [bulk_id, req.userId]).c;
        if (userCount + qty > bg.limit_count) throw new Error('超出限购数量');
      }

      const tiers = JSON.parse(bg.tiers || '[]');
      if (!tiers.length) throw new Error('阶梯价格未设置');

      // 向下匹配：找满足数量的最大阶梯
      let matchedTier = tiers[0];
      for (const t of tiers) {
        if (qty >= t.min_qty) matchedTier = t;
      }
      const unitPrice = matchedTier.price;
      const totalAmount = mul(unitPrice, qty);
      const product = get('SELECT name, image FROM products WHERE id=?', [product_id]);
      if (!product) throw new Error('商品不存在');

      const orderNo = genOrderNo('TG');

      run(`INSERT INTO bulk_group_orders(order_no,user_id,bulk_id,product_id,product_name,quantity,unit_price,total_amount,status,paid_at)
        VALUES(?,?,?,?,?,?,?,?,?,datetime('now','localtime'))`,
        [orderNo, req.userId, bulk_id, product_id, product.name, qty, unitPrice, totalAmount, 'paid']);
      result = { order_no: orderNo, unit_price: unitPrice, total_amount: totalAmount, tier_min_qty: matchedTier.min_qty };
    });
    return res.json(success(result, '下单成功'));
  } catch (e) {
    return res.json(fail(e.message || '操作失败'));
  }
});

// 我的团购订单
bulkGroupRouter.get('/orders', 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 bulk_group_orders WHERE user_id=?', [req.userId]).c;
    const list = all('SELECT * FROM bulk_group_orders WHERE user_id=? ORDER BY id DESC LIMIT ? OFFSET ?', [req.userId, size, (pageNum - 1) * size]);
    return res.json(page(list, total, pageNum, size));
  } catch (e) {
    return res.json(fail('获取失败'));
  }
});

// ===================== 后台管理 API =====================
// 这些路由注册在 /api/admin 下，但在 app.js 中会额外挂载

// --- 后台预售管理 ---
const adminPresale = express.Router();

adminPresale.get('/presale', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 15 } = 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 presale_products').c;
  const list = all(`SELECT pp.*, p.name as product_name FROM presale_products pp LEFT JOIN products p ON pp.product_id=p.id ORDER BY pp.id DESC LIMIT ? OFFSET ?`, [size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

adminPresale.post('/presale', authAdmin, (req, res) => {
  const { product_id, name, deposit, deposit_expand, final_start_time, final_end_time, delivery_time, total_stock, limit_count } = req.body;
  const r = run(`INSERT INTO presale_products(product_id,name,deposit,deposit_expand,final_start_time,final_end_time,delivery_time,total_stock,limit_count)
    VALUES(?,?,?,?,?,?,?,?,?)`, [product_id, name, deposit||0, deposit_expand||0, final_start_time||null, final_end_time||null, delivery_time||'', total_stock||0, limit_count||0]);
  return res.json(success({ id: r.lastInsertRowid }, '添加成功'));
});

adminPresale.put('/presale/:id', authAdmin, (req, res) => {
  const { product_id, name, deposit, deposit_expand, final_start_time, final_end_time, delivery_time, total_stock, limit_count, status } = req.body;
  run(`UPDATE presale_products SET product_id=?,name=?,deposit=?,deposit_expand=?,final_start_time=?,final_end_time=?,delivery_time=?,total_stock=?,limit_count=?,status=?,updated_at=datetime('now','localtime') WHERE id=?`,
    [product_id, name, deposit||0, deposit_expand||0, final_start_time||null, final_end_time||null, delivery_time||'', total_stock||0, limit_count||0, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});

adminPresale.delete('/presale/:id', authAdmin, (req, res) => {
  run('DELETE FROM presale_products WHERE id=?', [req.params.id]);
  return res.json(success(null, '删除成功'));
});

adminPresale.put('/presale/:id/toggle', authAdmin, (req, res) => {
  const p = get('SELECT status FROM presale_products WHERE id=?', [req.params.id]);
  if (!p) return res.json(fail('活动不存在'));
  const newStatus = p.status === 1 ? 0 : 1;
  run('UPDATE presale_products SET status=?,updated_at=datetime(\'now\',\'localtime\') WHERE id=?', [newStatus, req.params.id]);
  return res.json(success({ status: newStatus }, newStatus ? '已上架' : '已下架'));
});

adminPresale.get('/presale/orders', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 15, keyword, status } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(50, Math.max(1, +pageSize));
  let where = 'WHERE 1=1';
  const params = [];
  if (keyword) { where += ' AND (po.order_no LIKE ? OR po.product_name LIKE ?)'; params.push(`%${keyword}%`, `%${keyword}%`); }
  if (status) { where += ' AND po.status=?'; params.push(status); }
  const total = get(`SELECT COUNT(*) as c FROM presale_orders po ${where}`, params).c;
  const list = all(`SELECT po.*, u.nickname FROM presale_orders po LEFT JOIN users u ON po.user_id=u.id ${where} ORDER BY po.id DESC LIMIT ? OFFSET ?`,
    [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

// --- 后台阶梯团购管理 ---
adminPresale.get('/bulk-group', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 15 } = 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 bulk_group_products').c;
  const list = all(`SELECT bg.*, p.name as product_name FROM bulk_group_products bg LEFT JOIN products p ON bg.product_id=p.id ORDER BY bg.id DESC LIMIT ? OFFSET ?`, [size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

adminPresale.post('/bulk-group', authAdmin, (req, res) => {
  const { product_id, name, tiers, total_stock, min_people, limit_count, start_time, end_time } = req.body;
  const r = run(`INSERT INTO bulk_group_products(product_id,name,tiers,total_stock,min_people,limit_count,start_time,end_time)
    VALUES(?,?,?,?,?,?,?,?)`, [product_id, name, JSON.stringify(tiers||[]), total_stock||0, min_people||1, limit_count||0, start_time||null, end_time||null]);
  return res.json(success({ id: r.lastInsertRowid }, '添加成功'));
});

adminPresale.put('/bulk-group/:id', authAdmin, (req, res) => {
  const { product_id, name, tiers, total_stock, min_people, limit_count, start_time, end_time, status } = req.body;
  run(`UPDATE bulk_group_products SET product_id=?,name=?,tiers=?,total_stock=?,min_people=?,limit_count=?,start_time=?,end_time=?,status=?,updated_at=datetime('now','localtime') WHERE id=?`,
    [product_id, name, JSON.stringify(tiers||[]), total_stock||0, min_people||1, limit_count||0, start_time||null, end_time||null, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});

adminPresale.delete('/bulk-group/:id', authAdmin, (req, res) => {
  run('DELETE FROM bulk_group_products WHERE id=?', [req.params.id]);
  return res.json(success(null, '删除成功'));
});

adminPresale.put('/bulk-group/:id/toggle', authAdmin, (req, res) => {
  const p = get('SELECT status FROM bulk_group_products WHERE id=?', [req.params.id]);
  if (!p) return res.json(fail('活动不存在'));
  const newStatus = p.status === 1 ? 0 : 1;
  run('UPDATE bulk_group_products SET status=?,updated_at=datetime(\'now\',\'localtime\') WHERE id=?', [newStatus, req.params.id]);
  return res.json(success({ status: newStatus }, newStatus ? '已上架' : '已下架'));
});

adminPresale.get('/bulk-group/orders', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 15, keyword, status } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(50, Math.max(1, +pageSize));
  let where = 'WHERE 1=1';
  const params = [];
  if (keyword) { where += ' AND (bo.order_no LIKE ? OR bo.product_name LIKE ?)'; params.push(`%${keyword}%`, `%${keyword}%`); }
  if (status) { where += ' AND bo.status=?'; params.push(status); }
  const total = get(`SELECT COUNT(*) as c FROM bulk_group_orders bo ${where}`, params).c;
  const list = all(`SELECT bo.*, u.nickname FROM bulk_group_orders bo LEFT JOIN users u ON bo.user_id=u.id ${where} ORDER BY bo.id DESC LIMIT ? OFFSET ?`,
    [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

module.exports = { presaleRouter, bulkGroupRouter, adminPresale };
