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

// ========== 功能门控：页面装修仅在完整版可用 ==========
// 读公开(用户商城首页渲染)、写需管理员(防匿名篡改装修/草稿)
router.use((req, res, next) => {
  if (!isFeatureEnabled('page_designer')) {
    return res.json({ code: 403, message: '当前版本不支持页面装修功能', data: null });
  }
  if (req.method !== 'GET' && req.method !== 'HEAD') {
    return authAdmin(req, res, next);
  }
  next();
});

// ========== 模板 CRUD（新格式：content JSON blob） ==========

// 模板列表
router.get('/templates', (req, res) => {
  const list = all('SELECT * FROM design_templates ORDER BY is_default DESC, updated_at DESC');
  res.json(success(list));
});

// ====== 三端公开渲染：返回默认模板的 components（free 版被门控 403 → 前端降级默认）======
// GET /design/render/:terminal?page=home
router.get('/render/:terminal', (req, res) => {
  const terminal = ['h5','pc','miniapp'].includes(req.params.terminal) ? req.params.terminal : 'h5';
  const page = ['home','category','cart','mine'].includes(req.query.page) ? req.query.page : 'home';
  // v1.4.3 四页装修：按 terminal + page 定位模板；无则回退该终端 home，再回退 h5 home
  let tpl = get('SELECT * FROM design_templates WHERE terminal=? AND page=? AND is_default=1 AND status=1', [terminal, page])
        || get('SELECT * FROM design_templates WHERE terminal=? AND page=? AND is_default=1 AND status=1', [terminal, 'home'])
        || get('SELECT * FROM design_templates WHERE terminal=? AND page=? AND is_default=1 AND status=1', ['h5', page])
        || get('SELECT * FROM design_templates WHERE terminal=? AND page=? AND is_default=1 AND status=1', ['h5', 'home']);
  if (!tpl) {
    // 无默认模板：返回空(渲染端用内置默认)
    return res.json(success({ terminal, page, enabled: false, components: [] }));
  }
  let components = [];
  if (tpl.content && tpl.content.trim()) {
    try {
      const parsed = JSON.parse(tpl.content);
      components = Array.isArray(parsed) ? parsed : (parsed.components || []);
    } catch (e) {}
  }
  res.json(success({ terminal, page, enabled: components.length > 0, template_id: tpl.id, components }));
});

// 获取单个模板
router.get('/templates/:id', (req, res) => {
  const { id } = req.params;
  const template = get('SELECT * FROM design_templates WHERE id=?', [id]);
  if (!template) return res.json(fail('模板不存在'));

  // 自动解析 content 为 components
  let components = [];
  if (template.content && template.content.trim()) {
    try {
      const parsed = JSON.parse(template.content);
      components = Array.isArray(parsed) ? parsed : (parsed.components || []);
    } catch (e) {}
  }

  res.json(success({ ...template, components }));
});

// 创建模板
router.post('/templates', (req, res) => {
  const { name, terminal = 'h5', page = 'home', content, is_default = 0 } = req.body;
  if (!name) return res.json(fail('模板名称不能为空'));

  const contentStr = content ? (typeof content === 'string' ? content : JSON.stringify(content)) : '{"components":[]}';
  const r = run(
    "INSERT INTO design_templates(name,terminal,page,content,is_default,status,created_at,updated_at) VALUES(?,?,?,?,?,1,datetime('now','localtime'),datetime('now','localtime'))",
    [name, terminal, page, contentStr, is_default]
  );

  const created = get('SELECT * FROM design_templates WHERE id=?', [r.lastInsertRowid]);
  res.json(success(created, '模板创建成功'));
});

// 更新模板
router.put('/templates/:id', (req, res) => {
  const { id } = req.params;
  const { name, terminal, page, content, is_default } = req.body;

  const template = get('SELECT * FROM design_templates WHERE id=?', [id]);
  if (!template) return res.json(fail('模板不存在'));

  const updates = [];
  const params = [];

  if (name !== undefined) { updates.push('name=?'); params.push(name); }
  if (terminal !== undefined) { updates.push('terminal=?'); params.push(terminal); }
  if (page !== undefined) { updates.push('page=?'); params.push(page); }
  if (content !== undefined) {
    updates.push('content=?');
    params.push(typeof content === 'string' ? content : JSON.stringify(content));
  }
  if (is_default !== undefined) { updates.push('is_default=?'); params.push(is_default); }

  if (updates.length === 0) return res.json(fail('没有需要更新的字段'));

  updates.push("updated_at=datetime('now','localtime')");
  params.push(id);
  run(`UPDATE design_templates SET ${updates.join(',')} WHERE id=?`, params);

  const updated = get('SELECT * FROM design_templates WHERE id=?', [id]);
  res.json(success(updated, '模板更新成功'));
});

// 删除模板
router.delete('/templates/:id', (req, res) => {
  const { id } = req.params;
  const template = get('SELECT * FROM design_templates WHERE id=?', [id]);
  if (!template) return res.json(fail('模板不存在'));

  run('DELETE FROM design_components WHERE template_id=?', [id]);
  run('DELETE FROM design_templates WHERE id=?', [id]);
  res.json(success(null, '模板已删除'));
});

// 设为默认
router.post('/templates/:id/set-default', (req, res) => {
  const { id } = req.params;
  const template = get('SELECT * FROM design_templates WHERE id=?', [id]);
  if (!template) return res.json(fail('模板不存在'));

  // 清除该终端+页面其他默认模板（四页各自独立默认）
  run('UPDATE design_templates SET is_default=0 WHERE terminal=? AND page=?', [template.terminal, template.page || 'home']);
  // 设置当前为默认
  run('UPDATE design_templates SET is_default=1,updated_at=datetime(\'now\',\'localtime\') WHERE id=?', [id]);

  res.json(success(null, '已设为默认模板'));
});

// ========== 旧版草稿/文件系统（保留兼容） ==========

// 获取草稿
router.get('/draft', (req, res) => {
  const draftFile = path.join(__dirname, '..', 'public', 'design', 'draft_1.json');
  if (fs.existsSync(draftFile)) {
    return res.json({ code: 0, data: JSON.parse(fs.readFileSync(draftFile, 'utf8')) });
  }
  res.json({ code: 0, data: { global: {}, components: [] } });
});

// 保存草稿
router.post('/save', (req, res) => {
  const { page_id = 1, config } = req.body;
  // 🔒 防路径穿越：page_id 仅允许数字
  if (!/^\d+$/.test(String(page_id))) return res.json({ code: 1, message: '非法的页面ID' });
  const dir = path.join(__dirname, '..', 'public', 'design');
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  fs.writeFileSync(path.join(dir, `draft_${page_id}.json`), JSON.stringify(config, null, 2));

  // 🔧 v1.4.3 打通：同时把装修 components 同步写入 design_templates 表（按 terminal+page），三端 render 读表即得装修
  try {
    const components = (config && Array.isArray(config.components)) ? config.components : [];
    // 规范化组件结构（编辑器用 props，渲染端统一认 props/type)
    const normComponents = components.map((c) => ({
      type: c.type || '',
      key: c.uid || c.key || ('c_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8)),
      props: (c.props || c.config || {})
    })).filter((c) => c.type);
    const terminal = ['h5','pc','miniapp'].includes(config && config.terminal) ? config.terminal : 'h5';
    const page = ['home','category','cart','mine'].includes(config && config.page) ? config.page : 'home';
    const contentStr = JSON.stringify({ terminal, page, components: normComponents });

    // 更新该终端+页面模板；无则创建
    let tpl = get('SELECT id FROM design_templates WHERE terminal=? AND page=? AND is_default=1', [terminal, page])
          || get('SELECT id FROM design_templates WHERE terminal=? AND page=?', [terminal, page]) || null;
    if (tpl) {
      run("UPDATE design_templates SET content=?, updated_at=datetime('now','localtime') WHERE id=?", [contentStr, tpl.id]);
      // 同步 design_components 表
      run('DELETE FROM design_components WHERE template_id=?', [tpl.id]);
      normComponents.forEach((c, i) => {
        run('INSERT INTO design_components(template_id,comp_type,sort,config,created_at) VALUES(?,?,?,?,datetime(\'now\',\'localtime\'))',
          [tpl.id, c.type, i, JSON.stringify(c.props)]);
      });
    } else {
      const pageName = { home:'首页', category:'分类页', cart:'购物车页', mine:'我的页' }[page] || '首页';
      const r = run("INSERT INTO design_templates(name,terminal,page,content,is_default,status,created_at,updated_at) VALUES(?,?,?,?,1,1,datetime('now','localtime'),datetime('now','localtime'))",
        [pageName, terminal, page, contentStr]);
      normComponents.forEach((c, i) => {
        run('INSERT INTO design_components(template_id,comp_type,sort,config,created_at) VALUES(?,?,?,?,datetime(\'now\',\'localtime\'))',
          [r.lastInsertRowid, c.type, i, JSON.stringify(c.props)]);
      });
    }
  } catch (e) {
    // 同步失败不影响文件保存（草稿仍可用）
  }

  res.json({ code: 0, message: '草稿已保存' });
});

// 发布
router.post('/publish', (req, res) => {
  const { page_id = 1, remark = '日常更新' } = req.body;
  if (!/^\d+$/.test(String(page_id))) return res.json({ code: 1, message: '非法的页面ID' });
  const draftFile = path.join(__dirname, '..', 'public', 'design', `draft_${page_id}.json`);
  if (!fs.existsSync(draftFile)) return res.json({ code: 1, message: '未找到草稿' });
  const version = new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14);
  const publishFile = path.join(__dirname, '..', 'public', 'design', `page_${page_id}_${version}.json`);
  fs.copyFileSync(draftFile, publishFile);
  res.json({ code: 0, data: { version, url: `/design/page_${page_id}_${version}.json` } });
});

// 获取版本历史
router.get('/versions', (req, res) => {
  const dir = path.join(__dirname, '..', 'public', 'design');
  if (!fs.existsSync(dir)) return res.json({ code: 0, data: [] });
  const files = fs.readdirSync(dir).filter(f => f.startsWith('page_')).sort().reverse().slice(0, 20);
  const versions = files.map(f => {
    const stat = fs.statSync(path.join(dir, f));
    return { version: f.replace(/\.json$/, '').split('_').pop(), file_path: '/design/' + f, create_time: stat.mtime };
  });
  res.json({ code: 0, data: versions });
});

// ========== 组件CRUD ==========

// 获取组件列表（按sort排序）
router.get('/templates/:id/components', (req, res) => {
  const { id } = req.params;
  const template = get('SELECT * FROM design_templates WHERE id=?', [id]);
  if (!template) return res.json(fail('模板不存在'));

  const components = all('SELECT * FROM design_components WHERE template_id=? ORDER BY sort ASC', [id])
    .map(c => ({ ...c, config: JSON.parse(c.config || '{}') }));

  res.json(success(components));
});

// 添加组件
router.post('/templates/:id/components', (req, res) => {
  const { id } = req.params;
  const { comp_type, config } = req.body;

  const template = get('SELECT * FROM design_templates WHERE id=?', [id]);
  if (!template) return res.json(fail('模板不存在'));

  if (!comp_type) return res.json(fail('组件类型不能为空'));

  // 获取当前最大排序值
  const maxSort = get('SELECT COALESCE(MAX(sort),-1) as ms FROM design_components WHERE template_id=?', [id]);
  const nextSort = (maxSort ? maxSort.ms : -1) + 1;

  const configStr = config ? JSON.stringify(config) : '{}';
  const r = run(
    "INSERT INTO design_components(template_id,comp_type,sort,config,created_at) VALUES(?,?,?,?,datetime('now','localtime'))",
    [id, comp_type, nextSort, configStr]
  );

  const created = get('SELECT * FROM design_components WHERE id=?', [r.lastInsertRowid]);
  if (created) created.config = JSON.parse(created.config || '{}');

  res.json(success(created, '组件添加成功'));
});

// 批量排序（必须先于 :cid 路由注册，避免冲突）
router.put('/templates/:id/components/sort', (req, res) => {
  const { id } = req.params;
  const { orders } = req.body;

  if (!orders || !Array.isArray(orders)) return res.json(fail('排序数据无效'));

  const template = get('SELECT * FROM design_templates WHERE id=?', [id]);
  if (!template) return res.json(fail('模板不存在'));

  for (const item of orders) {
    if (item.id !== undefined && item.sort !== undefined) {
      run('UPDATE design_components SET sort=? WHERE id=? AND template_id=?', [item.sort, item.id, id]);
    }
  }

  res.json(success(null, '排序更新成功'));
});

// 更新组件配置
router.put('/templates/:id/components/:cid', (req, res) => {
  const { id, cid } = req.params;
  const { comp_type, config, sort } = req.body;

  const component = get('SELECT * FROM design_components WHERE id=? AND template_id=?', [cid, id]);
  if (!component) return res.json(fail('组件不存在'));

  const updates = [];
  const params = [];

  if (comp_type !== undefined) {
    updates.push('comp_type=?');
    params.push(comp_type);
  }
  if (config !== undefined) {
    updates.push('config=?');
    params.push(JSON.stringify(config));
  }
  if (sort !== undefined) {
    updates.push('sort=?');
    params.push(sort);
  }

  if (updates.length === 0) return res.json(fail('没有需要更新的字段'));

  params.push(cid, id);
  run(`UPDATE design_components SET ${updates.join(',')} WHERE id=? AND template_id=?`, params);

  const updated = get('SELECT * FROM design_components WHERE id=?', [cid]);
  if (updated) updated.config = JSON.parse(updated.config || '{}');

  res.json(success(updated, '组件更新成功'));
});

// 删除组件
router.delete('/templates/:id/components/:cid', (req, res) => {
  const { id, cid } = req.params;

  const component = get('SELECT * FROM design_components WHERE id=? AND template_id=?', [cid, id]);
  if (!component) return res.json(fail('组件不存在'));

  run('DELETE FROM design_components WHERE id=? AND template_id=?', [cid, id]);

  res.json(success(null, '组件删除成功'));
});

module.exports = router;
