/**
 * 主题管理（店铺装修可视化）— 管理端接口
 * 省胜优铺 · v1.4.3
 * 数据模型：
 *   store_theme          主题（配色风格 + 多页面布局）
 *   store_theme_page     主题页面（每主题 4 页：home/category/cart/user）
 *   store_theme_page_component  页面组件（单一数据源，后端拼装 JSON）
 * 全局开关：system_config.key='active_theme_id'
 */
const express = require('express');
const router = express.Router();
const { get, run, all, transaction } = require('../utils/db');
const { success, fail } = require('../utils/response');
const { authAdmin } = require('../middleware/auth');
const { demoSafeGuard } = require('./admin-auth');

// 可装修页面清单
const PAGE_KEYS = ['home', 'category', 'cart', 'user'];
const PAGE_LABELS = { home: '首页', category: '分类页', cart: '购物车', user: '我的' };

// 启用组件类型
const COMP_TYPES = [
  'banner', 'grid', 'goods-list', 'title', 'notice',
  'image', 'video', 'seckill', 'coupon', 'group-buy', 'bargain', 'article'
];

function ensurePages(themeId) {
  // 确保主题下 4 个页面都存在（懒创建）
  const exist = all('SELECT page_key FROM store_theme_page WHERE theme_id=?', [themeId])
    .map((r) => r.page_key);
  for (const k of PAGE_KEYS) {
    if (!exist.includes(k)) {
      run('INSERT INTO store_theme_page(theme_id, page_key, title) VALUES(?,?,?)',
        [themeId, k, PAGE_LABELS[k] || k]);
    }
  }
}

function readActiveThemeId() {
  const row = get("SELECT value FROM system_config WHERE key='active_theme_id'");
  return row ? Number(row.value) : 0;
}

// ========== 主题 CRUD ==========
router.get('/theme/list', authAdmin, (req, res) => {
  const list = all('SELECT * FROM store_theme ORDER BY sort ASC, id ASC');
  const activeId = readActiveThemeId();
  const data = list.map((t) => ({ ...t, is_active: t.id === activeId }));
  return res.json(success(data));
});

router.post('/theme', authAdmin, demoSafeGuard, (req, res) => {
  const { name, code, style, cover, sort } = req.body || {};
  if (!name || !code) return res.json(fail('主题名和标识必填', 400));
  if (COMP_TYPES.length && all(`SELECT id FROM store_theme WHERE code=?`, [code]).length) {
    return res.json(fail('主题标识已存在', 400));
  }
  run('INSERT INTO store_theme(name, code, style, cover, sort, is_builtin, status) VALUES(?,?,?,?,?,0,1)',
    [name, code, style || '{}', cover || '', sort || 0]);
  return res.json(success(null, '添加成功'));
});

router.put('/theme/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { name, style, cover, sort, status } = req.body || {};
  run('UPDATE store_theme SET name=?, style=?, cover=?, sort=?, status=?, updated_at=datetime(\'now\',\'localtime\') WHERE id=?',
    [name, style, cover, sort, status, req.params.id]);
  return res.json(success(null, '更新成功'));
});

router.delete('/theme/:id', authAdmin, demoSafeGuard, (req, res) => {
  const id = Number(req.params.id);
  const t = get('SELECT * FROM store_theme WHERE id=?', [id]);
  if (!t) return res.json(fail('主题不存在', 404));
  if (t.is_builtin) return res.json(fail('内置主题不可删除', 400));
  if (readActiveThemeId() === id) return res.json(fail('请先切换其他主题再删除', 400));
  transaction(() => {
    const pages = all('SELECT id FROM store_theme_page WHERE theme_id=?', [id]);
    for (const p of pages) {
      run('DELETE FROM store_theme_page_component WHERE page_id=?', [p.id]);
    }
    run('DELETE FROM store_theme_page WHERE theme_id=?', [id]);
    run('DELETE FROM store_theme WHERE id=?', [id]);
  });
  return res.json(success(null, '删除成功'));
});

// 应用主题
router.post('/theme/apply', authAdmin, demoSafeGuard, (req, res) => {
  const { id } = req.body || {};
  const t = get('SELECT * FROM store_theme WHERE id=?', [id]);
  if (!t) return res.json(fail('主题不存在', 404));
  ensurePages(id);
  run("INSERT INTO system_config(key, value, group_name, type, description) VALUES('active_theme_id', ?, 'base', 'number', '当前生效主题ID') " +
    "ON CONFLICT(key) DO UPDATE SET value=excluded.value", [String(id)]);
  run("UPDATE store_theme SET is_default = CASE WHEN id=? THEN 1 ELSE 0 END WHERE is_default=1 OR id=?", [id, id]);
  run("UPDATE store_theme SET is_default=CASE WHEN id=? THEN 1 ELSE 0 END", [id]);
  return res.json(success(null, '主题已应用'));
});

// ========== 页面 + 组件 ==========
// 读取某主题某页的完整装修结构（含组件树拼装）
router.get('/page/:pageKey', authAdmin, (req, res) => {
  const { pageKey } = req.params;
  if (!PAGE_KEYS.includes(pageKey)) return res.json(fail('无效页面', 400));
  const themeId = Number(req.query.theme_id) || readActiveThemeId() || 1;
  const page = get('SELECT * FROM store_theme_page WHERE theme_id=? AND page_key=?', [themeId, pageKey]);
  if (!page) return res.json(success({ themeId, pageKey, is_public: 1, components: [] }));
  const comps = all('SELECT * FROM store_theme_page_component WHERE page_id=? ORDER BY sort ASC, id ASC', [page.id])
    .map((c) => ({ ...c, config: safeJson(c.config) }));
  return res.json(success({ id: page.id, themeId, pageKey, title: page.title, is_public: page.is_public, components: comps }));
});

// 保存整页组件树（富编辑表单提交整体替换）
router.put('/page/:pageKey/save', authAdmin, demoSafeGuard, (req, res) => {
  const { pageKey } = req.params;
  if (!PAGE_KEYS.includes(pageKey)) return res.json(fail('无效页面', 400));
  const { theme_id, components, is_public } = req.body || {};
  const themeId = Number(theme_id) || readActiveThemeId() || 1;
  if (!Array.isArray(components)) return res.json(fail('components 必须是数组', 400));
  ensurePages(themeId);
  const page = get('SELECT * FROM store_theme_page WHERE theme_id=? AND page_key=?', [themeId, pageKey]);
  if (!page) return res.json(fail('页面不存在', 404));
  transaction(() => {
    run('DELETE FROM store_theme_page_component WHERE page_id=?', [page.id]);
    components.forEach((c, i) => {
      if (!COMP_TYPES.includes(c.type)) return;
      run('INSERT INTO store_theme_page_component(page_id, type, comp_key, sort, status, config) VALUES(?,?,?,?,?,?)',
        [page.id, c.type, c.comp_key || ('c_' + Date.now() + '_' + i), i, c.status === 0 ? 0 : 1, JSON.stringify(c.config || {})]);
    });
    run('UPDATE store_theme_page SET is_public=?, updated_at=datetime(\'now\',\'localtime\') WHERE id=?',
      [is_public === 0 ? 0 : 1, page.id]);
  });
  return res.json(success(null, '页面已保存'));
});

// 组件类型元数据（供管理端富编辑表单渲染表单）
router.get('/component-meta', authAdmin, (req, res) => {
  const meta = {
    banner: { label: '轮播图', fields: [{ name: 'images', label: '轮播图(多图,每图可配链接)', type: 'image-list' }, { name: 'height', label: '高度(px)', type: 'number' }, { name: 'interval', label: '自动轮播间隔(ms)', type: 'number' }] },
    grid: { label: '金刚区宫格', fields: [{ name: 'columns', label: '列数', type: 'select', options: [3, 4, 5] }, { name: 'items', label: '宫格项(label+icon+link)', type: 'grid-list' }] },
    'goods-list': { label: '商品栏', fields: [{ name: 'title', label: '标题', type: 'text' }, { name: 'source', label: '商品来源', type: 'select', options: ['cate', 'manual', 'hot', 'new'] }, { name: 'category_id', label: '分类ID(来源=分类时)', type: 'number' }, { name: 'product_ids', label: '手动选品ID(来源=手动)', type: 'number-list' }, { name: 'limit', label: '展示数量', type: 'number' }, { name: 'layout', label: '布局', type: 'select', options: ['grid', 'list'] }] },
    title: { label: '标题栏', fields: [{ name: 'text', label: '标题文字', type: 'text' }, { name: 'sub', label: '副标题', type: 'text' }, { name: 'style', label: '风格', type: 'select', options: ['left', 'center'] }, { name: 'link', label: '更多链接', type: 'text' }] },
    notice: { label: '公告', fields: [{ name: 'text', label: '公告内容', type: 'textarea' }, { name: 'mode', label: '模式', type: 'select', options: ['scroll', 'static'] }] },
    image: { label: '单图', fields: [{ name: 'image', label: '图片', type: 'image' }, { name: 'link', label: '跳转链接', type: 'text' }] },
    video: { label: '视频', fields: [{ name: 'src', label: '视频URL', type: 'text' }, { name: 'cover', label: '封面图', type: 'image' }, { name: 'autoplay', label: '自动播放', type: 'switch' }] },
    seckill: { label: '秒杀专区', fields: [{ name: 'title', label: '标题', type: 'text' }, { name: 'link', label: '链接', type: 'text' }] },
    coupon: { label: '领券中心', fields: [{ name: 'title', label: '标题', type: 'text' }, { name: 'link', label: '链接', type: 'text' }] },
    'group-buy': { label: '拼团专区', fields: [{ name: 'title', label: '标题', type: 'text' }, { name: 'link', label: '链接', type: 'text' }] },
    bargain: { label: '砍价专区', fields: [{ name: 'title', label: '标题', type: 'text' }, { name: 'link', label: '链接', type: 'text' }] },
    article: { label: '文章推荐', fields: [{ name: 'title', label: '标题', type: 'text' }, { name: 'category_id', label: '文章分类ID', type: 'number' }, { name: 'limit', label: '数量', type: 'number' }] }
  };
  return res.json(success(meta));
});

function safeJson(s) {
  try { return JSON.parse(s || '{}'); } catch (e) { return {}; }
}

module.exports = router;
