/**
 * 页面装修可视化 — 管理端接口
 * 省胜优铺 · v1.4.3
 * 与现有 theme.js（配色主题系统）职责分离：
 *   - theme.js           配色切换（CRMEB 主题管理）
 *   - page-decor.js      页面组件布局（拖拽装修）
 * 表：store_page_layout（每页一份全局布局）+ store_page_component（组件单一数据源）
 *
 * 前缀：/api/admin/page-decor/*
 */
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 { _cacheClear } = require('./page-layout');

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 safeJson(s) { try { return JSON.parse(s || '{}'); } catch (e) { return {}; } }

// 确保 4 页 layout 存在
function ensureLayouts() {
  for (const k of PAGE_KEYS) {
    if (!get('SELECT id FROM store_page_layout WHERE page_key=?', [k])) {
      run('INSERT INTO store_page_layout(page_key, title) VALUES(?,?)', [k, PAGE_LABELS[k] || k]);
    }
  }
}

// ====== 页面布局 CRUD ======
// 4 页布局列表
router.get('/layouts', authAdmin, (req, res) => {
  ensureLayouts();
  const list = all('SELECT id, page_key, title, is_public, updated_at FROM store_page_layout ORDER BY CASE page_key WHEN \'home\' THEN 0 WHEN \'category\' THEN 1 WHEN \'cart\' THEN 2 ELSE 3 END');
  return res.json(success(list));
});

// 某页完整装修结构（组件树）
router.get('/layout/:pageKey', authAdmin, (req, res) => {
  const { pageKey } = req.params;
  if (!PAGE_KEYS.includes(pageKey)) return res.json(fail('无效页面', 400));
  ensureLayouts();
  const layout = get('SELECT * FROM store_page_layout WHERE page_key=?', [pageKey]);
  const comps = all('SELECT * FROM store_page_component WHERE layout_id=? ORDER BY sort ASC, id ASC', [layout.id])
    .map((c) => ({ ...c, config: safeJson(c.config) }));
  return res.json(success({ id: layout.id, page_key: pageKey, title: layout.title, is_public: layout.is_public, components: comps }));
});

// 保存整页组件树（富编辑整体替换）
router.put('/layout/:pageKey/save', authAdmin, demoSafeGuard, (req, res) => {
  const { pageKey } = req.params;
  if (!PAGE_KEYS.includes(pageKey)) return res.json(fail('无效页面', 400));
  const { components, is_public } = req.body || {};
  if (!Array.isArray(components)) return res.json(fail('components 必须是数组', 400));
  ensureLayouts();
  const layout = get('SELECT id FROM store_page_layout WHERE page_key=?', [pageKey]);
  transaction(() => {
    run('DELETE FROM store_page_component WHERE layout_id=?', [layout.id]);
    components.forEach((c, i) => {
      if (!COMP_TYPES.includes(c.type)) return;
      const cfg = (c.config && typeof c.config === 'object') ? JSON.stringify(c.config) : '{}';
      run('INSERT INTO store_page_component(layout_id, type, comp_key, sort, status, config) VALUES(?,?,?,?,?,?)',
        [layout.id, c.type, c.comp_key || ('c_' + Date.now() + '_' + i), i, c.status === 0 ? 0 : 1, cfg]);
    });
    run('UPDATE store_page_layout SET is_public=?, title=?, updated_at=datetime(\'now\',\'localtime\') WHERE id=?',
      [is_public === 0 ? 0 : 1, (req.body && req.body.title) || PAGE_LABELS[pageKey], layout.id]);
  });
  try { _cacheClear && _cacheClear(); } catch (e) {}
  return res.json(success(null, '页面已保存'));
});

// 恢复默认模板（清空组件，前端回退默认渲染）
router.post('/layout/:pageKey/reset', authAdmin, demoSafeGuard, (req, res) => {
  const { pageKey } = req.params;
  if (!PAGE_KEYS.includes(pageKey)) return res.json(fail('无效页面', 400));
  const layout = get('SELECT id FROM store_page_layout WHERE page_key=?', [pageKey]);
  if (layout) {
    transaction(() => {
      run('DELETE FROM store_page_component WHERE layout_id=?', [layout.id]);
      run('UPDATE store_page_layout SET is_public=1, updated_at=datetime(\'now\',\'localtime\') WHERE id=?', [layout.id]);
    });
    try { _cacheClear && _cacheClear(); } catch (e) {}
  }
  return res.json(success(null, '已恢复默认模板'));
});

// 组件类型元数据（管理端富编辑表单驱动）
router.get('/component-meta', authAdmin, (req, res) => {
  const meta = {
    banner: {
      label: '轮播图', icon: '🖼️',
      fields: [
        { name: 'images', label: '轮播图（每图可配跳转链接）', type: 'image-list' },
        { name: 'height', label: '高度(px)', type: 'number', default: 150 },
        { name: 'interval', label: '自动轮播间隔(ms)', type: 'number', default: 4000 },
        { name: 'radius', label: '圆角(px)', type: 'number', default: 8 }
      ]
    },
    grid: {
      label: '金刚区宫格', icon: '🔲',
      fields: [
        { name: 'columns', label: '列数', type: 'select', options: [3, 4, 5], default: 4 },
        { name: 'items', label: '宫格项（图标/文字/链接）', type: 'grid-list' }
      ]
    },
    'goods-list': {
      label: '商品栏', icon: '🛍️',
      fields: [
        { name: 'title', label: '标题', type: 'text', default: '为你推荐' },
        { name: 'source', label: '商品来源', type: 'select', options: [{ v: 'cate', l: '分类商品' }, { v: 'manual', l: '手动选品' }, { v: 'hot', l: '热销商品' }, { v: 'new', l: '最新商品' }], default: 'hot' },
        { name: 'category_id', label: '分类ID（来源=分类商品）', type: 'number' },
        { name: 'product_ids', label: '商品ID（来源=手动选品，逗号分隔）', type: 'text' },
        { name: 'limit', label: '展示数量', type: 'number', default: 6 },
        { name: 'layout', label: '布局', type: 'select', options: [{ v: 'grid', l: '双列网格' }, { v: 'list', l: '单列列表' }], default: 'grid' }
      ]
    },
    title: {
      label: '标题栏', icon: '📌',
      fields: [
        { name: 'text', label: '标题文字', type: 'text', default: '热门推荐' },
        { name: 'sub', label: '副标题', type: 'text' },
        { name: 'align', label: '对齐', type: 'select', options: [{ v: 'left', l: '左对齐' }, { v: 'center', l: '居中' }], default: 'left' },
        { name: 'link', label: '更多链接', type: 'text' }
      ]
    },
    notice: {
      label: '公告', icon: '📢',
      fields: [
        { name: 'text', label: '公告内容', type: 'textarea', default: '欢迎光临本店！' },
        { name: 'mode', label: '模式', type: 'select', options: [{ v: 'scroll', l: '跑马灯' }, { v: 'static', l: '静态' }], default: 'scroll' }
      ]
    },
    image: {
      label: '单图', icon: '🖼️',
      fields: [
        { name: 'image', label: '图片', type: 'image' },
        { name: 'link', label: '跳转链接', type: 'text' }
      ]
    },
    video: {
      label: '视频', icon: '🎬',
      fields: [
        { name: 'src', label: '视频URL', type: 'text' },
        { name: 'cover', label: '封面图', type: 'image' },
        { name: 'autoplay', label: '自动播放', type: 'switch', default: false }
      ]
    },
    seckill: {
      label: '秒杀专区', icon: '⚡',
      fields: [
        { name: 'title', label: '标题', type: 'text', default: '限时秒杀' },
        { name: 'link', label: '链接', type: 'text' }
      ]
    },
    coupon: {
      label: '领券中心', icon: '🎟️',
      fields: [
        { name: 'title', label: '标题', type: 'text', default: '领券中心' },
        { name: 'link', label: '链接', type: 'text' }
      ]
    },
    'group-buy': {
      label: '拼团专区', icon: '🤝',
      fields: [
        { name: 'title', label: '标题', type: 'text', default: '好友拼团' },
        { name: 'link', label: '链接', type: 'text' }
      ]
    },
    bargain: {
      label: '砍价专区', icon: '🔪',
      fields: [
        { name: 'title', label: '标题', type: 'text', default: '砍价惠购' },
        { name: 'link', label: '链接', type: 'text' }
      ]
    },
    article: {
      label: '文章推荐', icon: '📰',
      fields: [
        { name: 'title', label: '标题', type: 'text', default: '好文推荐' },
        { name: 'category_id', label: '文章分类ID', type: 'number' },
        { name: 'limit', label: '数量', type: 'number', default: 3 }
      ]
    }
  };
  return res.json(success(meta));
});

module.exports = router;
