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 { isPremium } = require('../lib/limits');
const fs = require('fs');
const path = require('path');

// 辅助：记录操作日志
function logAction(adminId, action, module, targetId, detail, ip) {
  try {
    run('INSERT INTO operation_logs(admin_id,action,module,target_id,detail,ip) VALUES(?,?,?,?,?,?)',
      [adminId, action, module, targetId||null, detail||'', ip||'']);
  } catch(e) {}
}

// ========== 系统配置 ==========
router.get('/config', authAdmin, (req, res) => {
  const list = all('SELECT * FROM system_config ORDER BY group_name, sort');
  const grouped = {};
  list.forEach(c => {
    if (!grouped[c.group_name]) grouped[c.group_name] = [];
    grouped[c.group_name].push(c);
  });
  return res.json(success(grouped));
});

router.put('/config', authAdmin, demoSafeGuard, (req, res) => {
  const { configs } = req.body;
  for (const c of configs) {
    run('UPDATE system_config SET value=? WHERE key=?', [c.value, c.key]);
  }
  return res.json(success(null, '更新成功'));
});

router.put('/config/:key', authAdmin, demoSafeGuard, (req, res) => {
  const { value } = req.body;
  run('UPDATE system_config SET value=? WHERE key=?', [value, req.params.key]);
  return res.json(success(null, '更新成功'));
});

// ========== 小程序配置 ==========

// 获取小程序配置（仅付费版可配置）
router.get('/miniapp/config', authAdmin, (req, res) => {
  if (!isPremium()) {
    return res.json(fail('小程序配置需付费版，升级后可解锁'));
  }
  const configs = all("SELECT * FROM system_config WHERE key LIKE 'miniapp_%'");
  const result = {};
  configs.forEach(c => { result[c.key.replace('miniapp_', '')] = c.value; });
  return res.json(success(result));
});

// 保存小程序配置（仅付费版可配置）
router.put('/miniapp/config', authAdmin, demoSafeGuard, (req, res) => {
  if (!isPremium()) {
    return res.json(fail('小程序配置需付费版，升级后可解锁'));
  }
  const configKeys = ['appid', 'appsecret', 'tmpl_pay', 'tmpl_shipping', 'tmpl_refund'];
  const configBody = req.body;

  for (const key of configKeys) {
    if (configBody[key] !== undefined) {
      run('INSERT OR REPLACE INTO system_config (key, group_name, value, type, description) VALUES (?,?,?,?,?)',
        ['miniapp_' + key, 'miniapp', configBody[key], 'text', '小程序配置: ' + key]);
    }
  }

  logAction(req.userId, 'update_miniapp_config', 'system', null, '更新小程序配置', req.ip);
  return res.json(success(null, '保存成功'));
});

// CMS页面
router.get('/pages', authAdmin, (req, res) => {
  const list = all('SELECT id, title, type, status, created_at FROM pages ORDER BY id ASC');
  return res.json(success(list));
});

router.get('/pages/:id', authAdmin, (req, res) => {
  const page = get('SELECT * FROM pages WHERE id=?', [req.params.id]);
  return res.json(success(page));
});

router.put('/pages/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { title, content } = req.body;
  run("UPDATE pages SET title=?,content=?,updated_at=datetime('now','localtime') WHERE id=?", [title, content, req.params.id]);
  return res.json(success(null, '更新成功'));
});

// 运费模板
router.get('/shipping-templates', authAdmin, (req, res) => {
  const list = all('SELECT * FROM shipping_templates ORDER BY id DESC');
  return res.json(success(list));
});

router.post('/shipping-templates', authAdmin, demoSafeGuard, (req, res) => {
  const { name, type, free_shipping_amount, first_piece, first_fee, extra_piece, extra_fee } = req.body;
  const r = run('INSERT INTO shipping_templates(name,type,free_shipping_amount,first_piece,first_fee,extra_piece,extra_fee) VALUES(?,?,?,?,?,?,?)',
    [name, type||'piece', free_shipping_amount||0, first_piece||1, first_fee||0, extra_piece||1, extra_fee||0]);
  return res.json(success({id: r.lastInsertRowid}, '添加成功'));
});

router.put('/shipping-templates/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { name, type, free_shipping_amount, first_piece, first_fee, extra_piece, extra_fee, status } = req.body;
  run('UPDATE shipping_templates SET name=?,type=?,free_shipping_amount=?,first_piece=?,first_fee=?,extra_piece=?,extra_fee=?,status=? WHERE id=?',
    [name, type, free_shipping_amount||0, first_piece||1, first_fee||0, extra_piece||1, extra_fee||0, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});

router.delete('/shipping-templates/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM shipping_templates WHERE id=?', [req.params.id]);
  run('DELETE FROM shipping_regions WHERE template_id=?', [req.params.id]);
  run('DELETE FROM shipping_no_ship WHERE template_id=?', [req.params.id]);
  return res.json(success(null, '删除成功'));
});

// ========== 运费模板 - 地区管理 ==========

// 获取省份列表
router.get('/provinces', (req, res) => {
  const list = all('SELECT * FROM shipping_provinces ORDER BY id ASC');
  return res.json(success(list));
});

// 获取模板的地区分组
router.get('/shipping-templates/:id/regions', authAdmin, (req, res) => {
  const list = all('SELECT * FROM shipping_regions WHERE template_id=? ORDER BY id ASC', [req.params.id]);
  return res.json(success(list));
});

// 添加地区分组
router.post('/shipping-templates/:id/regions', authAdmin, demoSafeGuard, (req, res) => {
  const { region_ids, region_names, first_piece, first_fee, extra_piece, extra_fee } = req.body;
  run('INSERT INTO shipping_regions(template_id,region_ids,region_names,first_piece,first_fee,extra_piece,extra_fee) VALUES(?,?,?,?,?,?,?)',
    [req.params.id, JSON.stringify(region_ids||[]), JSON.stringify(region_names||[]), first_piece||1, first_fee||0, extra_piece||1, extra_fee||0]);
  return res.json(success(null, '地区分组添加成功'));
});

// 更新地区分组
router.put('/shipping-templates/:id/regions/:rid', authAdmin, demoSafeGuard, (req, res) => {
  const { region_ids, region_names, first_piece, first_fee, extra_piece, extra_fee } = req.body;
  run('UPDATE shipping_regions SET region_ids=?,region_names=?,first_piece=?,first_fee=?,extra_piece=?,extra_fee=? WHERE id=? AND template_id=?',
    [JSON.stringify(region_ids||[]), JSON.stringify(region_names||[]), first_piece||1, first_fee||0, extra_piece||1, extra_fee||0, req.params.rid, req.params.id]);
  return res.json(success(null, '地区分组更新成功'));
});

// 删除地区分组
router.delete('/shipping-templates/:id/regions/:rid', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM shipping_regions WHERE id=? AND template_id=?', [req.params.rid, req.params.id]);
  return res.json(success(null, '地区分组已删除'));
});

// 获取不发货地区
router.get('/shipping-templates/:id/no-ship', authAdmin, (req, res) => {
  const list = all('SELECT * FROM shipping_no_ship WHERE template_id=? ORDER BY id ASC', [req.params.id]);
  return res.json(success(list));
});

// 保存不发货地区
router.post('/shipping-templates/:id/no-ship', authAdmin, demoSafeGuard, (req, res) => {
  const { region_ids, region_names } = req.body;
  // 先清空再插入
  run('DELETE FROM shipping_no_ship WHERE template_id=?', [req.params.id]);
  if (region_ids && region_ids.length > 0) {
    run('INSERT INTO shipping_no_ship(template_id,region_ids,region_names) VALUES(?,?,?)',
      [req.params.id, JSON.stringify(region_ids), JSON.stringify(region_names||[])]);
  }
  return res.json(success(null, '不发货地区已保存'));
});

// ========== 备份管理 ==========
const backupDir=path.join(__dirname,'..','..','backup');
router.get('/backups', authAdmin, (req, res) => {
  try{if(!fs.existsSync(backupDir))fs.mkdirSync(backupDir,{recursive:true});
    const files=fs.readdirSync(backupDir).filter(f=>f.endsWith('.db')).sort().reverse();
    res.json(success(files));
  }catch{res.json(success([]))}
});
router.post('/backup', authAdmin, demoSafeGuard, (req, res) => {
  try{
    if(!fs.existsSync(backupDir))fs.mkdirSync(backupDir,{recursive:true});
    const name='backup_'+new Date().toISOString().replace(/[:.]/g,'-')+'.db';
    const src=path.join(__dirname,'..','data','litemall.db');
    if(fs.existsSync(src))fs.copyFileSync(src,path.join(backupDir,name));
    logAction(req.userId,'backup','system','数据库备份完成: '+name);
    res.json(success(null,'备份成功'));
  }catch{res.json(fail('备份失败'))}
});
router.post('/backup/restore', authAdmin, demoSafeGuard, (req, res) => {
  try{
    const backup=path.join(backupDir,req.body.name);
    if(!fs.existsSync(backup))return res.json(fail('备份文件不存在'));
    const dest=path.join(__dirname,'..','data','litemall.db');
    // 先备份当前数据库
    const preName='pre_restore_'+Date.now()+'.db';
    if(fs.existsSync(dest))fs.copyFileSync(dest,path.join(backupDir,preName));
    fs.copyFileSync(backup,dest);
    logAction(req.userId,'restore','system','数据库还原: '+req.body.name);
    res.json(success(null,'还原成功，请重启服务'));
  }catch{res.json(fail('还原失败'))}
});
router.delete('/backup/:name', authAdmin, demoSafeGuard, (req, res) => {
  try{const f=path.join(backupDir,req.params.name);if(fs.existsSync(f))fs.unlinkSync(f);res.json(success(null,'已删除'))}catch{res.json(fail('删除失败'))}
});

// ========== 缓存管理 ==========
router.post('/cache/clear', authAdmin, demoSafeGuard, (req, res) => {
  try{
    const dir=path.join(__dirname,'..','..','runtime','cache');
    if(fs.existsSync(dir)){const files=fs.readdirSync(dir);files.forEach(f=>fs.unlinkSync(path.join(dir,f)))}
    logAction(req.userId,'clear_cache','system','清除缓存');
    res.json(success(null,'缓存已清除'));
  }catch{res.json(success(null,'缓存已清除'))}
});

// ========== 系统信息 ==========
router.get('/system-info', authAdmin, (req, res) => {
  const tables=get("SELECT COUNT(*) as c FROM sqlite_master WHERE type='table'").c;
  const totalRows=all("SELECT SUM(cnt) as s FROM (SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' UNION ALL SELECT 0)")[0]?.s||0;
  const users=get('SELECT COUNT(*) as c FROM users').c;
  const products=get('SELECT COUNT(*) as c FROM products').c;
  const orders=get('SELECT COUNT(*) as c FROM orders').c;
  res.json(success({node:process.version,db:'SQLite3',tables,totalRows,users,products,orders}));
});


module.exports = { router };
