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");

// ========== AI知识库管理 ==========
router.get('/knowledge', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 20, keyword } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(100, Math.max(1, +pageSize));
  let where = 'WHERE 1=1';
  const params = [];
  if (keyword) { where += ' AND (question LIKE ? OR answer LIKE ? OR keywords LIKE ?)'; params.push(`%${keyword}%`, `%${keyword}%`, `%${keyword}%`); }
  const total = get(`SELECT COUNT(*) as c FROM ai_knowledge_base ${where}`, params).c;
  const list = all(`SELECT * FROM ai_knowledge_base ${where} ORDER BY weight DESC LIMIT ? OFFSET ?`, [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

router.post('/knowledge', authAdmin, demoSafeGuard, (req, res) => {
  const { category, question, answer, keywords, weight } = req.body;
  run('INSERT INTO ai_knowledge_base(category,question,answer,keywords,weight) VALUES(?,?,?,?,?)',
    [category||'', question, answer, keywords||'', weight||0]);
  return res.json(success(null, '添加成功'));
});

router.put('/knowledge/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { category, question, answer, keywords, weight, status } = req.body;
  run("UPDATE ai_knowledge_base SET category=?,question=?,answer=?,keywords=?,weight=?,status=?,updated_at=datetime('now','localtime') WHERE id=?",
    [category||'', question, answer, keywords||'', weight||0, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});

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

router.post('/knowledge/import', authAdmin, demoSafeGuard, (req, res) => {
  const { items } = req.body;
  if (!items || !items.length) return res.json(fail('请提供数据'));
  for (const item of items) {
    run('INSERT INTO ai_knowledge_base(category,question,answer,keywords,weight) VALUES(?,?,?,?,?)',
      [item.category||'', item.question, item.answer, item.keywords||'', item.weight||0]);
  }
  return res.json(success(null, `成功导入${items.length}条`));
});

// ========== 售后订单管理 ==========
router.get('/refunds', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 10, status, keyword } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(50, Math.max(1, +pageSize));
  let where = 'WHERE 1=1';
  const params = [];
  if (status) { where += ' AND r.status=?'; params.push(status); }
  if (keyword) { where += ' AND (r.refund_no LIKE ? OR o.order_no LIKE ?)'; params.push(`%${keyword}%`, `%${keyword}%`); }
  const total = get(`SELECT COUNT(*) as c FROM refunds r LEFT JOIN orders o ON r.order_id=o.id ${where}`, params).c;
  const list = all(`SELECT r.*, o.order_no, o.pay_amount as order_amount FROM refunds r LEFT JOIN orders o ON r.order_id=o.id ${where} ORDER BY r.id DESC LIMIT ? OFFSET ?`, [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

router.post('/refunds/:id/approve', authAdmin, demoSafeGuard, (req, res) => {
  const refund = get('SELECT * FROM refunds WHERE id=?', [req.params.id]);
  if (!refund) return res.json(fail('退款申请不存在'));
  run('UPDATE refunds SET status=? WHERE id=?', ['refunded', refund.id]);
  run('UPDATE orders SET status=? WHERE id=?', ['received', refund.order_id]);
  run("INSERT INTO order_logs(order_id,action,content,operator) VALUES(?,?,?,?)", [refund.order_id, 'refund_approve', '管理员同意退款，金额:'+refund.amount, 'admin']);
  return res.json(success(null, '退款成功'));
});

router.post('/refunds/:id/reject', authAdmin, demoSafeGuard, (req, res) => {
  const refund = get('SELECT * FROM refunds WHERE id=?', [req.params.id]);
  if (!refund) return res.json(fail('退款申请不存在'));
  run('UPDATE refunds SET status=? WHERE id=?', ['rejected', refund.id]);
  run('UPDATE orders SET status=? WHERE id=?', ['pending_ship', refund.order_id]);
  run("INSERT INTO order_logs(order_id,action,content,operator) VALUES(?,?,?,?)", [refund.order_id, 'refund_reject', '管理员拒绝退款', 'admin']);
  return res.json(success(null, '已拒绝'));
});

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

router.get('/articles', authAdmin, (req, res) => {
  const {page:p=1,pageSize=10,category_id,keyword} = req.query;
  const pageNum=Math.max(1,+p); const size=Math.min(50,Math.max(1,+pageSize));
  let where='WHERE 1=1'; const params=[];
  if(category_id){where+=' AND a.category_id=?';params.push(category_id)}
  if(keyword){where+=' AND a.title LIKE ?';params.push('%'+keyword+'%')}
  const total=get(`SELECT COUNT(*) as c FROM articles a ${where}`,params).c;
  const list=all(`SELECT a.*, c.name as cat_name FROM articles a LEFT JOIN article_categories c ON a.category_id=c.id ${where} ORDER BY a.sort ASC, a.id DESC LIMIT ? OFFSET ?`,[...params,size,(pageNum-1)*size]);
  res.json(page(list,total,pageNum,size));
});
router.post('/articles', authAdmin, demoSafeGuard, (req, res) => {
  const {title,category_id,author,cover,summary,content,sort,status}=req.body;
  const r=run('INSERT INTO articles(title,category_id,author,cover,summary,content,sort,status) VALUES(?,?,?,?,?,?,?,?)',
    [title,category_id||null,author||'admin',cover||'',summary||'',content||'',sort||0,status||1]);
  res.json(success({id:r.lastInsertRowid}));
});
router.put('/articles/:id', authAdmin, demoSafeGuard, (req, res) => {
  const {title,category_id,author,cover,summary,content,sort,status}=req.body;
  run("UPDATE articles SET title=?,category_id=?,author=?,cover=?,summary=?,content=?,sort=?,status=?,updated_at=datetime('now','localtime') WHERE id=?",
    [title,category_id||null,author||'admin',cover||'',summary||'',content||'',sort||0,status||1,req.params.id]);
  res.json(success(null,'更新成功'));
});
router.delete('/articles/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM articles WHERE id=?',[req.params.id]);
  res.json(success(null,'已删除'));
});

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

// ========== 通知模板管理 ==========
router.get('/notification-templates', authAdmin, (req, res) => {
  res.json(success(all('SELECT * FROM notification_templates ORDER BY code ASC')));
});
router.put('/notification-templates/:id', authAdmin, demoSafeGuard, (req, res) => {
  const {title,content,channels,status}=req.body;
  run('UPDATE notification_templates SET title=?,content=?,channels=?,status=? WHERE id=?',[title,content,JSON.stringify(channels||[]),status||1,req.params.id]);
  res.json(success(null,'更新成功'));
});
router.get('/notification-logs', authAdmin, (req, res) => {
  const {page:p=1,pageSize=20}=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 notification_logs').c;
  const list=all('SELECT nl.*,u.nickname FROM notification_logs nl LEFT JOIN users u ON nl.user_id=u.id ORDER BY nl.id DESC LIMIT ? OFFSET ?',[size,(pageNum-1)*size]);
  res.json(page(list,total,pageNum,size));
});

// ========== 操作日志 ==========
router.get('/operation-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 operation_logs').c;
  const list=all('SELECT * FROM operation_logs ORDER BY id DESC LIMIT ? OFFSET ?',[size,(pageNum-1)*size]);
  res.json(page(list,total,pageNum,size));
});

// ========== 登录日志 ==========
router.get('/login-logs', authAdmin, (req, res) => {
  const {pageSize=20}=req.query;
  const list=all('SELECT * FROM login_logs ORDER BY id DESC LIMIT ?',[Math.min(50,+pageSize)]);
  res.json(success(list));
});


module.exports = { router };
