const express = require('express');
const router = express.Router();
const { get, run, all, transaction } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authAdmin } = require('../middleware/auth');
const { demoSafeGuard } = require("./admin-auth");

// ========== 分销管理 ==========
router.get('/distribution/users', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 20, keyword } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(100, Math.max(1, +pageSize));
  let where = "WHERE u.parent_id IS NOT NULL AND u.phone != 'admin'";
  const params = [];
  if (keyword) { where += ' AND (u.nickname LIKE ? OR u.phone LIKE ?)'; params.push(`%${keyword}%`, `%${keyword}%`); }

  const total = get(`SELECT COUNT(DISTINCT u.id) as c FROM users u ${where}`, params).c;
  const list = all(`SELECT u.id,u.nickname,u.avatar,u.phone,u.team_count,u.total_consumed,u.created_at,
    (SELECT COALESCE(SUM(commission),0) FROM distribution_records WHERE user_id=u.id AND status='settled') as total_commission
    FROM users u ${where} ORDER BY u.id DESC LIMIT ? OFFSET ?`, [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

router.get('/distribution/commissions', authAdmin, (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 1=1';
  const params = [];
  if (status) { where += ' AND dr.status=?'; params.push(status); }

  const total = get(`SELECT COUNT(*) as c FROM distribution_records dr ${where}`, params).c;
  const list = all(`SELECT dr.*, u.nickname, u.phone, o.order_no FROM distribution_records dr 
    LEFT JOIN users u ON dr.user_id=u.id 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.post('/distribution/commission/:id/settle', authAdmin, demoSafeGuard, (req, res) => {
  run("UPDATE distribution_records SET status='settled',settled_at=datetime('now','localtime') WHERE id=?", [req.params.id]);
  return res.json(success(null, '已结算'));
});

router.get('/distribution/withdraws', authAdmin, (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 1=1';
  const params = [];
  if (status) { where += ' AND wr.status=?'; params.push(status); }

  const total = get(`SELECT COUNT(*) as c FROM withdraw_requests wr ${where}`, params).c;
  const list = all(`SELECT wr.*, u.nickname, u.phone FROM withdraw_requests wr LEFT JOIN users u ON wr.user_id=u.id ${where} ORDER BY wr.id DESC LIMIT ? OFFSET ?`,
    [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

router.post('/distribution/withdraw/:id/approve', authAdmin, demoSafeGuard, (req, res) => {
  const wr = get('SELECT * FROM withdraw_requests WHERE id=?', [req.params.id]);
  if (!wr) return res.json(fail('记录不存在'));
  transaction(() => {
    run("UPDATE withdraw_requests SET status='approved',completed_at=datetime('now','localtime') WHERE id=?", [req.params.id]);
    run('UPDATE users SET freeze_balance=freeze_balance-?,balance=balance-? WHERE id=?', [wr.amount, wr.amount, wr.user_id]);
  });
  return res.json(success(null, '审核通过'));
});

router.post('/distribution/withdraw/:id/reject', authAdmin, demoSafeGuard, (req, res) => {
  const { reject_reason } = req.body;
  const wr = get('SELECT * FROM withdraw_requests WHERE id=?', [req.params.id]);
  if (!wr) return res.json(fail('记录不存在'));
  transaction(() => {
    run('UPDATE withdraw_requests SET status=?,reject_reason=? WHERE id=?', ['rejected', reject_reason||'', req.params.id]);
    run('UPDATE users SET freeze_balance=freeze_balance-? WHERE id=?', [wr.amount, wr.user_id]);
  });
  return res.json(success(null, '已拒绝'));
});

router.get('/distribution/levels', authAdmin, (req, res) => {
  const list = all('SELECT * FROM distribution_levels ORDER BY level ASC');
  return res.json(success(list));
});

router.post('/distribution/levels', authAdmin, demoSafeGuard, (req, res) => {
  const { name, level, min_team_count, min_team_sales, commission_rate, commission_rate2, commission_rate3 } = req.body;
  run('INSERT INTO distribution_levels(name,level,min_team_count,min_team_sales,commission_rate,commission_rate2,commission_rate3) VALUES(?,?,?,?,?,?,?)',
    [name, level, min_team_count||0, min_team_sales||0, commission_rate||0, commission_rate2||0, commission_rate3||0]);
  return res.json(success(null, '添加成功'));
});

router.put('/distribution/levels/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { name, min_team_count, min_team_sales, commission_rate, commission_rate2, commission_rate3, status } = req.body;
  run('UPDATE distribution_levels SET name=?,min_team_count=?,min_team_sales=?,commission_rate=?,commission_rate2=?,commission_rate3=?,status=? WHERE id=?',
    [name, min_team_count||0, min_team_sales||0, commission_rate||0, commission_rate2||0, commission_rate3||0, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});

// 分销设置
router.get('/distribution/settings', authAdmin, (req, res) => {
  const list = all('SELECT * FROM distribution_config ORDER BY id');
  return res.json(success(list));
});
router.put('/distribution/settings', authAdmin, demoSafeGuard, (req, res) => {
  const { configs } = req.body;
  for (const c of configs) {
    run('INSERT OR REPLACE INTO distribution_config(key,value,description) VALUES(?,?,?)', [c.key, c.value, c.desc||'']);
  }
  return res.json(success(null, '保存成功'));
});

// 分销员申请
router.get('/distribution/applies', authAdmin, (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 1=1'; const params = [];
  if (status) { where += ' AND a.status=?'; params.push(status); }
  const total = get(`SELECT COUNT(*) as c FROM distributor_applies a ${where}`, params).c;
  const list = all(`SELECT a.*, u.nickname, u.phone as user_phone FROM distributor_applies a LEFT JOIN users u ON a.user_id=u.id ${where} ORDER BY a.id DESC LIMIT ? OFFSET ?`, [...params, size, (pageNum-1)*size]);
  return res.json(page(list, total, pageNum, size));
});
router.post('/distribution/applies/:id/approve', authAdmin, demoSafeGuard, (req, res) => {
  run("UPDATE distributor_applies SET status='approved',handled_at=datetime('now','localtime') WHERE id=?", [req.params.id]);
  const apply = get('SELECT user_id FROM distributor_applies WHERE id=?', [req.params.id]);
  // 🩹联动：审核通过时按会员等级设置分销等级档位（白银=1/黄金=2/钻石=3，默认普通=1）
  const u = get('SELECT level_id, distributor_level FROM users WHERE id=?', [apply.user_id]);
  const levelMap = { 2: 1, 3: 2, 4: 3 };
  const mapped = levelMap[u && u.level_id] || 1;
  const finalLevel = (u && u.distributor_status === 'active' && u.distributor_level)
    ? Math.max(u.distributor_level, mapped) : mapped;
  run("UPDATE users SET distributor_status='active', distributor_level=? WHERE id=?", [finalLevel, apply.user_id]);
  return res.json(success(null, '已通过'));
});
router.post('/distribution/applies/:id/reject', authAdmin, demoSafeGuard, (req, res) => {
  const { reason } = req.body;
  run("UPDATE distributor_applies SET status='rejected',reject_reason=?,handled_at=datetime('now','localtime') WHERE id=?", [reason||'', req.params.id]);
  return res.json(success(null, '已拒绝'));
});

// 事业部
router.get('/distribution/divisions', authAdmin, (req, res) => {
  const list = all('SELECT d.*, u.nickname as manager_name FROM business_divisions d LEFT JOIN users u ON d.manager_id=u.id ORDER BY d.id DESC');
  return res.json(success(list));
});
router.post('/distribution/divisions', authAdmin, demoSafeGuard, (req, res) => {
  const { name, manager_id, description, commission_rate } = req.body;
  run('INSERT INTO business_divisions(name,manager_id,description,commission_rate) VALUES(?,?,?,?)', [name, manager_id||null, description||'', commission_rate||0]);
  return res.json(success(null, '添加成功'));
});
router.put('/distribution/divisions/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { name, manager_id, description, commission_rate, status } = req.body;
  run('UPDATE business_divisions SET name=?,manager_id=?,description=?,commission_rate=?,status=? WHERE id=?', [name, manager_id||null, description||'', commission_rate||0, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});
router.delete('/distribution/divisions/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM business_divisions WHERE id=?', [req.params.id]);
  return res.json(success(null, '删除成功'));
});

router.delete('/distribution/levels/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM distribution_levels WHERE id=?', [req.params.id]);
  return res.json(success(null, '删除成功'));
});

router.put('/distribution/config', authAdmin, demoSafeGuard, (req, res) => {
  const { configs } = req.body; // [{key, value}]
  for (const c of configs) {
    run('UPDATE distribution_config SET value=? WHERE key=?', [c.value, c.key]);
  }
  return res.json(success(null, '更新成功'));
});
// ========== 分销进阶 ==========
router.get('/distribution/dashboard', authAdmin, (req, res) => {
  const totalCommission = get("SELECT COALESCE(SUM(commission),0) as s FROM distribution_records WHERE status='settled'").s;
  const pendingCommission = get("SELECT COALESCE(SUM(commission),0) as s FROM distribution_records WHERE status='pending'").s;
  const totalWithdrawn = get("SELECT COALESCE(SUM(amount),0) as s FROM withdraw_requests WHERE status='approved'").s;
  const distributors = get("SELECT COUNT(*) as c FROM users WHERE distributor_status='active'").c;
  const teamCount = get('SELECT COALESCE(SUM(team_count),0) as c FROM users').c;
  res.json(success({totalCommission,pendingCommission,totalWithdrawn,distributors,teamCount}));
});
router.get('/distribution/level-stats', authAdmin, (req, res) => {
  const stats = all('SELECT dl.name,dl.level,COUNT(u.id) as users FROM distribution_levels dl LEFT JOIN users u ON u.distributor_level=dl.level AND u.distributor_status=\'active\' GROUP BY dl.id ORDER BY dl.level');
  res.json(success(stats));
});
router.get('/distribution/team-ranking', authAdmin, (req, res) => {
  const ranking = all("SELECT u.id,u.nickname,u.phone,u.team_count,COALESCE((SELECT SUM(commission) FROM distribution_records WHERE user_id=u.id AND status='settled'),0) as total_commission FROM users u WHERE u.distributor_status='active' AND u.team_count>0 ORDER BY u.team_count DESC LIMIT 10");
  res.json(success(ranking));
});
router.get('/distribution/commission-trend', authAdmin, (req, res) => {
  const trend = all("SELECT date(created_at) as d,COUNT(*) as cnt,COALESCE(SUM(commission),0) as amount FROM distribution_records WHERE created_at>=date('now','-30 days') GROUP BY d ORDER BY d");
  res.json(success(trend));
});
// 事业部API
router.get('/distribution/teams', authAdmin, (req, res) => {
  const list = all('SELECT * FROM business_divisions ORDER BY id DESC');
  res.json(success(list));
});
router.post('/distribution/teams', authAdmin, demoSafeGuard, (req, res) => {
  const r = run('INSERT INTO business_divisions(name,manager_id,description,commission_rate) VALUES(?,?,?,?)',[req.body.name,req.body.manager_id||null,req.body.description||'',req.body.commission_rate||0]);
  res.json(success({id:r.lastInsertRowid},'添加成功'));
});
router.put('/distribution/teams/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('UPDATE business_divisions SET name=?,manager_id=?,description=?,commission_rate=?,status=? WHERE id=?',[req.body.name,req.body.manager_id||null,req.body.description||'',req.body.commission_rate||0,req.body.status||1,req.params.id]);
  res.json(success(null,'更新成功'));
});
router.delete('/distribution/teams/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM business_divisions WHERE id=?',[req.params.id]);
  res.json(success(null,'已删除'));
});


module.exports = { router };
