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 notification = require('../lib/notification');

// ========== 订单管理 ==========
router.get('/orders', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 20, status, 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 (status) { where += ' AND o.status=?'; params.push(status); }
  if (keyword) { where += ' AND (o.order_no LIKE ? OR o.consignee LIKE ? OR o.phone LIKE ?)'; params.push(`%${keyword}%`, `%${keyword}%`, `%${keyword}%`); }

  const total = get(`SELECT COUNT(*) as c FROM orders o ${where}`, params).c;
  const list = all(`SELECT o.*, u.nickname FROM orders o LEFT JOIN users u ON o.user_id=u.id ${where} ORDER BY o.id DESC LIMIT ? OFFSET ?`,
    [...params, size, (pageNum - 1) * size]);
  // 批量查询子项（优化 N+1）
  if (list.length > 0) {
    const ids = list.map(o => o.id);
    const placeholders = ids.map(() => '?').join(',');
    const allItems = all(`SELECT * FROM order_items WHERE order_id IN (${placeholders})`, ids);
    const itemsByOrder = {};
    for (const item of allItems) {
      if (!itemsByOrder[item.order_id]) itemsByOrder[item.order_id] = [];
      itemsByOrder[item.order_id].push(item);
    }
    for (const order of list) {
      order.items = itemsByOrder[order.id] || [];
    }
  }
  return res.json(page(list, total, pageNum, size));
});

router.get('/orders/:orderNo', authAdmin, (req, res) => {
  const order = get('SELECT o.*, u.nickname, u.phone as user_phone FROM orders o LEFT JOIN users u ON o.user_id=u.id WHERE o.order_no=?', [req.params.orderNo]);
  if (!order) return res.json(fail('订单不存在'));
  order.items = all('SELECT * FROM order_items WHERE order_id=?', [order.id]);
  order.logs = all('SELECT * FROM order_logs WHERE order_id=? ORDER BY id ASC', [order.id]);
  return res.json(success(order));
});

router.post('/orders/:orderNo/ship', authAdmin, demoSafeGuard, (req, res) => {
  const { shipping_company, shipping_no } = req.body;
  const order = get('SELECT * FROM orders WHERE order_no=?', [req.params.orderNo]);
  if (!order) return res.json(fail('订单不存在'));
  run('UPDATE orders SET status=?,shipping_company=?,shipping_no=?,shipping_time=datetime(\'now\',\'localtime\') WHERE id=?',
    ['shipped', shipping_company||'', shipping_no||'', order.id]);
  run('INSERT INTO order_logs(order_id,action,content,operator) VALUES(?,?,?,?)', [order.id, 'ship', `发货:${shipping_company||''} ${shipping_no||''}`, 'admin']);

  // 异步通知 - 发货通知
  notification.send('order_shipped', order.user_id, {
    order_no: order.order_no,
    shipping_company: shipping_company || '',
    shipping_no: shipping_no || ''
  }).catch(err => console.error('[通知] 发货通知失败:', err.message));

  return res.json(success(null, '发货成功'));
});

router.post('/orders/:orderNo/complete', authAdmin, demoSafeGuard, (req, res) => {
  run("UPDATE orders SET status='completed',updated_at=datetime('now','localtime') WHERE order_no=?", [req.params.orderNo]);
  return res.json(success(null, '操作成功'));
});

router.post('/orders/:orderNo/close', authAdmin, demoSafeGuard, (req, res) => {
  run("UPDATE orders SET status='closed',close_time=datetime('now','localtime') WHERE order_no=?", [req.params.orderNo]);
  return res.json(success(null, '已关闭'));
});

// ========== 评价管理 ==========
router.get('/reviews/admin', authAdmin, (req, res) => {
  const {page:p=1,pageSize=10,status}=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!==undefined&&status!==''){where+=' AND r.status=?';params.push(+status)}
  const total=get(`SELECT COUNT(*) as c FROM product_reviews r ${where}`,params).c;
  const list=all(`SELECT r.*,u.nickname,p.name as product_name FROM product_reviews r LEFT JOIN users u ON r.user_id=u.id LEFT JOIN products p ON r.product_id=p.id ${where} ORDER BY r.id DESC LIMIT ? OFFSET ?`,[...params,size,(pageNum-1)*size]);
  res.json(page(list,total,pageNum,size));
});
router.put('/reviews/admin/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('UPDATE product_reviews SET status=? WHERE id=?',[req.body.status??1,req.params.id]);
  res.json(success(null,'更新成功'));
});
router.delete('/reviews/admin/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM product_reviews WHERE id=?',[req.params.id]);
  res.json(success(null,'已删除'));
});


module.exports = { router };
