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 bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('../../config');

router.use(authAdmin);

// ============================
//  1. 系统配置管理 (可视化配置面板)
// ============================

// 获取所有配置 (按组)
router.get('/config', (req, res) => {
  const configs = all('SELECT * FROM system_config ORDER BY group_name, id ASC');
  const grouped = {};
  for (const c of configs) {
    if (!grouped[c.group_name]) grouped[c.group_name] = [];
    grouped[c.group_name].push(c);
  }
  return res.json(success(grouped));
});

// 更新配置 (批量)
router.put('/config', (req, res) => {
  try {
    const { updates } = req.body;
    if (!updates || !updates.length) return res.json(fail('无更新数据'));
    
    transaction(() => {
      for (const u of updates) {
        run('UPDATE system_config SET value=? WHERE key=?', [String(u.value), u.key]);
      }
    });
    return res.json(success(null, '配置更新成功'));
  } catch (e) {
    console.error('配置更新失败:', e);
    return res.json(fail('配置更新失败'));
  }
});

// ============================
//  2. 模块开关状态
// ============================
router.get('/modules', (req, res) => {
  const modules = all("SELECT key, value, description FROM system_config WHERE group_name='module'");
  const map = {};
  modules.forEach(m => map[m.key.replace('module_', '')] = m.value === '1');
  return res.json(success(map));
});

// ============================
//  3. 管理员列表
// ============================
router.get('/admins', (req, res) => {
  const list = all("SELECT id, nickname, phone, avatar, status, created_at FROM users ORDER BY id ASC");
  return res.json(success(list));
});

// 创建管理员
router.post('/admins', async (req, res) => {
  try {
    const { phone, password, nickname } = req.body;
    if (!phone || !password) return res.json(fail('手机号和密码不能为空'));
    if (password.length < 6) return res.json(fail('密码长度不能少于6位'));
    
    const exist = get('SELECT id FROM users WHERE phone=?', [phone]);
    if (exist) return res.json(fail('该账号已存在'));
    
    const hash = await bcrypt.hash(password, 10);
    run('INSERT INTO users(phone,password,nickname) VALUES(?,?,?)',
      [phone, hash, nickname || phone]);
    return res.json(success(null, '创建成功'));
  } catch (e) {
    return res.json(fail('创建失败'));
  }
});

// 修改管理员状态
router.put('/admins/:id/status', (req, res) => {
  const { status } = req.body;
  const id = +req.params.id;
  if (id === 1) return res.json(fail('不能操作超级管理员'));
  run('UPDATE users SET status=? WHERE id=?', [status, id]);
  return res.json(success(null, status ? '已启用' : '已禁用'));
});

// 删除管理员
router.delete('/admins/:id', (req, res) => {
  const id = +req.params.id;
  if (id === 1) return res.json(fail('不能删除超级管理员'));
  run('DELETE FROM users WHERE id=?', [id]);
  return res.json(success(null, '删除成功'));
});

// ============================
//  4. 角色权限
// ============================
router.get('/roles', (req, res) => {
  const perms = [
    { id: 1, name: '超级管理员', permissions: 'all', desc: '系统全部权限，无限制' },
    { id: 2, name: '运营', permissions: 'products,orders,users,marketing,distribution,ai', desc: '商品、订单、用户、营销管理' },
    { id: 3, name: '财务', permissions: 'orders,users,distribution,stats,export', desc: '订单查看、数据统计、导出' },
    { id: 4, name: '客服', permissions: 'orders,users,ai', desc: '订单处理、用户查询、AI客服管理' },
  ];
  return res.json(success(perms));
});

// ============================
//  5. 数据库备份
// ============================
router.post('/backup', (req, res) => {
  try {
    const fs = require('fs');
    const path = require('path');
    const src = config.dbPath;
    const backupDir = path.join(path.dirname(src), 'backup');
    if (!fs.existsSync(backupDir)) fs.mkdirSync(backupDir, { recursive: true });
    
    const date = new Date();
    const stamp = `${date.getFullYear()}${String(date.getMonth()+1).padStart(2,'0')}${String(date.getDate()).padStart(2,'0')}_${String(date.getHours()).padStart(2,'0')}${String(date.getMinutes()).padStart(2,'0')}`;
    const dest = path.join(backupDir, 'litemall_' + stamp + '.db');
    
    fs.copyFileSync(src, dest);
    const size = fs.statSync(dest).size;
    
    const keepDays = +(get("SELECT value FROM system_config WHERE key='backup_keep_days'")?.value || 7);
    const files = fs.readdirSync(backupDir).filter(f => f.startsWith('litemall_') && f.endsWith('.db'));
    const now = Date.now();
    for (const f of files) {
      const fp = path.join(backupDir, f);
      const age = (now - fs.statSync(fp).mtimeMs) / 86400000;
      if (age > keepDays) fs.unlinkSync(fp);
    }
    
    return res.json(success({ path: dest, size, keepDays }, '备份成功'));
  } catch (e) {
    return res.json(fail('备份失败: ' + e.message));
  }
});

// 备份列表
router.get('/backups', (req, res) => {
  try {
    const fs = require('fs');
    const path = require('path');
    const backupDir = path.join(path.dirname(config.dbPath), 'backup');
    if (!fs.existsSync(backupDir)) return res.json(success([]));
    
    const files = fs.readdirSync(backupDir)
      .filter(f => f.startsWith('litemall_') && f.endsWith('.db'))
      .map(f => {
        const fp = path.join(backupDir, f);
        const stat = fs.statSync(fp);
        return { name: f, size: stat.size, mtime: stat.mtime.toISOString() };
      })
      .sort((a, b) => b.mtime < a.mtime ? -1 : 1);
    
    return res.json(success(files));
  } catch (e) {
    return res.json(fail('获取备份列表失败'));
  }
});

// 恢复备份
router.post('/backup/restore', (req, res) => {
  try {
    const { name } = req.body;
    if (!name) return res.json(fail('请指定备份文件'));
    const fs = require('fs');
    const path = require('path');
    const backupDir = path.join(path.dirname(config.dbPath), 'backup');
    // 🔒 防路径穿越：仅允许合法的备份文件名（白名单），拒绝 .. / / 绝对路径
    const plain = path.basename(String(name));
    if (name !== plain || !/^litemall_[A-Za-z0-9_.-]+\.(db|sqlite)$/.test(plain)) {
      return res.json(fail('非法的备份文件名'));
    }
    const src = path.join(backupDir, plain);
    if (!fs.existsSync(src)) return res.json(fail('备份文件不存在'));
    
    const { close } = require('../utils/db');
    close();
    fs.copyFileSync(src, config.dbPath);
    
    return res.json(success(null, '恢复成功，请重启服务'));
  } catch (e) {
    return res.json(fail('恢复失败: ' + e.message));
  }
});

// ============================
//  6. 运行日志
// ============================
router.get('/logs', (req, res) => {
  try {
    const fs = require('fs');
    const path = require('path');
    const logFile = path.join(__dirname, '..', '..', 'server.log');
    if (!fs.existsSync(logFile)) return res.json(success({ lines: ['暂无日志数据'], total: 0 }));
    
    const maxLines = 200;
    const content = fs.readFileSync(logFile, 'utf-8');
    const lines = content.split('\n').filter(Boolean).slice(-maxLines).reverse();
    
    return res.json(success({ lines, total: lines.length }));
  } catch (e) {
    return res.json(fail('读取日志失败'));
  }
});

// 清除日志
router.delete('/logs', (req, res) => {
});

// ============================
//  7. 运营模式切换
// ============================
router.post('/switch-mode', (req, res) => {
  const { mode } = req.body;
  if (!['test', 'production'].includes(mode)) return res.json(fail('无效模式'));
  run("UPDATE system_config SET value=? WHERE key='operate_mode'", [mode]);
  const label = mode === 'test' ? '测试' : '正式';
  return res.json(success({ mode }, '已切换至' + label + '模式'));
});

// 获取当前模式
router.get('/mode', (req, res) => {
  const mode = get("SELECT value FROM system_config WHERE key='operate_mode'")?.value || 'test';
  return res.json(success({ mode, label: mode === 'test' ? '测试模式' : '正式运营' }));
});


// ============================
//  8. 登录日志
// ============================
router.get('/login-logs', (req, res) => {
  const { page: p = 1, pageSize = 30, phone, result } = 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 (phone) { where += ' AND phone LIKE ?'; params.push('%' + phone + '%'); }
  if (result) { where += ' AND result=?'; params.push(result); }
  
  const total = get('SELECT COUNT(*) as c FROM login_logs ' + where, params).c;
  const list = all('SELECT * FROM login_logs ' + where + ' ORDER BY id DESC LIMIT ? OFFSET ?',
    [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

// 登录日志统计
router.get('/login-logs/stats', (req, res) => {
  const today = get("SELECT COUNT(*) as total, SUM(CASE WHEN result='success' THEN 1 ELSE 0 END) as success, SUM(CASE WHEN result='fail' THEN 1 ELSE 0 END) as fail FROM login_logs WHERE date(created_at)=date('now','localtime')");
  const total = get('SELECT COUNT(*) as c FROM login_logs').c;
  return res.json(success({ today, total }));
});

// ============================
//  9. 密码强度检查
// ============================
router.post('/check-password', (req, res) => {
  const { password } = req.body;
  const { checkPasswordStrength } = require('../middleware/security');
  const errors = checkPasswordStrength(password);
  return res.json(success({ valid: errors.length === 0, errors }));
});

module.exports = router;
