/**
 * 转化漏斗 + RFM 数据看板（P2）
 * ==============================
 * 漏斗: 访问(user_events.visit) → 加购(carts/unique user) → 下单(orders) → 支付(paid orders)
 * RFM : R最近消费 / F消费频次 / M消费金额，分层
 */
const express = require('express');
const router = express.Router();
const { get, all } = require('../utils/db');
const { success, fail } = 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);

// 日期范围 7d/30d/3m/1y → SQL 偏移
const RANGE_OFFSET = { '7d': '-7 day', '30d': '-30 day', '3m': '-90 day', '1y': '-365 day' };
function rangeOffset(r) { return RANGE_OFFSET[r] || RANGE_OFFSET['30d']; }

// 转化漏斗
router.get('/funnel', (req, res) => {
  const offset = rangeOffset(req.query.range);
  // 访问(visit 事件去重按 user 或 按 ip+时间粗去重)
  const visit = get(`SELECT COUNT(*) c FROM (SELECT user_id, ip, date(created_at) d FROM user_events WHERE action='visit' AND created_at>=datetime('now','localtime',?) GROUP BY user_id, ip, date(created_at))`, [offset]).c;
  const productView = get(`SELECT COUNT(DISTINCT user_id||ip||date(created_at)) c FROM user_events WHERE action='product_view' AND created_at>=datetime('now','localtime',?)`, [offset]).c;
  // 加购：有加购事件或被加购到购物车的去重用户
  const addCart = get(`SELECT COUNT(DISTINCT user_id) c FROM carts WHERE created_at>=datetime('now','localtime',?)`, [offset]).c;
  // 下单：非无效订单数
  const order = get(`SELECT COUNT(*) c FROM orders WHERE status NOT IN ('pending_pay','closed','cancelled') AND created_at>=datetime('now','localtime',?)`, [offset]).c;
  // 支付：已支付订单
  const pay = get(`SELECT COUNT(DISTINCT order_id) c FROM payment_records WHERE status='success' AND pay_time>=datetime('now','localtime',?)`, [offset]).c;
  // 环比(前一时段)
  const prevOrder = get(`SELECT COUNT(*) c FROM orders WHERE status NOT IN ('pending_pay','closed','cancelled') AND created_at>=datetime('now','localtime',?) AND created_at<datetime('now','localtime',?)`, [offset, offset.replace('-', '-').replace(/day$/, 'day') ]).c;

  const steps = [
    { key: 'visit', name: '访问', value: visit, rate: 100 },
    { key: 'product_view', name: '浏览商品', value: productView, rate: visit ? Math.round(productView / visit * 1000) / 10 : 0 },
    { key: 'add_cart', name: '加购', value: addCart, rate: visit ? Math.round(addCart / visit * 1000) / 10 : 0 },
    { key: 'order', name: '下单', value: order, rate: visit ? Math.round(order / visit * 1000) / 10 : 0 },
    { key: 'pay', name: '支付', value: pay, rate: visit ? Math.round(pay / visit * 1000) / 10 : 0 },
  ];
  // 逐级转化率(相对上一级)
  for (let i = 1; i < steps.length; i++) {
    const from = steps[i - 1].value, to = steps[i].value;
    steps[i].stepRate = from ? Math.round(to / from * 1000) / 10 : 0;
  }
  return res.json(success({ steps, prevOrders: prevOrder }));
});

// RFM 分析
router.get('/rfm', (req, res) => {
  const offset = rangeOffset(req.query.range);
  // 每位有购买行为用户: 最近消费日R / 订单数F / 总金额M
  const rows = all(`SELECT u.id, u.nickname, u.phone,
      MAX(o.created_at) last_order,
      COUNT(o.id) order_count,
      COALESCE(SUM(o.pay_amount),0) amount
    FROM users u
    JOIN orders o ON o.user_id = u.id
    WHERE o.status NOT IN ('pending_pay','closed','cancelled')
      AND o.created_at >= datetime('now','localtime',?)
    GROUP BY u.id`, [offset]);
  const metrics = rows.map(r => ({
    user_id: r.id, nickname: r.nickname, phone: r.phone,
    R: Math.max(0, Math.round((Date.now() - new Date(r.last_order).getTime()) / 86400000)),
    F: r.order_count, M: Math.round(r.amount)
  }));
  // 分位数分档 R/F/M → 1-5
  function quartile(vals, k) {
    const s = [...vals].sort((a, b) => a - b);
    if (!s.length) return 3;
    const idx = Math.min(s.length - 1, Math.floor(k * s.length / 5));
    return s[idx];
  }
  const Rs = metrics.map(m => m.R), Fs = metrics.map(m => m.F), Ms = metrics.map(m => m.M);
  const rQ = [quartile(Rs, 4), quartile(Rs, 3), quartile(Rs, 2), quartile(Rs, 1)]; // R越小越好
  const fQ = [quartile(Fs, 1), quartile(Fs, 2), quartile(Fs, 3), quartile(Fs, 4)];
  const mQ = [quartile(Ms, 1), quartile(Ms, 2), quartile(Ms, 3), quartile(Ms, 4)];
  const scored = metrics.map(m => {
    const rs = m.R <= rQ[0] ? 5 : m.R <= rQ[1] ? 4 : m.R <= rQ[2] ? 3 : m.R <= rQ[3] ? 2 : 1;
    const fs = m.F >= fQ[3] ? 5 : m.F >= fQ[2] ? 4 : m.F >= fQ[1] ? 3 : m.F >= fQ[0] ? 2 : 1;
    const ms = m.M >= mQ[3] ? 5 : m.M >= mQ[2] ? 4 : m.M >= mQ[1] ? 3 : m.M >= mQ[0] ? 2 : 1;
    // 客户分层：重要价值/重要发展/重要保持/重要挽留/一般
    let tier = '一般客户';
    if (rs >= 4 && fs >= 4 && ms >= 4) tier = '重要价值客户';
    else if (rs >= 4 && ms >= 3) tier = '重要发展客户';
    else if (rs <= 2 && ms >= 4) tier = '重要保持客户';
    else if (rs <= 2 && ms <= 2 && (fs >= 3)) tier = '重要挽留客户';
    return Object.assign({}, m, { rScore: rs, fScore: fs, mScore: ms, tier });
  });
  // 分层统计
  const tierCount = {};
  for (const x of scored) tierCount[x.tier] = (tierCount[x.tier] || 0) + 1;
  return res.json(success({ list: scored.slice(0, 200), tierCount, total: scored.length }));
});

module.exports = router;
