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

// ====== 预设主题 ======
const PRESET_THEMES = {
  'icy_blue': {
    name: '冰蓝',
    desc: '清爽商务蓝',
    colors: {
      primary: '#4A7CF7',
      primaryLight: '#7C9FFF',
      pageBg: '#f5f7fa',
      cardBg: '#ffffff',
      headerBg: 'linear-gradient(135deg, #4A7CF7, #7C9FFF)',
      headerText: '#ffffff',
      tabbarActive: '#4A7CF7',
      tabbarInactive: '#999999',
      tabbarBg: '#ffffff',
      priceColor: '#ee0a24',
      tagColor: '#ee0a24',
      tagText: '#ffffff',
      buttonPrimary: '#4A7CF7',
      buttonText: '#ffffff',
      titleText: '#1a1a2e',
      bodyText: '#333333',
      secondaryText: '#999999',
      borderColor: '#eeeeee',
      shadow: 'rgba(74,124,247,0.2)'
    }
  },
  'sunset_purple': {
    name: '暮山紫',
    desc: '高端优雅紫',
    colors: {
      primary: '#7C5BF7',
      primaryLight: '#A78BFA',
      pageBg: '#f8f6fe',
      cardBg: '#ffffff',
      headerBg: 'linear-gradient(135deg, #7C5BF7, #A78BFA)',
      headerText: '#ffffff',
      tabbarActive: '#7C5BF7',
      tabbarInactive: '#999999',
      tabbarBg: '#ffffff',
      priceColor: '#e84393',
      tagColor: '#e84393',
      tagText: '#ffffff',
      buttonPrimary: '#7C5BF7',
      buttonText: '#ffffff',
      titleText: '#1a1a2e',
      bodyText: '#333333',
      secondaryText: '#999999',
      borderColor: '#eeeeee',
      shadow: 'rgba(124,91,247,0.2)'
    }
  },
  'forest_green': {
    name: '青绿',
    desc: '自然清新绿',
    colors: {
      primary: '#10B981',
      primaryLight: '#34D399',
      pageBg: '#f0fdf4',
      cardBg: '#ffffff',
      headerBg: 'linear-gradient(135deg, #059669, #34D399)',
      headerText: '#ffffff',
      tabbarActive: '#10B981',
      tabbarInactive: '#999999',
      tabbarBg: '#ffffff',
      priceColor: '#ef4444',
      tagColor: '#ef4444',
      tagText: '#ffffff',
      buttonPrimary: '#10B981',
      buttonText: '#ffffff',
      titleText: '#1a1a2e',
      bodyText: '#333333',
      secondaryText: '#999999',
      borderColor: '#eeeeee',
      shadow: 'rgba(16,185,129,0.2)'
    }
  },
  'sunset_orange': {
    name: '蜜橙',
    desc: '热情活力橙',
    colors: {
      primary: '#F97316',
      primaryLight: '#FB923C',
      pageBg: '#fff7ed',
      cardBg: '#ffffff',
      headerBg: 'linear-gradient(135deg, #EA580C, #FB923C)',
      headerText: '#ffffff',
      tabbarActive: '#F97316',
      tabbarInactive: '#999999',
      tabbarBg: '#ffffff',
      priceColor: '#dc2626',
      tagColor: '#dc2626',
      tagText: '#ffffff',
      buttonPrimary: '#F97316',
      buttonText: '#ffffff',
      titleText: '#1a1a2e',
      bodyText: '#333333',
      secondaryText: '#999999',
      borderColor: '#eeeeee',
      shadow: 'rgba(249,115,22,0.2)'
    }
  },
  'midnight_dark': {
    name: '暗夜',
    desc: '深邃暗色模式',
    colors: {
      primary: '#6366F1',
      primaryLight: '#818CF8',
      pageBg: '#0f0f23',
      cardBg: '#1a1a2e',
      headerBg: 'linear-gradient(135deg, #1a1a2e, #16213e)',
      headerText: '#ffffff',
      tabbarActive: '#818CF8',
      tabbarInactive: '#666666',
      tabbarBg: '#1a1a2e',
      priceColor: '#f87171',
      tagColor: '#f87171',
      tagText: '#1a1a2e',
      buttonPrimary: '#6366F1',
      buttonText: '#ffffff',
      titleText: '#e2e8f0',
      bodyText: '#cbd5e1',
      secondaryText: '#64748b',
      borderColor: '#2d2d44',
      shadow: 'rgba(99,102,241,0.3)'
    }
  }
};

// ====== 管理后台 API ======

// 获取所有预设主题
router.get('/presets', authAdmin, (req, res) => {
  const list = Object.entries(PRESET_THEMES).map(([key, t]) => ({
    id: key, name: t.name, desc: t.desc, colors: t.colors
  }));
  res.json(success(list));
});

// 获取当前生效主题
router.get('/current', (req, res) => {
  const cfg = get("SELECT value FROM system_config WHERE key='theme_config'");
  if (cfg) {
    try {
      const data = JSON.parse(cfg.value);
      return res.json(success(data));
    } catch {}
  }
  // 默认冰蓝
  res.json(success({ themeId: 'icy_blue', name: '冰蓝', colors: PRESET_THEMES.icy_blue.colors }));
});

// 保存主题
router.put('/save', authAdmin, (req, res) => {
  const { themeId, name, colors } = req.body;
  if (!themeId || !colors) return res.json(fail('参数不完整'));
  
  const value = JSON.stringify({ themeId, name: name || PRESET_THEMES[themeId]?.name || name, colors });
  const exist = get("SELECT id FROM system_config WHERE key='theme_config'");
  
  if (exist) {
    run("UPDATE system_config SET value=?, updated_at=datetime('now','localtime') WHERE key='theme_config'", [value]);
  } else {
    run("INSERT INTO system_config (key, group_name, value, type, description) VALUES ('theme_config','theme',?,'json','移动端主题配置')", [value]);
  }
  
  res.json(success(null, '主题已保存'));
});

// 自定义保存（非预设，完全自定义配置）
router.put('/custom', authAdmin, (req, res) => {
  const { name, colors } = req.body;
  if (!colors) return res.json(fail('颜色配置不能为空'));
  
  const value = JSON.stringify({ themeId: 'custom', name: name || '自定义', colors, isCustom: true });
  const exist = get("SELECT id FROM system_config WHERE key='theme_config'");
  
  if (exist) {
    run("UPDATE system_config SET value=?, updated_at=datetime('now','localtime') WHERE key='theme_config'", [value]);
  } else {
    run("INSERT INTO system_config (key, group_name, value, type, description) VALUES ('theme_config','theme',?,'json','移动端主题配置')", [value]);
  }
  
  res.json(success(null, '自定义主题已保存'));
});

// 获取主题CSS变量（移动端前端调用）
router.get('/css-vars', (req, res) => {
  const cfg = get("SELECT value FROM system_config WHERE key='theme_config'");
  let colors = PRESET_THEMES.icy_blue.colors;
  let name = '冰蓝';
  
  if (cfg) {
    try {
      const data = JSON.parse(cfg.value);
      if (data.colors) colors = data.colors;
      if (data.name) name = data.name;
    } catch {}
  }
  
  // 构建CSS变量字符串
  // 🔒 防存储型 CSS 注入：转义/剥离危险字符，仅允许样式安全的值
  const safeCssVal = (v) => String(v == null ? '' : v).replace(/[{};<>\n\r]/g, '').slice(0, 64);
  let css = ':root {\n';
  for (const [key, val] of Object.entries(colors)) {
    const cssVar = '--theme-' + key.replace(/([A-Z])/g, '-$1').toLowerCase();
    css += `  ${cssVar}: ${safeCssVal(val)};\n`;
  }
  // 生成primary颜色的RGB值（用于rgba使用）
  if (colors.primary) {
    const hex = colors.primary.replace('#', '');
    if (hex.length === 6 && /^[0-9a-fA-F]{6}$/.test(hex)) {
      const r = parseInt(hex.slice(0, 2), 16);
      const g = parseInt(hex.slice(2, 4), 16);
      const b = parseInt(hex.slice(4, 6), 16);
      css += `  --theme-primary-rgb: ${r},${g},${b};\n`;
    }
  }
  css += '}';
  
  res.set('Content-Type', 'text/css');
  res.set('Cache-Control', 'public, max-age=3600');
  res.send(css);
});

// 获取主题JSON（移动端前端调用）
router.get('/json', (req, res) => {
  const cfg = get("SELECT value FROM system_config WHERE key='theme_config'");
  let themeData = { themeId: 'icy_blue', name: '冰蓝', colors: PRESET_THEMES.icy_blue.colors };
  
  if (cfg) {
    try {
      const data = JSON.parse(cfg.value);
      if (data.colors) themeData = data;
    } catch {}
  }
  
  res.json(success(themeData));
});

// ====== 我的主题管理 API ======

// 获取所有主题（预设 + 自定义）
router.get('/my-themes', authAdmin, (req, res) => {
  // 预设主题
  const presets = Object.entries(PRESET_THEMES).map(([key, t]) => ({
    id: key,
    type: 'preset',
    name: t.name,
    desc: t.desc,
    colors: t.colors,
    isActive: false
  }));
  
  // 自定义主题
  const customs = all('SELECT * FROM theme_customs ORDER BY created_at DESC').map(c => ({
    id: 'custom_' + c.id,
    dbId: c.id,
    type: 'custom',
    name: c.name,
    desc: '自定义主题',
    colors: JSON.parse(c.colors || '{}'),
    isActive: c.is_active === 1
  }));
  
  // 获取当前激活的主题
  const cfg = get("SELECT value FROM system_config WHERE key='theme_config'");
  let activeThemeId = 'icy_blue';
  if (cfg) {
    try {
      const data = JSON.parse(cfg.value);
      if (data.themeId) activeThemeId = data.themeId;
    } catch {}
  }
  
  // 标记激活状态
  presets.forEach(p => { if (p.id === activeThemeId) p.isActive = true; });
  customs.forEach(c => { if ('custom_' + c.dbId === activeThemeId) c.isActive = true; });
  
  res.json(success({ presets, customs, activeThemeId }));
});

// 保存新的自定义主题
router.post('/custom', authAdmin, (req, res) => {
  const { name, colors } = req.body;
  if (!colors) return res.json(fail('颜色配置不能为空'));
  
  const themeName = name || '自定义主题';
  const colorsJson = JSON.stringify(colors);
  
  const result = run(
    'INSERT INTO theme_customs (name, colors, is_active) VALUES (?, ?, 0)',
    [themeName, colorsJson]
  );
  
  res.json(success({ id: result.lastInsertRowid, name: themeName }, '自定义主题已保存'));
});

// 删除自定义主题
router.delete('/custom/:id', authAdmin, (req, res) => {
  const id = parseInt(req.params.id);
  if (!id) return res.json(fail('无效的主题ID'));
  
  // 检查是否是当前激活的主题
  const theme = get('SELECT * FROM theme_customs WHERE id = ?', [id]);
  if (!theme) return res.json(fail('主题不存在'));
  
  const cfg = get("SELECT value FROM system_config WHERE key='theme_config'");
  if (cfg) {
    try {
      const data = JSON.parse(cfg.value);
      if (data.themeId === 'custom_' + id) {
        return res.json(fail('不能删除当前正在使用的主题'));
      }
    } catch {}
  }
  
  run('DELETE FROM theme_customs WHERE id = ?', [id]);
  res.json(success(null, '主题已删除'));
});

// 应用主题（设为当前激活）
router.put('/apply', authAdmin, (req, res) => {
  const { themeId } = req.body;
  if (!themeId) return res.json(fail('主题ID不能为空'));
  
  let themeData;
  
  // 判断是预设还是自定义
  if (PRESET_THEMES[themeId]) {
    // 预设主题
    themeData = {
      themeId,
      name: PRESET_THEMES[themeId].name,
      colors: PRESET_THEMES[themeId].colors
    };
    // 取消所有自定义主题的激活状态
    run('UPDATE theme_customs SET is_active = 0');
  } else if (themeId.startsWith('custom_')) {
    // 自定义主题
    const dbId = parseInt(themeId.replace('custom_', ''));
    const custom = get('SELECT * FROM theme_customs WHERE id = ?', [dbId]);
    if (!custom) return res.json(fail('自定义主题不存在'));
    
    themeData = {
      themeId,
      name: custom.name,
      colors: JSON.parse(custom.colors),
      isCustom: true
    };
    // 激活该主题，取消其他
    run('UPDATE theme_customs SET is_active = 0');
    run('UPDATE theme_customs SET is_active = 1 WHERE id = ?', [dbId]);
  } else {
    return res.json(fail('无效的主题ID'));
  }
  
  // 保存到系统配置
  const value = JSON.stringify(themeData);
  const exist = get("SELECT id FROM system_config WHERE key='theme_config'");
  
  if (exist) {
    run("UPDATE system_config SET value=?, updated_at=datetime('now','localtime') WHERE key='theme_config'", [value]);
  } else {
    run("INSERT INTO system_config (key, group_name, value, type, description) VALUES ('theme_config','theme',?,'json','移动端主题配置')", [value]);
  }
  
  res.json(success(themeData, '主题已应用'));
});

// ====== 主题-页面映射 API ======

// 获取所有页面的主题映射
router.get('/page-map', authAdmin, (req, res) => {
  const list = all('SELECT * FROM theme_page_map ORDER BY page_key');
  // 获取全局主题ID
  const cfg = get("SELECT value FROM system_config WHERE key='theme_config'");
  let globalThemeId = 'icy_blue';
  if (cfg) {
    try {
      const data = JSON.parse(cfg.value);
      if (data.themeId) globalThemeId = data.themeId;
    } catch {}
  }
  res.json(success({ list, globalThemeId }));
});

// 设置页面主题映射
router.put('/page-map', authAdmin, (req, res) => {
  const { pageKey, themeId } = req.body;
  if (!pageKey || !themeId) return res.json(fail('参数不完整'));
  
  const exist = get('SELECT page_key FROM theme_page_map WHERE page_key = ?', [pageKey]);
  if (exist) {
    run("UPDATE theme_page_map SET theme_id=?, updated_at=datetime('now','localtime') WHERE page_key=?", [themeId, pageKey]);
  } else {
    run('INSERT INTO theme_page_map (page_key, theme_id) VALUES (?, ?)', [pageKey, themeId]);
  }
  res.json(success(null, '已保存'));
});

// 获取移动端页面主题（公开接口，移动端调用）
router.get('/page-theme/:pageKey', (req, res) => {
  const pageKey = req.params.pageKey;
  
  // 查询该页面的主题映射
  const map = get('SELECT theme_id FROM theme_page_map WHERE page_key = ?', [pageKey]);
  let themeId = map?.theme_id || 'global';
  
  // 如果是global，返回全局主题
  if (themeId === 'global') {
    const cfg = get("SELECT value FROM system_config WHERE key='theme_config'");
    let themeData = { themeId: 'icy_blue', name: '冰蓝', colors: PRESET_THEMES.icy_blue.colors };
    if (cfg) {
      try {
        const data = JSON.parse(cfg.value);
        if (data.colors) themeData = data;
      } catch {}
    }
    return res.json(success(themeData));
  }
  
  // 否则返回指定主题
  let themeData;
  if (PRESET_THEMES[themeId]) {
    themeData = { themeId, name: PRESET_THEMES[themeId].name, colors: PRESET_THEMES[themeId].colors };
  } else if (themeId.startsWith('custom_')) {
    const dbId = parseInt(themeId.replace('custom_', ''));
    const custom = get('SELECT * FROM theme_customs WHERE id = ?', [dbId]);
    if (custom) {
      themeData = { themeId, name: custom.name, colors: JSON.parse(custom.colors) };
    }
  }
  
  if (!themeData) {
    // 回退到全局主题
    const cfg = get("SELECT value FROM system_config WHERE key='theme_config'");
    themeData = { themeId: 'icy_blue', name: '冰蓝', colors: PRESET_THEMES.icy_blue.colors };
    if (cfg) {
      try {
        const data = JSON.parse(cfg.value);
        if (data.colors) themeData = data;
      } catch {}
    }
  }
  
  res.json(success(themeData));
});

module.exports = router;
module.exports.PRESET_THEMES = PRESET_THEMES;