const express = require('express');

// [LiteMall_Copyright] fba28f00dae77aa2 LiteMall_Lobster_v1.0_2026


const router = express.Router();
const { get, run, all, transaction } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authUser } = require('../middleware/auth');
const { isFeatureEnabled } = require('../lib/license');
const { checkCommissionCap, checkTeamLimit, MAX_DISTRIBUTION_COMMISSION, MAX_TEAM_SIZE } = require('../lib/limits');
// ========== 功能门控：免费版开放二级分销但限制佣金上限 ==========
// 完整版无限分销
router.use((req, res, next) => {
  if (!isFeatureEnabled('distribution')) {
    // 免费版：记录已开放且带有水印限制
    return next(); // 放行，具体限制在接口级别
  }
  next();
});
router.use(authUser);
// 分销概况
router.get('/info', (req, res) => {
  const user = get('SELECT id,parent_id,team_count FROM users WHERE id=?', [req.userId]);
  const totalCommission = get('SELECT COALESCE(SUM(commission),0) as c FROM distribution_records WHERE user_id=?', [req.userId]).c;
  const settled = get('SELECT COALESCE(SUM(commission),0) as c FROM distribution_records WHERE user_id=? AND status=\'settled\'', [req.userId]).c;
  const pending = get('SELECT COALESCE(SUM(commission),0) as c FROM distribution_records WHERE user_id=? AND status=\'pending\'', [req.userId]).c;
  const withdrawable = settled - get('SELECT COALESCE(SUM(amount),0) as c FROM withdraw_requests WHERE user_id=? AND status IN (\'pending\',\'approved\')', [req.userId]).c;
  
  const distConfig = all('SELECT key,value FROM distribution_config');
  const configMap = {};
  distConfig.forEach(c => configMap[c.key] = c.value);
  // 免费版标记佣金上限
  const isFree = require('../lib/limits').isFree();
  const limitInfo = isFree ? {
    commission_cap: MAX_DISTRIBUTION_COMMISSION,
    team_cap: MAX_TEAM_SIZE
  } : null;
  return res.json(success({ team_count: user.team_count, total_commission: totalCommission, settled, pending, withdrawable, config: configMap, limit: limitInfo }));
});
// 团队列表
router.get('/team', (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 users WHERE parent_id=?', [req.userId]).c;
  const list = all('SELECT id,nickname,avatar,phone,level_id,order_count,total_consumed,created_at FROM users WHERE parent_id=? ORDER BY id DESC LIMIT ? OFFSET ?',
    [req.userId, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});
// 佣金记录
router.get('/commission', (req, res) => {
  const { page: p = 1, pageSize = 20, status } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(100, 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 distribution_records ${where}`, params).c;
  const list = all(`SELECT dr.*, o.order_no FROM distribution_records dr LEFT JOIN orders o ON dr.order_id=o.id ${where} ORDER BY dr.id DESC LIMIT ? OFFSET ?`,
    [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});
// 佣金统计
router.get('/commission/stat', (req, res) => {
  const stats = {
    today: get('SELECT COALESCE(SUM(commission),0) as c FROM distribution_records WHERE user_id=? AND date(created_at)=date(\'now\',\'localtime\')', [req.userId]).c,
    month: get("SELECT COALESCE(SUM(commission),0) as c FROM distribution_records WHERE user_id=? AND strftime('%Y-%m',created_at)=strftime('%Y-%m','now','localtime')", [req.userId]).c,
    total: get('SELECT COALESCE(SUM(commission),0) as c FROM distribution_records WHERE user_id=? AND status=\'settled\'', [req.userId]).c,
  };
  return res.json(success(stats));
});
// 分销等级
router.get('/level', (req, res) => {
  const levels = all('SELECT * FROM distribution_levels WHERE status=1 ORDER BY level ASC');
  return res.json(success(levels));
});
// 分销状态（前端判断是否已开通/可否申请）
router.get('/status', (req, res) => {
  const user = get('SELECT distributor_status, distributor_level, level_id, total_consumed FROM users WHERE id=?', [req.userId]);
  const cfg = {};
  all('SELECT key,value FROM distribution_config').forEach(c => cfg[c.key] = c.value);
  return res.json(success({
    status: user.distributor_status || 'none',
    level: user.distributor_level || 0,
    member_level: user.level_id || 0,
    dist_mode: cfg.dist_mode || 'everyone',
    agent_apply_enabled: cfg.agent_apply_enabled === '1',
    paid_member: (user.level_id || 0) >= 2
  }));
});
// 申请开通分销（支持三种模式：everyone大人人分销直接开通 / threshold满额直接开通 / designated指定需审批）
router.post('/apply', (req, res) => {
  try {
    const { real_name, phone, wechat, reason } = req.body;
    const user = get('SELECT distributor_status, distributor_level, level_id, total_consumed FROM users WHERE id=?', [req.userId]);
    if (!user) return res.json(fail('用户不存在'));
    if (user.distributor_status === 'active') return res.json(fail('您已开通分销，无需重复申请'));
    const cfg = {};
    all('SELECT key,value FROM distribution_config').forEach(c => cfg[c.key] = c.value);
    const mode = cfg.dist_mode || 'everyone';
    // 🩹联动：同一逻辑——付费会员(level>=2)可直接开通分销；普通用户按分销模式判断
    const paidMember = (user.level_id || 0) >= 2;
    const levelMap = { 2: 1, 3: 2, 4: 3 };
    const mappedLevel = levelMap[user.level_id] || 1;
    if (mode === 'everyone' || paidMember || (mode === 'threshold' && (user.total_consumed || 0) >= (+(cfg.apply_threshold || 0)))) {
      // 直接开通
      const finalLevel = Math.max(user.distributor_level || 1, mappedLevel);
      run("UPDATE users SET distributor_status='active', distributor_level=? WHERE id=?", [finalLevel, req.userId]);
      return res.json(success({ status: 'active', level: finalLevel }, '开通成功，您已成为分销商'));
    }
    if (mode === 'designated') {
      const exist = get("SELECT id FROM distributor_applies WHERE user_id=? AND status='pending'", [req.userId]);
      if (exist) return res.json(fail('申请已提交，请等待审核'));
      run(`INSERT INTO distributor_applies(user_id,real_name,phone,wechat,reason,status,created_at)
        VALUES(?,?,?,?,?,'pending',datetime('now','localtime'))`,
        [req.userId, real_name || '', phone || '', wechat || '', reason || '']);
      return res.json(success(null, '申请已提交，请等待平台审核'));
    }
    return res.json(fail('当前未满足开通分销条件'));
  } catch (e) {
    return res.json(fail('申请失败'));
  }
});
// 申请提现
router.post('/withdraw', (req, res) => {
  try {
    const { amount, account_type, account_info } = req.body;
    const minWithdraw = +(get('SELECT value FROM distribution_config WHERE key=?', ['min_withdraw'])?.value || 10);
    if (!amount || amount < minWithdraw) return res.json(fail(`最低提现金额${minWithdraw}元`));
    // 🔒 资金安全：提现校验+扣减必须在事务内，防并发重复提现/超提
    const result = transaction(() => {
      const user = get('SELECT id,freeze_balance FROM users WHERE id=?', [req.userId]);
      if (!user) throw new Error('用户不存在');
      const settled = get('SELECT COALESCE(SUM(commission),0) as c FROM distribution_records WHERE user_id=? AND status=\'settled\'', [req.userId]).c;
      const used = get('SELECT COALESCE(SUM(amount),0) as c FROM withdraw_requests WHERE user_id=? AND status IN (\'pending\',\'approved\')', [req.userId]).c;
      const available = +(settled - used).toFixed(2);
      if (amount > available) throw new Error('可提现金额不足');
      const fee = +(amount * (+(get('SELECT value FROM distribution_config WHERE key=?', ['withdraw_fee_rate'])?.value || 0) / 100)).toFixed(2);
      const realAmount = +(amount - fee).toFixed(2);
      run('INSERT INTO withdraw_requests(user_id,amount,fee,real_amount,account_type,account_info) VALUES(?,?,?,?,?,?)',
        [req.userId, amount, fee, realAmount, account_type || 'wechat', account_info || '']);
      run('UPDATE users SET freeze_balance=freeze_balance+? WHERE id=?', [amount, req.userId]);
      return { amount, fee, realAmount };
    });
    return res.json(success(result, '申请成功，等待审核'));
  } catch (e) {
    return res.json(fail(e.message || '申请失败'));
  }
});
// 提现记录
router.get('/withdraw/list', (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 withdraw_requests WHERE user_id=?', [req.userId]).c;
  const list = all('SELECT * FROM withdraw_requests WHERE user_id=? ORDER BY id DESC LIMIT ? OFFSET ?', [req.userId, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});
// 分销二维码（简化为分享链接）
router.get('/qrcode', (req, res) => {
  const inviteUrl = `${req.protocol}://${req.get('host')}/mobile/#/?parent_id=${req.userId}`;
  return res.json(success({ url: inviteUrl, user_id: req.userId }));
});
// 绑定上级
router.post('/bind', (req, res) => {
  try {
    const { parent_id } = req.body;
    if (!parent_id || parent_id == req.userId) return res.json(fail('无效的上级'));
    const user = get('SELECT parent_id FROM users WHERE id=?', [req.userId]);
    if (user.parent_id) return res.json(fail('已绑定上级，不可更改'));
    
    const parent = get('SELECT id FROM users WHERE id=?', [parent_id]);
    if (!parent) return res.json(fail('上级用户不存在'));
    // 免费版团队人数上限检查
    const teamCheck = checkTeamLimit(parent_id);
    if (!teamCheck.ok) {
      return res.json(fail(teamCheck.message, 403));
    }
    run('UPDATE users SET parent_id=? WHERE id=?', [parent_id, req.userId]);
    run('UPDATE users SET team_count=team_count+1 WHERE id=?', [parent_id]);
    return res.json(success(null, '绑定成功'));
  } catch (e) {
    return res.json(fail('绑定失败'));
  }
});
module.exports = router;