/**
 * 分销佣金计算与记录服务
 * ============================================
 * 职责：
 *   1. 订单支付后自动创建佣金记录
 *   2. 佣金试算器（管理后台）
 *   3. 佣金变更日志审计
 *   4. 佣金自动结算
 *

 */
const { get, run, all, transaction } = require('../utils/db');
const notification = require('../lib/notification');
const { checkCommissionCap } = require('../lib/limits');
// ===================================================================
// 1. 支付成功后创建佣金记录
// ===================================================================
function createCommissionRecords(orderId) {
  const order = get('SELECT * FROM orders WHERE id=?', [orderId]);
  if (!order) return [];
  if (order.status !== 'pending_ship' && order.status !== 'received' && order.status !== 'completed') return [];
  
  // 检查分销是否开启
  const distOpen = get("SELECT value FROM distribution_config WHERE key='is_open'")?.value;
  if (distOpen !== '1') return [];
  // 检查分销层级配置
  const levels = +(get("SELECT value FROM distribution_config WHERE key='commission_levels'")?.value || 3);
  
  // 获取买家信息，找上级链
  const buyer = get('SELECT id,parent_id FROM users WHERE id=?', [order.user_id]);
  if (!buyer || !buyer.parent_id) return []; // 没有上级，不产生佣金
  const items = all('SELECT * FROM order_items WHERE order_id=?', [orderId]);
  let createdRecords = [];
  
  // 向上查找三级分销链
  let currentUserId = buyer.parent_id;
  let currentLevel = 1;
  while (currentUserId && currentLevel <= levels && currentLevel <= 3) {
    // 检查上级是否为分销商（🩹修复：佣金等级用分销等级 distributor_level，不再误用会员等级 level_id）
    const parent = get('SELECT id,nickname,distributor_status,distributor_level FROM users WHERE id=?', [currentUserId]);
    if (!parent) break;
    // 未开通分销的上家不产生佣金，继续向上追溯
    if (parent.distributor_status !== 'active' || !parent.distributor_level) {
      currentUserId = get('SELECT parent_id FROM users WHERE id=?', [currentUserId])?.parent_id;
      currentLevel++;
      continue;
    }
    // 计算该级别的佣金率（按分销等级 distributor_level 对应档位）
    const rate = getCommissionRate(parent.distributor_level, currentLevel);
    if (rate <= 0) {
      // 继续找上一级
      currentUserId = get('SELECT parent_id FROM users WHERE id=?', [currentUserId])?.parent_id;
      currentLevel++;
      continue;
    }
    // 逐商品计算佣金
    for (const item of items) {
      // 获取商品分销比例
      const product = get('SELECT commission_rate FROM products WHERE id=?', [item.product_id]);
      const productCommissionRate = product?.commission_rate || 0;
      
      // 最终佣金率 = 等级佣金率 × 商品佣金系数
      const finalRate = rate * (productCommissionRate > 0 ? productCommissionRate / 100 : 1.0);
      const commission = Math.round(item.subtotal * finalRate * 100) / 100;
      if (commission <= 0) continue;
      // 佣金上限检查（免费版）
      const capCheck = checkCommissionCap(currentUserId);
      if (!capCheck.ok) continue;
      // 写入佣金记录
      const result = run(
        `INSERT INTO distribution_records(order_id, order_item_id, buyer_id, user_id, level, product_amount, rate, commission, status, created_at)
         VALUES(?,?,?,?,?,?,?,?, 'pending', datetime('now','localtime'))`,
        [orderId, item.id, order.user_id, currentUserId, currentLevel, item.subtotal, finalRate, commission]
      );
      createdRecords.push({
        id: result.lastInsertRowid,
        user_id: currentUserId,
        level: currentLevel,
        commission,
        product: item.product_name
      });
    }
    // 继续找上一级
    currentUserId = get('SELECT parent_id FROM users WHERE id=?', [currentUserId])?.parent_id;
    currentLevel++;
  }
  // 记录佣金变更日志
  for (const record of createdRecords) {
    addCommissionLog({
      user_id: record.user_id,
      amount: record.commission,
      type: 'earn',
      source: 'order',
      source_id: orderId,
      note: `订单支付佣金: 第${record.level}级, 商品: ${record.product}, 金额: ¥${record.commission}`
    });
  }
  return createdRecords;
}
// ===================================================================
// 2. 获取佣金率（根据用户分销等级和分销层级）
// ===================================================================
function getCommissionRate(userDistributorLevel, distLevel) {
  // userDistributorLevel = 分销等级档位(distribution_levels.level)，与后台 `u.distributor_level=dl.level` 对齐
  const level = get('SELECT commission_rate,commission_rate2,commission_rate3 FROM distribution_levels WHERE level=?', [userDistributorLevel]);
  if (!level) return 0;
  switch (distLevel) {
    case 1: return level.commission_rate || 0;
    case 2: return level.commission_rate2 || 0;
    case 3: return level.commission_rate3 || 0;
    default: return 0;
  }
}
// ===================================================================
// 3. 佣金试算器（管理后台用）
// ===================================================================
function calculateCommission(productPrice, productCommissionRate, userLevelId, quantity = 1) {
  const total = productPrice * quantity;
  const levels = get('SELECT id, name, level, commission_rate, commission_rate2, commission_rate3 FROM distribution_levels WHERE id=?', [userLevelId]);
  if (!levels) return { error: '分销等级不存在' };
  const rate = productCommissionRate > 0 ? productCommissionRate / 100 : 1.0;
  const finalCommissionRate = productCommissionRate > 0 ? 0 : 1.0;
  const results = [];
  // 一级佣金
  const l1Rate = levels.commission_rate * rate;
  const l1Amount = Math.round(total * l1Rate * 100) / 100;
  if (l1Rate > 0) {
    results.push({
      level: 1,
      name: levels.name,
      baseRate: levels.commission_rate,
      productRate: productCommissionRate > 0 ? productCommissionRate + '%' : '默认',
      effectiveRate: Math.round(l1Rate * 10000) / 100 + '%',
      amount: l1Amount
    });
  }
  // 二级佣金
  const l2Rate = levels.commission_rate2 * rate;
  const l2Amount = Math.round(total * l2Rate * 100) / 100;
  if (l2Rate > 0) {
    results.push({
      level: 2, name: levels.name + '(二级)',
      baseRate: levels.commission_rate2,
      productRate: productCommissionRate > 0 ? productCommissionRate + '%' : '默认',
      effectiveRate: Math.round(l2Rate * 10000) / 100 + '%',
      amount: l2Amount
    });
  }
  // 三级佣金
  const l3Rate = levels.commission_rate3 * rate;
  const l3Amount = Math.round(total * l3Rate * 100) / 100;
  if (l3Rate > 0) {
    results.push({
      level: 3, name: levels.name + '(三级)',
      baseRate: levels.commission_rate3,
      productRate: productCommissionRate > 0 ? productCommissionRate + '%' : '默认',
      effectiveRate: Math.round(l3Rate * 10000) / 100 + '%',
      amount: l3Amount
    });
  }
  return {
    product_price: productPrice,
    quantity,
    total,
    detail: results,
    total_commission: results.reduce((s, r) => s + r.amount, 0)
  };
}
// ===================================================================
// 4. 佣金变更日志
// ===================================================================
function addCommissionLog({ user_id, amount, type, source, source_id, note }) {
  run(`INSERT INTO commission_logs(user_id, amount, type, source, source_id, note, created_at)
       VALUES(?,?,?,?,?,?, datetime('now','localtime'))`,
    [user_id, amount, type, source, source_id, note || '']);
}
function getCommissionLogs(userId, pageNum = 1, pageSize = 20) {
  const total = get('SELECT COUNT(*) as c FROM commission_logs WHERE user_id=?', [userId]).c;
  const list = all('SELECT * FROM commission_logs WHERE user_id=? ORDER BY id DESC LIMIT ? OFFSET ?',
    [userId, pageSize, (pageNum - 1) * pageSize]);
  return { list, total };
}
function getAllCommissionLogs(pageNum = 1, pageSize = 50, filters = {}) {
  let where = 'WHERE 1=1';
  const params = [];
  if (filters.user_id) { where += ' AND user_id=?'; params.push(filters.user_id); }
  if (filters.type) { where += ' AND type=?'; params.push(filters.type); }
  if (filters.source) { where += ' AND source=?'; params.push(filters.source); }
  const total = get(`SELECT COUNT(*) as c FROM commission_logs ${where}`, params).c;
  const list = all(`SELECT cl.*, u.nickname FROM commission_logs cl LEFT JOIN users u ON cl.user_id=u.id ${where} ORDER BY cl.id DESC LIMIT ? OFFSET ?`,
    [...params, pageSize, (pageNum - 1) * pageSize]);
  return { list, total, page: pageNum, pageSize };
}
// ===================================================================
// 5. 佣金自动结算（定时任务调用）
// ===================================================================
function autoSettleCommissions() {
  const settleDays = +(get("SELECT value FROM distribution_config WHERE key='auto_settle_days'")?.value || 7);
  
  const pendingRecords = all(`SELECT dr.*, o.order_no 
    FROM distribution_records dr 
    JOIN orders o ON dr.order_id=o.id 
    WHERE dr.status='pending' AND o.status IN ('received','completed')
    AND datetime(o.confirm_time, '+' || ? || ' days') <= datetime('now','localtime')`, [settleDays]);
  let settledCount = 0;
  for (const record of pendingRecords) {
    transaction(() => {
      run("UPDATE distribution_records SET status='settled', settled_at=datetime('now','localtime') WHERE id=?", [record.id]);
      run('UPDATE users SET total_commission=COALESCE(total_commission,0)+? WHERE id=?', [record.commission, record.user_id]);
      addCommissionLog({
        user_id: record.user_id,
        amount: record.commission,
        type: 'settle',
        source: 'auto',
        source_id: record.id,
        note: `佣金自动结算: 订单${record.order_no}, 金额¥${record.commission}`
      });
      // 通知分销员
      notification.send('commission_received', record.user_id, {
        amount: record.commission.toFixed(2),
        order_no: record.order_no,
        balance: get('SELECT COALESCE(SUM(commission),0) as c FROM distribution_records WHERE user_id=? AND status=\'settled\'', [record.user_id]).c.toFixed(2)
      }).catch(() => {});
    });
    settledCount++;
  }
  return settledCount;
}
// ===================================================================
// 6. 手动调整佣金（管理后台）
// ===================================================================
function adjustCommission(recordId, newAmount, reason, operator) {
  const record = get('SELECT * FROM distribution_records WHERE id=?', [recordId]);
  if (!record) return { success: false, message: '佣金记录不存在' };
  if (record.status === 'settled') return { success: false, message: '已结算不可调整' };
  const oldAmount = record.commission;
  if (newAmount > oldAmount) return { success: false, message: '只允许减少不允许增加' };
  if (newAmount < 0) return { success: false, message: '金额不能为负数' };
  transaction(() => {
    run('UPDATE distribution_records SET commission=? WHERE id=?', [newAmount, recordId]);
    addCommissionLog({
      user_id: record.user_id,
      amount: oldAmount - newAmount,
      type: 'adjust',
      source: 'manual',
      source_id: recordId,
      note: `人工调整佣金: ¥${oldAmount}→¥${newAmount}, 原因: ${reason || '无'}, 操作人: ${operator}`
    });
  });
  return { success: true, message: `佣金已从¥${oldAmount}调整为¥${newAmount}` };
}
module.exports = {
  createCommissionRecords,
  getCommissionRate,
  calculateCommission,
  addCommissionLog,
  getCommissionLogs,
  getAllCommissionLogs,
  autoSettleCommissions,
  adjustCommission,
  openDistribution,
  resolveDistributorLevel
};

// ===================================================================
// 分销开通辅助：付费会员开通 / 用户申请开通（统一入口，幂等）
// ===================================================================
// 映射：会员等级 → 建议分销等级（1=普通分销商起步；白银=1；黄金=2；钻石=3）
function resolveDistributorLevel(memberLevelId) {
  const map = { 2: 1, 3: 2, 4: 3 };
  return map[memberLevelId] || 1;
}

// 开通分销（幂等）：设置 distributor_status=active 并保底分销等级
function openDistribution(userId, distributorLevel) {
  const user = get('SELECT distributor_status, distributor_level FROM users WHERE id=?', [userId]);
  if (!user) return { ok: false, reason: '用户不存在' };
  const target = distributorLevel > 0 ? distributorLevel : resolveDistributorLevel(get('SELECT level_id FROM users WHERE id=?', [userId])?.level_id);
  // 已开通则保留较高等级
  const finalLevel = user.distributor_status === 'active' ? Math.max(user.distributor_level || 1, target) : target;
  run('UPDATE users SET distributor_status=?, distributor_level=? WHERE id=?', ['active', finalLevel, userId]);
  return { ok: true, level: finalLevel };
}