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

// ========== 功能门控：高级数据统计仅在完整版可用 ==========
router.use((req, res, next) => {
  if (!isFeatureEnabled('advanced_stats')) {
    return res.json(fail('当前版本不支持高级统计功能', 403));
  }
  next();
});

router.use(authAdmin);

// 📊 销售趋势（按日/周/月）
router.get('/sales-trend', (req, res) => {
  // 🔒 数值钳制 + 白名单，interval 参数绑定，防 SQL 注入
  const range = Math.max(1, Math.min(365, Math.floor(Number(req.query.range) || 7)));
  const unit = ['day','week','month'].includes(req.query.unit) ? req.query.unit : 'day';
  let fmt = "date(created_at)";
  let days = range;
  if (unit === 'week') { fmt = "strftime('%Y-W%W', created_at)"; days = range * 7; }
  if (unit === 'month') { fmt = "strftime('%Y-%m', created_at)"; days = range * 30; }

  const data = all(`SELECT ${fmt} as d, 
    COUNT(*) as order_count, 
    COALESCE(SUM(pay_amount),0) as sales_amount,
    COALESCE(AVG(pay_amount),0) as avg_amount
    FROM orders WHERE status NOT IN ('pending_pay','closed') 
    AND created_at >= date('now','localtime',?)
    GROUP BY d ORDER BY d ASC`, [`-${days} day`]);
  return res.json(success(data));
});

// 📊 热销商品 Top
router.get('/top-products', (req, res) => {
  const { limit = 10 } = req.query;
  const data = all(`SELECT oi.product_id, oi.product_name, oi.image,
    SUM(oi.quantity) as total_qty, SUM(oi.subtotal) as total_amount,
    COUNT(DISTINCT oi.order_id) as order_count
    FROM order_items oi JOIN orders o ON oi.order_id=o.id
    WHERE o.status NOT IN ('pending_pay','closed')
    GROUP BY oi.product_id ORDER BY total_qty DESC LIMIT ?`, [+limit]);
  return res.json(success(data));
});

// 📊 用户增长趋势
router.get('/user-growth', (req, res) => {
  // 🔒 days 数值钳制 + 参数绑定
  const days = Math.max(1, Math.min(365, Math.floor(Number(req.query.days) || 7)));
  const data = all(`SELECT date(created_at) as d, COUNT(*) as new_users 
    FROM users WHERE phone != 'admin' 
    AND created_at >= date('now','localtime',?)
    GROUP BY d ORDER BY d ASC`, [`-${days} day`]);
  return res.json(success(data));
});

// 📊 会员统计
router.get('/membership-stats', (req, res) => {
  const totalUsers = get("SELECT COUNT(*) as c FROM users WHERE phone != 'admin'").c;
  const vipUsers = get("SELECT COUNT(DISTINCT user_id) as c FROM user_memberships WHERE status='active'").c;
  const levelDist = all(`SELECT l.name, l.level, COUNT(u.id) as user_count 
    FROM user_levels l LEFT JOIN users u ON u.level_id=l.id AND u.phone!='admin'
    GROUP BY l.id ORDER BY l.level ASC`);
  const revenue = get("SELECT COALESCE(SUM(price),0) as s FROM membership_plans mp JOIN user_memberships um ON mp.id=um.plan_id").s;
  return res.json(success({ total_users: totalUsers, vip_users: vipUsers, vip_rate: totalUsers ? +(vipUsers/totalUsers*100).toFixed(1) : 0, level_distribution: levelDist, total_revenue: revenue }));
});

// 📊 订单状态分布
router.get('/order-status', (req, res) => {
  const data = all(`SELECT status, COUNT(*) as count, COALESCE(SUM(pay_amount),0) as amount 
    FROM orders GROUP BY status ORDER BY count DESC`);
  return res.json(success(data));
});

// 📊 今日/本周/本月概览
router.get('/overview', (req, res) => {
  const today = get("SELECT COUNT(*) as orders, COALESCE(SUM(pay_amount),0) as sales FROM orders WHERE date(created_at)=date('now','localtime') AND status NOT IN ('pending_pay','closed')");
  const week = get("SELECT COUNT(*) as orders, COALESCE(SUM(pay_amount),0) as sales FROM orders WHERE created_at>=date('now','localtime','-7 day') AND status NOT IN ('pending_pay','closed')");
  const month = get("SELECT COUNT(*) as orders, COALESCE(SUM(pay_amount),0) as sales FROM orders WHERE strftime('%Y-%m',created_at)=strftime('%Y-%m','now','localtime') AND status NOT IN ('pending_pay','closed')");
  return res.json(success({ today, week, month }));
});

// 📊 库存预警
router.get('/low-stock', (req, res) => {
  const { threshold = 10 } = req.query;
  const products = all(`SELECT id, name, image, stock, sales, price FROM products 
    WHERE status=1 AND stock <= ? ORDER BY stock ASC LIMIT 50`, [+threshold]);
  const skus = all(`SELECT ps.id, ps.product_id, p.name, ps.sku_code, ps.image, ps.stock, ps.price 
    FROM product_skus ps JOIN products p ON ps.product_id=p.id 
    WHERE ps.status=1 AND ps.stock <= ? ORDER BY ps.stock ASC LIMIT 50`, [+threshold]);
  return res.json(success({ products, skus, threshold: +threshold }));
});

// 🔒 CSV 输出清洗：防公式注入(=+-@起始字段加前导单引号) + 转义双引号
function csvEsc(v) {
  v = String(v == null ? '-' : v);
  v = v.replace(/"/g, '""');
  if (/^[=+\-@\t\r]/.test(v)) v = "'" + v;
  return v;
}

// 📤 导出订单 CSV
router.get('/export/orders', (req, res) => {
  const { status, start_date, end_date } = req.query;
  let where = "WHERE o.status NOT IN ('pending_pay','closed')";
  const params = [];
  if (status) { where += ' AND o.status=?'; params.push(status); }
  if (start_date) { where += ' AND date(o.created_at)>=?'; params.push(start_date); }
  if (end_date) { where += ' AND date(o.created_at)<=?'; params.push(end_date); }

  const orders = all(`SELECT o.order_no,o.created_at,o.status,o.pay_amount,o.total_amount,
    o.discount_amount,o.payment_method,o.consignee,o.phone,o.province||o.city||o.district||o.address as full_address,
    o.remark,u.nickname,u.phone as user_phone
    FROM orders o LEFT JOIN users u ON o.user_id=u.id ${where} ORDER BY o.id DESC`, params);

  const header = '订单号,下单时间,状态,支付金额,商品总额,优惠金额,支付方式,收货人,联系电话,收货地址,备注,用户昵称,用户手机\n';
  const statusMap = { pending_pay:'待付款',pending_ship:'待发货',shipped:'已发货',received:'已收货',completed:'已完成',closed:'已关闭',refunding:'退款中',refunded:'已退款' };
  const rows = orders.map(o => 
    `"${csvEsc(o.order_no)}","${csvEsc(o.created_at)}","${csvEsc(statusMap[o.status]||o.status)}","${csvEsc(o.pay_amount)}","${csvEsc(o.total_amount)}","${csvEsc(o.discount_amount)}","${csvEsc(o.payment_method||'-')}","${csvEsc(o.consignee||'-')}","${csvEsc(o.phone||'-')}","${csvEsc(o.full_address||'-')}","${csvEsc(o.remark||'-')}","${csvEsc(o.nickname||'-')}","${csvEsc(o.user_phone||'-')}"`
  ).join('\n');

  res.setHeader('Content-Type', 'text/csv; charset=utf-8');
  res.setHeader('Content-Disposition', 'attachment; filename=orders.csv');
  res.send('\uFEFF' + header + rows);
});

// 📤 导出用户 CSV
router.get('/export/users', (req, res) => {
  const { start_date, end_date } = req.query;
  let where = "WHERE phone != 'admin'";
  const params = [];
  if (start_date) { where += ' AND date(created_at)>=?'; params.push(start_date); }
  if (end_date) { where += ' AND date(created_at)<=?'; params.push(end_date); }

  const users = all(`SELECT u.id,u.nickname,u.phone,u.balance,u.total_consumed,u.order_count,
    u.experience,u.team_count,u.created_at,l.name as level_name
    FROM users u LEFT JOIN user_levels l ON u.level_id=l.id ${where} ORDER BY u.id DESC`, params);

  const header = '用户ID,昵称,手机号,余额,累计消费,订单数,经验值,团队人数,等级,注册时间\n';
  const rows = users.map(u => 
    `"${csvEsc(u.id)}","${csvEsc(u.nickname)}","${csvEsc(u.phone)}","${csvEsc(u.balance)}","${csvEsc(u.total_consumed)}","${csvEsc(u.order_count)}","${csvEsc(u.experience)}","${csvEsc(u.team_count)}","${csvEsc(u.level_name)}","${csvEsc(u.created_at)}"`
  ).join('\n');

  res.setHeader('Content-Type', 'text/csv; charset=utf-8');
  res.setHeader('Content-Disposition', 'attachment; filename=users.csv');
  res.send('\uFEFF' + header + rows);
});

// 📤 导出商品 CSV
router.get('/export/products', (req, res) => {
  const products = all(`SELECT p.id,p.name,p.price,p.original_price,p.cost_price,p.stock,p.sales,
    p.unit,p.status,p.created_at,c.name as category_name
    FROM products p LEFT JOIN categories c ON p.category_id=c.id ORDER BY p.id DESC`);

  const header = '商品ID,商品名,售价,原价,成本价,库存,销量,单位,状态,分类,创建时间\n';
  const rows = products.map(p => 
    `"${csvEsc(p.id)}","${csvEsc(p.name)}","${csvEsc(p.price)}","${csvEsc(p.original_price)}","${csvEsc(p.cost_price)}","${csvEsc(p.stock)}","${csvEsc(p.sales)}","${csvEsc(p.unit||'件')}","${csvEsc(p.status?'上架':'下架')}","${csvEsc(p.category_name||'-')}","${csvEsc(p.created_at)}"`
  ).join('\n');

  res.setHeader('Content-Type', 'text/csv; charset=utf-8');
  res.setHeader('Content-Disposition', 'attachment; filename=products.csv');
  res.send('\uFEFF' + header + rows);
});

// 🔔 操作日志查询
router.get('/operation-logs', (req, res) => {
  const { page: p = 1, pageSize = 30, module, action } = 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 (module) { where += ' AND module=?'; params.push(module); }
  if (action) { where += ' AND action LIKE ?'; params.push(`%${action}%`); }
  const total = get(`SELECT COUNT(*) as c FROM operation_logs ${where}`, params).c;
  const list = all(`SELECT * FROM operation_logs ${where} ORDER BY id DESC LIMIT ? OFFSET ?`,
    [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

// 📋 最近活动（用于首页）
router.get('/recent-activity', (req, res) => {
  const recentOrders = all("SELECT order_no,pay_amount,created_at FROM orders WHERE status NOT IN ('pending_pay') ORDER BY id DESC LIMIT 10");
  const newUsers = all("SELECT id,nickname,phone,created_at FROM users WHERE phone != 'admin' ORDER BY id DESC LIMIT 10");
  return res.json(success({ recent_orders: recentOrders, new_users: newUsers }));
});

// 🔔 系统通知 - 发送给用户
router.post('/send-notification', authAdmin, (req, res) => {
  const { user_id, type, title, content } = req.body;
  if (!title) return res.json(fail('标题不能为空'));
  
  if (user_id && user_id !== 'all') {
    run('INSERT INTO notifications(user_id,type,title,content) VALUES(?,?,?,?)', [user_id, type||'system', title, content||'']);
    return res.json(success(null, '发送成功'));
  }
  // 发送给所有用户
  run('INSERT INTO notifications(user_id,type,title,content) VALUES(0,?,?,?)', [type||'system', title, content||'']);
  return res.json(success(null, '已发送给全站用户'));
});

// 🔔 通知列表（管理端）
router.get('/notifications', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 20 } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(100, Math.max(1, +pageSize));
  const total = get('SELECT COUNT(*) as c FROM notifications', []).c;
  const list = all('SELECT * FROM notifications ORDER BY id DESC LIMIT ? OFFSET ?', [size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

// 🏷️ 批量操作 - 批量上下架
router.post('/batch/product-status', authAdmin, (req, res) => {
  const { ids, status } = req.body;
  if (!ids || !ids.length) return res.json(fail('请选择商品'));
  const stmt = get('?').constructor; // placeholder
  const placeholders = ids.map(() => '?').join(',');
  run(`UPDATE products SET status=?,updated_at=datetime('now','localtime') WHERE id IN (${placeholders})`, [status, ...ids]);
  return res.json(success(null, `已${status?'上架':'下架'}${ids.length}个商品`));
});

// 🏷️ 批量发货
router.post('/batch/ship', authAdmin, (req, res) => {
  const { order_ids, shipping_company, shipping_no } = req.body;
  if (!order_ids || !order_ids.length) return res.json(fail('请选择订单'));
  for (const oid of order_ids) {
    run(`UPDATE orders SET status='shipped',shipping_company=?,shipping_no=?,shipping_time=datetime('now','localtime') WHERE id=? AND status='pending_ship'`,
      [shipping_company||'', shipping_no||'', oid]);
    run('INSERT INTO order_logs(order_id,action,content) VALUES(?,?,?)', [oid, 'ship', `批量发货:${shipping_company||''}`]);
  }
  return res.json(success(null, `已批量发货${order_ids.length}单`));
});

module.exports = router;
