const express = require('express');
const router = express.Router();
const { get, run, all, transaction } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authAdmin } = require('../middleware/auth');
const { demoSafeGuard } = require("./admin-auth");
const licenseLib = require('../lib/license');
const crypto = require('crypto');

// ========== 品牌管理 ==========
router.get('/brands', authAdmin, (req, res) => {
  res.json(success(all('SELECT * FROM brands ORDER BY sort ASC, id ASC')));
});
router.post('/brands', authAdmin, demoSafeGuard, (req, res) => {
  const r=run('INSERT INTO brands(name,logo,sort) VALUES(?,?,?)',[req.body.name,req.body.logo||'',req.body.sort||0]);
  res.json(success({id:r.lastInsertRowid},'添加成功'));
});
router.put('/brands/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('UPDATE brands SET name=?,logo=?,sort=?,status=? WHERE id=?',[req.body.name,req.body.logo||'',req.body.sort||0,req.body.status??1,req.params.id]);
  res.json(success(null,'更新成功'));
});
router.delete('/brands/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM brands WHERE id=?',[req.params.id]);
  res.json(success(null,'已删除'));
});

// ========== 支付记录 ==========
router.get('/payment-records', authAdmin, (req, res) => {
  const {page:p=1,pageSize=15}=req.query;
  const pageNum=Math.max(1,+p);const size=Math.min(50,Math.max(1,+pageSize));
  const total=get('SELECT COUNT(*) as c FROM payment_records').c;
  const list=all('SELECT p.*,o.order_no,u.nickname FROM payment_records p LEFT JOIN orders o ON p.order_id=o.id LEFT JOIN users u ON p.user_id=u.id ORDER BY p.id DESC LIMIT ? OFFSET ?',[size,(pageNum-1)*size]);
  res.json(page(list,total,pageNum,size));
});

// ========== 数据统计 ==========
router.get('/stats/dashboard', authAdmin, (req, res) => {
  const {range='7d'}=req.query;
  let days=7; if(range==='30d')days=30; else if(range==='3m')days=90; else if(range==='1y')days=365;
  
  const now = new Date();
  const startDate = new Date(now.getTime()-days*86400000).toISOString().split('T')[0];
  
  // 概览
  const totalOrders=get("SELECT COUNT(*) as c FROM orders").c;
  const totalRevenue=get("SELECT COALESCE(SUM(pay_amount),0) as s FROM orders WHERE status NOT IN ('pending_pay','closed')").s;
  const avgOrderAmount=totalOrders>0?+(totalRevenue/totalOrders).toFixed(2):0;
  const newUsers=get("SELECT COUNT(*) as c FROM users WHERE date(created_at)>=?",[startDate]).c;
  
  // 销售趋势
  const trend=all(`SELECT date(created_at) as d, COUNT(*) as orders, COALESCE(SUM(pay_amount),0) as revenue 
    FROM orders WHERE date(created_at)>=? AND status NOT IN ('pending_pay') GROUP BY d ORDER BY d`,[startDate]);
  
  res.json(success({totalOrders,totalRevenue,avgOrderAmount,newUsers,trend}));
});

router.get('/stats/top-products', authAdmin, (req, res) => {
  const data=all(`SELECT p.id,p.name,p.image,SUM(oi.quantity) as total_qty,SUM(oi.subtotal) as total_sales 
    FROM order_items oi JOIN products p ON oi.product_id=p.id GROUP BY oi.product_id ORDER BY total_sales DESC LIMIT 10`);
  res.json(success(data));
});

router.get('/stats/user-growth', authAdmin, (req, res) => {
  const data=all(`SELECT date(created_at) as d, COUNT(*) as cnt FROM users GROUP BY d ORDER BY d DESC LIMIT 30`);
  res.json(success(data.reverse()));
});

router.get('/stats/order-distribution', authAdmin, (req, res) => {
  const data=all("SELECT status, COUNT(*) as cnt FROM orders GROUP BY status");
  res.json(success(data));
});


// ========== 付费会员管理 ==========
router.get('/membership/members', authAdmin, (req, res) => {
  const {page:p=1,pageSize=15,keyword}=req.query;
  const pageNum=Math.max(1,+p);const size=Math.min(50,Math.max(1,+pageSize));
  let where="WHERE um.status='active'";const params=[];
  if(keyword){where+=' AND (u.nickname LIKE ? OR u.phone LIKE ?)';params.push('%'+keyword+'%','%'+keyword+'%')}
  const total=get("SELECT COUNT(*) as c FROM user_memberships um JOIN users u ON um.user_id=u.id "+where,params).c;
  const list=all("SELECT um.*,u.nickname,u.phone,mp.name as plan_name,mp.type as plan_type FROM user_memberships um LEFT JOIN users u ON um.user_id=u.id LEFT JOIN membership_plans mp ON um.plan_id=mp.id "+where+" ORDER BY um.id DESC LIMIT ? OFFSET ?",[...params,size,(pageNum-1)*size]);
  res.json(page(list,total,pageNum,size));
});
router.get('/membership/renew-logs', authAdmin, (req, res) => {
  const {page:p=1,pageSize=15}=req.query;
  const pageNum=Math.max(1,+p);const size=Math.min(50,Math.max(1,+pageSize));
  const total=get('SELECT COUNT(*) as c FROM membership_renew_logs').c;
  const list=all('SELECT r.*,u.nickname,u.phone,mp.name as plan_name FROM membership_renew_logs r LEFT JOIN users u ON r.user_id=u.id LEFT JOIN membership_plans mp ON r.plan_id=mp.id ORDER BY r.id DESC LIMIT ? OFFSET ?',[size,(pageNum-1)*size]);
  res.json(page(list,total,pageNum,size));
});
router.get('/membership/stats', authAdmin, (req, res) => {
  const total=get("SELECT COUNT(*) as c FROM user_memberships WHERE status='active'").c;
  const active=get("SELECT COUNT(*) as c FROM user_memberships WHERE status='active' AND end_time>datetime('now','localtime')").c;
  const revenue=get('SELECT COALESCE(SUM(amount),0) as s FROM membership_renew_logs').s;
  const breakdown=all("SELECT mp.name,mp.type,COUNT(DISTINCT um.user_id) as members,COALESCE(SUM(r.amount),0) as revenue FROM membership_plans mp LEFT JOIN user_memberships um ON um.plan_id=mp.id AND um.status='active' LEFT JOIN membership_renew_logs r ON r.plan_id=mp.id GROUP BY mp.id ORDER BY mp.sort_order");
  res.json(success({total,active,revenue,breakdown}));
});


// ========== LiteDesign ==========
// ========== 页面装修模板（含content JSON存储） ==========
router.get('/design/templates', authAdmin, (req, res) => {
  try {
    const list = all('SELECT * FROM design_templates ORDER BY id DESC');
    list.forEach(t => { try { t.content = JSON.parse(t.content || '{}'); } catch(e) { t.content = {}; } });
    res.json(success(list));
  } catch(e) { res.json(fail('获取模板列表失败')); }
});

router.get('/design/templates/:id', authAdmin, (req, res) => {
  try {
    const t = get('SELECT * FROM design_templates WHERE id=?', [req.params.id]);
    if (!t) return res.json(fail('模板不存在'));
    try { t.content = JSON.parse(t.content || '{}'); } catch(e) { t.content = {}; }
    res.json(success(t));
  } catch(e) { res.json(fail('获取模板失败')); }
});

router.get('/design/templates/default/current', authAdmin, (req, res) => {
  try {
    const t = get('SELECT * FROM design_templates WHERE is_default=1 AND status=1 LIMIT 1');
    if (!t) return res.json(success(null));
    try { t.content = JSON.parse(t.content || '{}'); } catch(e) { t.content = {}; }
    res.json(success(t));
  } catch(e) { res.json(fail('获取默认模板失败')); }
});

router.post('/design/templates', authAdmin, demoSafeGuard, (req, res) => {
  try {
    const { name, terminal, content } = req.body;
    const contentStr = typeof content === 'string' ? content : JSON.stringify(content || {});
    const r = run('INSERT INTO design_templates(name,terminal,content,created_at,updated_at) VALUES(?,?,?,datetime(\'now\',\'localtime\'),datetime(\'now\',\'localtime\'))',
      [name || '未命名模板', terminal || 'h5', contentStr]);
    res.json(success({ id: r.lastInsertRowid }, '创建成功'));
  } catch(e) { res.json(fail('创建失败: ' + e.message)); }
});

router.put('/design/templates/:id', authAdmin, demoSafeGuard, (req, res) => {
  try {
    const { name, terminal, is_default, status, content } = req.body;
    const contentStr = typeof content === 'string' ? content : JSON.stringify(content || {});
    run('UPDATE design_templates SET name=?,terminal=?,is_default=?,status=?,content=?,updated_at=datetime(\'now\',\'localtime\') WHERE id=?',
      [name, terminal, is_default || 0, status || 1, contentStr, req.params.id]);
    res.json(success(null, '保存成功'));
  } catch(e) { res.json(fail('保存失败: ' + e.message)); }
});

router.delete('/design/templates/:id', authAdmin, demoSafeGuard, (req, res) => {
  try {
    run('DELETE FROM design_templates WHERE id=?', [req.params.id]);
    res.json(success(null, '已删除'));
  } catch(e) { res.json(fail('删除失败')); }
});

router.post('/design/templates/:id/duplicate', authAdmin, demoSafeGuard, (req, res) => {
  try {
    const src = get('SELECT * FROM design_templates WHERE id=?', [req.params.id]);
    if (!src) return res.json(fail('源模板不存在'));
    const r = run('INSERT INTO design_templates(name,terminal,content,created_at,updated_at) VALUES(?,?,?,datetime(\'now\',\'localtime\'),datetime(\'now\',\'localtime\'))',
      [src.name + '(副本)', src.terminal, src.content]);
    res.json(success({ id: r.lastInsertRowid }, '已复制'));
  } catch(e) { res.json(fail('复制失败')); }
});

router.post('/design/templates/:id/publish', authAdmin, demoSafeGuard, (req, res) => {
  try {
    // 取消其他默认
    run('UPDATE design_templates SET is_default=0 WHERE terminal=?', [get('SELECT terminal FROM design_templates WHERE id=?', [req.params.id])?.terminal || 'h5']);
    // 设为默认+已发布
    run('UPDATE design_templates SET status=1, is_default=1 WHERE id=?', [req.params.id]);
    res.json(success(null, '已发布并设为默认'));
  } catch(e) { res.json(fail('发布失败')); }
});

// ========== 素材管理 ==========
router.get('/assets', authAdmin, (req, res) => {
  const list = all('SELECT * FROM theme_assets ORDER BY sort ASC, id DESC');
  return res.json(success(list));
});

router.post('/assets', authAdmin, demoSafeGuard, (req, res) => {
  const { name, url, type } = req.body;
  if (!url) return res.json(fail('图片URL不能为空'));
  run('INSERT INTO theme_assets(name,url,type,sort) VALUES(?,?,?,?)', [name||'', url, type||'image', 0]);
  const id = run('SELECT last_insert_rowid() as id').lastInsertRowid;
  const created = get('SELECT * FROM theme_assets WHERE id=?', [id]);
  return res.json(success(created, '添加成功'));
});

router.delete('/assets/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM theme_assets WHERE id=?', [req.params.id]);
  return res.json(success(null, '已删除'));
});

// ========== 链接管理 ==========
router.get('/links', authAdmin, (req, res) => {
  const list = all('SELECT * FROM theme_links ORDER BY sort ASC, id DESC');
  return res.json(success(list));
});

router.post('/links', authAdmin, demoSafeGuard, (req, res) => {
  const { name, url, icon, group_name } = req.body;
  if (!name || !url) return res.json(fail('名称和链接不能为空'));
  run('INSERT INTO theme_links(name,url,icon,group_name) VALUES(?,?,?,?)', [name, url, icon||'', group_name||'default']);
  const id = run('SELECT last_insert_rowid() as id').lastInsertRowid;
  return res.json(success({id}, '添加成功'));
});

router.put('/links/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { name, url, icon, group_name, sort, status } = req.body;
  run('UPDATE theme_links SET name=?,url=?,icon=?,group_name=?,sort=?,status=? WHERE id=?',
    [name, url, icon||'', group_name||'default', sort||0, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});

router.delete('/links/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM theme_links WHERE id=?', [req.params.id]);
  return res.json(success(null, '已删除'));
});

// 授权管理（挂在 admin 路由下，省去额外配置）

router.get('/license', (req, res) => {
  return res.json(success({
    type: licenseLib.getLicenseType(),
    serverId: licenseLib.getSystemId(),
  }));
});

router.post('/license/activate', (req, res) => {
  try {
    const { key } = req.body;
    if (!key) return res.json(fail('请输入激活码'));
    
    const serverId = licenseLib.getSystemId();
    const parts = key.trim().split('-');
    
    if (parts.length !== 5 || parts[0] !== 'LITEMALL') {
      return res.json(fail('激活码格式不正确'));
    }
    
    const inputHash = parts.slice(1).join('').toUpperCase();
    const SECRET = 'LiteMall_2026_SecureKey_!@#$%^';
    
    const check = (type) => {
      const raw = serverId + '|' + type + '|' + SECRET;
      const hash = crypto.createHash('sha256').update(raw).digest('hex').toUpperCase();
      return hash.substring(0, 16);
    };
    
    let licenseType = null;
    if (inputHash === check('premium')) licenseType = 'premium';
    else if (inputHash === check('lifetime')) licenseType = 'lifetime';
    
    if (!licenseType) {
      return res.json(fail('激活码无效或与当前服务器不匹配'));
    }
    
    run("UPDATE system_config SET value=? WHERE key='license_type'", [licenseType]);
    run("UPDATE system_config SET value=? WHERE key='license_key'", [key.trim()]);
    
    return res.json(success({ type: licenseType }, `激活成功！已解锁${licenseType === 'premium' ? '商用版' : '终身版'}全部功能`));
  } catch (e) {
    return res.json(fail('激活失败: ' + e.message));
  }
});

module.exports = { router };
