const express = require('express');

// [LiteMall_Copyright] fba28f00dae77aa2 LiteMall_Lobster_v1.0_2026


const router = express.Router();
const { get, run, all, transaction, getDb } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { $, mul, add, sub, discountAmt, afterDiscount, afterCoupon, toNum } = require('../utils/money');
const { authUser } = require('../middleware/auth');
const notification = require('../lib/notification');
    // NOTE: genOrderNo 前缀+日期+随机数，单日碰撞概率极低
function genOrderNo() {
  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 `DD${date}${rand}`;
}
function genRefundNo() {
  return `TK${Date.now()}${Math.floor(Math.random()*1000)}`;
}
// 预计算金额
router.post('/calc-amount', authUser, (req, res) => {
  try {
    const { items } = req.body; // [{product_id, sku_id, quantity}]
    let total = 0;
    const detail = [];
    for (const item of items) {
      let price = 0, name = '', image = '';
      if (item.sku_id) {
        const sku = get('SELECT ps.*,p.name,p.image FROM product_skus ps JOIN products p ON ps.product_id=p.id WHERE ps.id=?', [item.sku_id]);
        if (!sku) continue;
        price = sku.price;
        name = sku.name || sku.product_name;
        image = sku.image || sku.product_image;
      } else {
        const p = get('SELECT * FROM products WHERE id=?', [item.product_id]);
        if (!p) continue;
        price = p.price;
        name = p.name;
        image = p.image;
      }
      const subtotal = mul(price, item.quantity);
      total = add(total, subtotal);
      detail.push({ product_id: item.product_id, sku_id: item.sku_id, name, image, price, quantity: item.quantity, subtotal });
    }
    // 等级折扣（带兜底保护）
    const user = get('SELECT u.level_id, l.discount FROM users u JOIN user_levels l ON u.level_id=l.id WHERE u.id=?', [req.userId]);
    let discount = 1.00;
    try {
      if (user && user.discount) {
        // 兜底：折扣必须在 0.1~1.0 之间
        discount = Math.max(0.1, Math.min(1.0, parseFloat(user.discount)));
      }
    } catch (e) {
      console.error('[折扣] 等级折扣计算异常，使用原价兜底:', e.message);
      discount = 1.00;
    }
    const discountAmount = discountAmt(total, discount);
    const payAmount = afterDiscount(total, discount);
    return res.json(success({ items: detail, total_amount: total, discount_amount: discountAmount, pay_amount: payAmount, level_discount: discount }));
  } catch (e) {
    return res.json(fail('计算失败'));
  }
});
// 免费版订单数量限制
const { checkOrderLimit } = require('../lib/limits');
// 创建订单
router.post('/create', authUser, (req, res) => {
  // 记录并发数据
  const { trackOrder } = require('../lib/concurrency');
  trackOrder();
  
  // 防重复提交：检查30秒内是否有相同用户的未支付订单
  const recentOrder = get("SELECT id FROM orders WHERE user_id=? AND created_at > datetime('now','-30 seconds') AND status='pending_pay'",
    [req.userId]);
  if (recentOrder) {
    return res.json(fail('操作太频繁，请30秒后再试'));
  }
  try {
    // 免费版订单数量检查
    const limitCheck = checkOrderLimit();
    if (!limitCheck.ok) {
      return res.json(fail(limitCheck.message, 403));
    }
    
    const { items, address_id, remark, use_coupon_ids } = req.body;
    if (!items || !items.length) return res.json(fail('请选择商品'));
    const result = transaction(() => {
      const orderNo = genOrderNo();
      let totalAmount = 0;
      const orderItems = [];
      for (const item of items) {
        let price = 0, skuInfo = '', image = '', productName = '', stock = 0;
        const product = get('SELECT * FROM products WHERE id=? AND status=1', [item.product_id]);
        if (!product) throw new Error(`商品不存在: ${item.product_id}`);
        if (item.sku_id) {
          const sku = get('SELECT * FROM product_skus WHERE id=? AND product_id=?', [item.sku_id, item.product_id]);
          if (!sku) throw new Error(`规格不存在: ${product.name}`);
          price = sku.price;
          stock = sku.stock;
          skuInfo = JSON.stringify(sku.specs || []);
          image = sku.image || product.image;
          // 原子扣减：CAS（Compare-And-Swap）防止并发超卖
          const r1 = run('UPDATE product_skus SET stock=stock-?,sales=sales+? WHERE id=? AND stock>=?', [item.quantity, item.quantity, sku.id, item.quantity]);
          if (r1.changes === 0) throw new Error(`库存不足: ${product.name}`);
        } else {
          price = product.price;
          stock = product.stock;
          image = product.image;
          // 原子扣减：CAS（Compare-And-Swap）防止并发超卖
          const r2 = run('UPDATE products SET stock=stock-? WHERE id=? AND stock>=?', [item.quantity, product.id, item.quantity]);
          if (r2.changes === 0) throw new Error(`库存不足: ${product.name}`);
        }
        
        productName = product.name;
        const subtotal = mul(price, item.quantity);
        totalAmount = add(totalAmount, subtotal);
        orderItems.push({ product_id: product.id, sku_id: item.sku_id || null, product_name: productName, sku_info: skuInfo, image, price, quantity: item.quantity, subtotal });
        run('UPDATE products SET sales=sales+? WHERE id=?', [item.quantity, product.id]);
      }
      // 等级折扣（带兜底保护）
      const user = get('SELECT u.level_id, l.discount FROM users u JOIN user_levels l ON u.level_id=l.id WHERE u.id=?', [req.userId]);
      let discount = 1.00;
      try {
        if (user && user.discount) {
          discount = Math.max(0.1, Math.min(1.0, parseFloat(user.discount)));
        }
      } catch (e) {
        console.error('[折扣] 订单创建折扣异常，使用原价兜底:', e.message);
        discount = 1.00;
      }
      const discAmtNum = discountAmt(totalAmount, discount);
      let payAmount = afterDiscount(totalAmount, discount);
      
      // ========== 优惠券抵扣 ==========
      let couponAmount = 0;
      let usedCouponIds = '';
      if (use_coupon_ids && Array.isArray(use_coupon_ids) && use_coupon_ids.length > 0) {
        const placeholders = use_coupon_ids.map(() => '?').join(',');
        const userCoupons = all(
          `SELECT uc.id as uc_id, uc.coupon_id, c.type, c.value, c.min_amount, c.max_amount
           FROM user_coupons uc JOIN coupons c ON uc.coupon_id=c.id
           WHERE uc.id IN (${placeholders}) AND uc.user_id=? AND uc.status='unused' AND (uc.expired_time IS NULL OR uc.expired_time > datetime('now','localtime'))`,
          [...use_coupon_ids, req.userId]
        );
        for (const uc of userCoupons) {
          if (payAmount < uc.min_amount) continue;
          let disc = 0;
          if (uc.type === 'cash' || uc.type === 'full_reduce') {
            disc = uc.value;
          } else if (uc.type === 'discount') {
            disc = discountAmt(payAmount, $(uc.value).div(100).toNumber());
            if (uc.max_amount > 0 && disc > uc.max_amount) disc = uc.max_amount;
          }
          couponAmount = add(couponAmount, disc);
          usedCouponIds += (usedCouponIds ? ',' : '') + uc.uc_id;
          run("UPDATE user_coupons SET status='used', used_time=datetime('now','localtime') WHERE id=?", [uc.uc_id]);
        }
        payAmount = sub(payAmount, couponAmount);
        if (payAmount < 0) payAmount = 0;
      }
      // 满减活动计算
      let promoBenefit = 0, promoId = null, promoRuleIdx = -1, promoDesc = '';
      try {
        const { calcBestPromotion } = require('../lib/promotion-engine');
        const productIds = orderItems.map(i => i.product_id);
        const cats = all('SELECT DISTINCT category_id FROM products WHERE id IN (' + productIds.map(()=>'?').join(',') + ')', productIds);
        const catIds = cats.map(c => c.category_id).filter(Boolean);
        const result = calcBestPromotion(payAmount, orderItems.reduce((s,i)=>add(s,i.quantity),0), productIds, catIds);
        if (result.best && result.benefitAmount > 0) {
          promoBenefit = result.benefitAmount;
          promoId = result.best.promotionId;
          promoRuleIdx = result.best.ruleIndex;
          promoDesc = result.best.benefitDesc;
          payAmount = sub(payAmount, promoBenefit);
          if (payAmount < 0) payAmount = 0;
        }
      } catch(e) {}
      // 地址
      let consignee = '', phone = '', province = '', city = '', district = '', address = '';
      if (address_id) {
        const addr = get('SELECT * FROM user_addresses WHERE id=? AND user_id=?', [address_id, req.userId]);
        if (addr) { consignee = addr.name; phone = addr.phone; province = addr.province; city = addr.city; district = addr.district; address = addr.detail; }
      }
      // ========== 积分抵现 ==========
      // 独立积分抵扣（100积分=1元，默认可配），条件更新防超扣，不污染经验值
      let usedPoints = 0, pointsAmount = 0;
      const pts = (() => {
        try { return require('../lib/points'); } catch (e) { return null; }
      })();
      const usePoints = parseInt(req.body.use_points || 0) || 0;
      if (pts && pts.pointsDeductEnabled() && usePoints > 0 && payAmount > 0) {
        const ratio = pts.pointsDeductRatio();
        const limit = pts.pointsDeductLimit();
        const bal = pts.getBalance(req.userId);
        const canUse = Math.min(usePoints, bal.points, limit > 0 ? limit : bal.points);
        if (canUse > 0) {
          const maxByAmount = Math.floor(payAmount * ratio); // 最多抵到应付金额
          const actualUse = Math.min(canUse, maxByAmount);
          if (actualUse > 0) {
            const d = pts.deductPoints(req.userId, actualUse, 'deduct', orderNo, '下单积分抵现');
            if (d.ok) {
              usedPoints = actualUse;
              pointsAmount = sub(payAmount, actualUse / ratio);
              pointsAmount = +(payAmount - actualUse / ratio).toFixed(2);
              payAmount = Math.max(0, +(payAmount - actualUse / ratio).toFixed(2));
            }
          }
        }
      }
      run(`INSERT INTO orders(order_no,user_id,total_amount,discount_amount,pay_amount,consignee,phone,province,city,district,address,remark,use_coupon_ids)
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`,
        [orderNo, req.userId, totalAmount, add(discAmtNum, couponAmount), payAmount, consignee, phone, province, city, district, address, remark || '', usedCouponIds]);
      const order = get('SELECT id FROM orders WHERE order_no=?', [orderNo]);
      const stmt = getDb().prepare('INSERT INTO order_items(order_id,product_id,sku_id,product_name,sku_info,image,price,quantity,subtotal) VALUES(?,?,?,?,?,?,?,?,?)');
      for (const oi of orderItems) stmt.run(order.id, oi.product_id, oi.sku_id, oi.product_name, oi.sku_info, oi.image, oi.price, oi.quantity, oi.subtotal);
      run('INSERT INTO order_logs(order_id,action,content) VALUES(?,?,?)', [order.id, 'create', '订单创建成功']);
      // 记录满减活动
      if (promoId && promoBenefit > 0) {
        run('INSERT INTO promotion_logs(promotion_id,order_id,user_id,rule_index,cond_desc,benefit_desc,benefit_amount) VALUES(?,?,?,?,?,?,?)',
          [promoId, order.id, req.userId, promoRuleIdx, '活动自动匹配', promoDesc, promoBenefit]);
        run('UPDATE promotions SET order_count=order_count+1,discount_total=discount_total+?,participant_count=participant_count+1 WHERE id=?', [promoBenefit, promoId]);
      }
      // 清除已选购物车
      const cartIds = items.filter(i => i.cart_id).map(i => i.cart_id);
      if (cartIds.length) {
        const placeholders = cartIds.map(() => '?').join(',');
        run(`DELETE FROM carts WHERE id IN (${placeholders}) AND user_id=?`, [...cartIds, req.userId]);
      }
      return { orderNo, payAmount, discountAmount: discAmtNum, promoBenefit, promoDesc, usedPoints: usedPoints, pointsAmount: pointsAmount };
    });
    // 异步通知 - 不阻塞主流程
    notification.send('order_created', req.userId, {
      order_no: result.orderNo,
      amount: result.payAmount.toFixed(2)
    }).catch(err => console.error('[通知] 下单通知失败:', err.message));
    return res.json(success(result, '下单成功'));
  } catch (e) {
    console.error('创建订单失败:', e);
    return res.json(fail(e.message || '下单失败'));
  }
});
// 订单列表
router.get('/list', authUser, (req, res) => {
  const { page: p = 1, pageSize = 10, status } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(50, Math.max(1, +pageSize));
  let where = 'WHERE user_id=?';
  const params = [req.userId];
  if (status) { where += ' AND status=?'; params.push(status); }
  const total = get(`SELECT COUNT(*) as c FROM orders ${where}`, params).c;
  const list = all(`SELECT * FROM orders ${where} ORDER BY id DESC LIMIT ? OFFSET ?`, [...params, size, (pageNum - 1) * size]);
  // 批量查询子项（优化 N+1）
  if (list.length > 0) {
    const ids = list.map(o => o.id);
    const placeholders = ids.map(() => '?').join(',');
    const allItems = all(`SELECT * FROM order_items WHERE order_id IN (${placeholders})`, ids);
    const itemsByOrder = {};
    for (const item of allItems) {
      if (!itemsByOrder[item.order_id]) itemsByOrder[item.order_id] = [];
      itemsByOrder[item.order_id].push(item);
    }
    for (const order of list) {
      order.items = itemsByOrder[order.id] || [];
    }
  }
  return res.json(page(list, total, pageNum, size));
});
// 订单详情
router.get('/detail/:orderNo', authUser, (req, res) => {
  const order = get('SELECT * FROM orders WHERE order_no=? AND user_id=?', [req.params.orderNo, req.userId]);
  if (!order) return res.json(fail('订单不存在'));
  order.items = all('SELECT * FROM order_items WHERE order_id=?', [order.id]);
  order.logs = all('SELECT * FROM order_logs WHERE order_id=? ORDER BY id ASC', [order.id]);
  return res.json(success(order));
});
// 取消订单
router.post('/:orderNo/cancel', authUser, (req, res) => {
  const { close_reason } = req.body;
  const order = get('SELECT * FROM orders WHERE order_no=? AND user_id=?', [req.params.orderNo, req.userId]);
  if (!order) return res.json(fail('订单不存在'));
  if (order.status !== 'pending_pay') return res.json(fail('当前状态不可取消'));
  transaction(() => {
    run('UPDATE orders SET status=?,close_reason=?,close_time=datetime(\'now\',\'localtime\') WHERE id=?', ['closed', close_reason || '用户取消', order.id]);
    run('INSERT INTO order_logs(order_id,action,content) VALUES(?,?,?)', [order.id, 'cancel', '订单已取消']);
    // 归还库存
    const items = all('SELECT * FROM order_items WHERE order_id=?', [order.id]);
    for (const item of items) {
      if (item.sku_id) {
        run('UPDATE product_skus SET stock=stock+?,sales=sales-? WHERE id=?', [item.quantity, item.quantity, item.sku_id]);
      } else {
        run('UPDATE products SET stock=stock+?,sales=sales-? WHERE id=?', [item.quantity, item.quantity, item.product_id]);
      }
    }
    // 归还优惠券
    if (order.use_coupon_ids) {
      const ucIds = String(order.use_coupon_ids).split(',').filter(Boolean);
      for (const ucId of ucIds) {
        run("UPDATE user_coupons SET status='unused', used_time=NULL WHERE id=? AND user_id=?", [+ucId, req.userId]);
      }
    }
  });
  return res.json(success(null, '取消成功'));
});
// 确认收货
router.post('/:orderNo/confirm', authUser, (req, res) => {
  const order = get('SELECT * FROM orders WHERE order_no=? AND user_id=?', [req.params.orderNo, req.userId]);
  if (!order) return res.json(fail('订单不存在'));
  if (order.status !== 'shipped') return res.json(fail('当前状态不可确认收货'));
  run('UPDATE orders SET status=?,confirm_time=datetime(\'now\',\'localtime\') WHERE id=?', ['received', order.id]);
  run('INSERT INTO order_logs(order_id,action,content) VALUES(?,?,?)', [order.id, 'confirm', '用户确认收货']);
  // 更新用户消费统计
  run('UPDATE users SET total_consumed=total_consumed+?,order_count=order_count+1 WHERE id=?', [order.pay_amount, req.userId]);
  return res.json(success(null, '确认收货成功'));
});
// [安全] 订单直付守卫：该路由是模拟直付（直接置为已支付），生产必须禁用，改为走真实支付平台
const ORDER_DIRECT_PAY = process.env.ALLOW_DIRECT_PAY === '1';

// 支付（模拟）
router.post('/:orderNo/pay', authUser, (req, res) => {
  // 🔒 资金安全：生产环境禁止模拟直付（防免费白嫖下单）
  if (!ORDER_DIRECT_PAY) return res.status(403).json(fail('模拟直付已禁用，请走真实支付', 403));
  const { payment_method } = req.body;
  const order = get('SELECT * FROM orders WHERE order_no=? AND user_id=?', [req.params.orderNo, req.userId]);
  if (!order) return res.json(fail('订单不存在'));
  if (order.status !== 'pending_pay') return res.json(fail('当前状态不可支付'));
  transaction(() => {
    run('UPDATE orders SET status=?,payment_method=?,paid_amount=?,updated_at=datetime(\'now\',\'localtime\') WHERE id=?',
      ['pending_ship', payment_method || 'wechat', order.pay_amount, order.id]);
    run('INSERT INTO payment_records(trade_no,order_id,user_id,amount,method,status,pay_time) VALUES(?,?,?,?,?,?,datetime(\'now\',\'localtime\'))',
      [`PAY${Date.now()}`, order.id, req.userId, order.pay_amount, payment_method || 'wechat', 'success']);
    run('INSERT INTO order_logs(order_id,action,content) VALUES(?,?,?)', [order.id, 'pay', `支付成功(${order.pay_amount}元)`]);
  });
  // 异步通知 - 支付成功
  notification.send('payment_success', req.userId, {
    order_no: order.order_no,
    amount: order.pay_amount.toFixed(2)
  }).catch(err => console.error('[通知] 支付通知失败:', err.message));
  // 营销自动化 - 首单礼
  try { require('../lib/marketing-automation').onOrderPaid(req.userId); } catch (e) { console.error('[营销自动化-首单]', e.message); }
  return res.json(success(null, '支付成功'));
});
// 申请退款
router.post('/refund', authUser, (req, res) => {
  try {
    const { order_id, order_item_id, type, reason, amount } = req.body;
    const order = get('SELECT * FROM orders WHERE id=? AND user_id=?', [order_id, req.userId]);
    if (!order) return res.json(fail('订单不存在'));
    // 🔒 退款金额不能超过支付金额
    const reqAmount = amount !== undefined && amount !== null && amount !== '' ? toNum(amount) : toNum(order.pay_amount);
    if (!(reqAmount > 0) || reqAmount > toNum(order.pay_amount)) {
      return res.json(fail('退款金额无效或超出支付金额'));
    }
    // 🔒 幂等：同一订单存在未处理的退款申请则拒绝重复申请
    const exist = get("SELECT id FROM refunds WHERE order_id=? AND status IN ('pending') ", [order_id]);
    if (exist) return res.json(fail('已有待处理的退款申请'));
    const r = run('INSERT INTO refunds(refund_no,order_id,order_item_id,user_id,type,reason,amount,status) VALUES(?,?,?,?,?,?,?,?)',
      [genRefundNo(), order_id, order_item_id || null, req.userId, type || 'only_refund', reason || '', reqAmount, 'pending']);
    
    run('UPDATE orders SET status=? WHERE id=?', ['refunding', order_id]);
    run('INSERT INTO order_logs(order_id,action,content) VALUES(?,?,?)', [order_id, 'refund_apply', '用户申请退款']);
    
    return res.json(success({ id: r.lastInsertRowid }, '申请成功'));
  } catch (e) {
    return res.json(fail('申请失败'));
  }
});
// 退款列表
router.get('/refund/list', authUser, (req, res) => {
  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 refunds WHERE user_id=?', [req.userId]).c;
  const list = all('SELECT * FROM refunds WHERE user_id=? ORDER BY id DESC LIMIT ? OFFSET ?', [req.userId, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});
// 取消退款
router.post('/refund/:id/cancel', authUser, (req, res) => {
  const refund = get('SELECT * FROM refunds WHERE id=? AND user_id=?', [req.params.id, req.userId]);
  if (!refund) return res.json(fail('退款申请不存在'));
  run('UPDATE refunds SET status=? WHERE id=?', ['cancelled', refund.id]);
  run('UPDATE orders SET status=? WHERE id=?', ['pending_ship', refund.order_id]);
  return res.json(success(null, '已取消退款'));
});
// 订单日志
router.post('/:orderNo/log', authUser, (req, res) => {
  const order = get('SELECT id FROM orders WHERE order_no=? AND user_id=?', [req.params.orderNo, req.userId]);
  if (!order) return res.json(fail('订单不存在'));
  run('INSERT INTO order_logs(order_id,action,content,operator) VALUES(?,?,?,?)', [order.id, 'user_action', req.body.content || '', 'user']);
  return res.json(success(null, '记录成功'));
});
// 快递公司列表
const SHIPPING_COMPANIES = [
  { code: 'SF', name: '顺丰快递' }, { code: 'EMS', name: 'EMS' }, { code: 'STO', name: '申通快递' },
  { code: 'YTO', name: '圆通速递' }, { code: 'ZTO', name: '中通快递' }, { code: 'YUNDA', name: '韵达快递' },
  { code: 'JT', name: '极兔速递' }, { code: 'BSHT', name: '百世快递' }, { code: 'TTKD', name: '天天快递' },
  { code: 'UC', name: '优速快递' }, { code: 'DBL', name: '德邦快递' }, { code: 'ZJS', name: '宅急送' },
];
router.get('/shipping-companies', (req, res) => {
  return res.json(success(SHIPPING_COMPANIES));
});
module.exports = router;