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

// 获取页面布局
router.get('/layout', (req, res) => {
  const { device = 'mobile', page: p = 'home' } = req.query;
  const layout = get('SELECT * FROM page_layouts WHERE device=? AND page=? AND status=1 ORDER BY id DESC LIMIT 1', [device, p]);
  if (layout) {
    layout.layout = JSON.parse(layout.layout);
    return res.json(success(layout));
  }
  return res.json(success({ layout: [], name: '默认布局' }));
});

// 保存页面布局
router.post('/layout', authAdmin, (req, res) => {
  const { name, page: p = 'home', device = 'mobile', layout: layoutData } = req.body;
  if (!layoutData) return res.json(fail('布局数据不能为空'));
  
  const existing = get('SELECT id FROM page_layouts WHERE device=? AND page=? ORDER BY id DESC LIMIT 1', [device, p]);
  if (existing) {
    run("UPDATE page_layouts SET name=?,layout=?,updated_at=datetime('now','localtime') WHERE id=?", [name||p, JSON.stringify(layoutData), existing.id]);
  } else {
    run('INSERT INTO page_layouts(name,page,device,layout) VALUES(?,?,?,?)', [name||p, p, device, JSON.stringify(layoutData)]);
  }
  return res.json(success(null, '布局保存成功'));
});

// 获取所有布局
router.get('/layouts', authAdmin, (req, res) => {
  const list = all('SELECT * FROM page_layouts ORDER BY id DESC');
  return res.json(success(list));
});

// 获取某终端当前生效模板的完整组件列表
router.get('/render/:terminal', (req, res) => {
  const { terminal } = req.params;
  const result = renderTemplate(terminal);
  if (!result.template) {
    return res.json(success({ template: null, components: [] }, '未找到对应终端的生效模板'));
  }
  res.json(success(result));
});

module.exports = router;
