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

// ========== 仪表盘 ==========
router.get('/dashboard/stats', authAdmin, (req, res) => {
  try {
    const totalUsers = get("SELECT COUNT(*) as c FROM users WHERE phone!='admin'")?.c || 0;
    const pendingShip = get("SELECT COUNT(*) as c FROM orders WHERE status='pending_ship'")?.c || 0;
    const pendingRefund = get("SELECT COUNT(*) as c FROM orders WHERE status='refunding'")?.c || 0;
    const totalSales = get("SELECT COALESCE(SUM(pay_amount),0) as s FROM orders WHERE status NOT IN ('pending_pay','closed')")?.s || 0;
    const today = get("SELECT COUNT(*) as c, COALESCE(SUM(pay_amount),0) as s FROM orders WHERE date(created_at)=date('now','localtime') AND status NOT IN ('pending_pay')") || { c: 0, s: 0 };
    const lowStockCount = get('SELECT COUNT(*) as c FROM products WHERE status=1 AND stock<=10')?.c || 0;
    const totalOrders = get('SELECT COUNT(*) as c FROM orders')?.c || 0;
    return res.json(success({
      todayOrders: today.c,
      todaySales: today.s,
      totalUsers,
      totalSales,
      pendingShip,
      pendingRefund,
      lowStock: lowStockCount,
      totalOrders,
      orderChange: 0,
      salesChange: 0,
      userChange: 0
    }));
  } catch(e) {
    console.error('[Dashboard] 统计查询失败:', e.message);
    return res.json(fail('获取统计数据失败'));
  }
});

router.get('/dashboard/order-trend', authAdmin, (req, res) => {
  const days = Math.min(365, Math.max(1, parseInt(req.query.days) || 7));
  const chart = all(`SELECT date(created_at) as d, COUNT(*) as orders, COALESCE(SUM(pay_amount),0) as revenue FROM orders WHERE created_at >= datetime('now','localtime',?) AND status NOT IN ('pending_pay') GROUP BY d ORDER BY d`, [`-${days} day`]);
  return res.json(success(chart));
});

router.get('/dashboard', authAdmin, (req, res) => {
  try {
    const totalUsers = get("SELECT COUNT(*) as c FROM users WHERE phone!='admin'")?.c || 0;
    const pendingShip = get("SELECT COUNT(*) as c FROM orders WHERE status='pending_ship'")?.c || 0;
    const pendingRefund = get("SELECT COUNT(*) as c FROM orders WHERE status='refunding'")?.c || 0;
    const totalSales = get("SELECT COALESCE(SUM(pay_amount),0) as s FROM orders WHERE status NOT IN ('pending_pay','closed')")?.s || 0;
    const today = get("SELECT COUNT(*) as c, COALESCE(SUM(pay_amount),0) as s FROM orders WHERE date(created_at)=date('now','localtime') AND status NOT IN ('pending_pay')") || { c: 0, s: 0 };
    const lowStockCount = get('SELECT COUNT(*) as c FROM products WHERE status=1 AND stock<=10')?.c || 0;
    const totalOrders = get('SELECT COUNT(*) as c FROM orders')?.c || 0;
    return res.json(success({
      today_orders: today.c,
      today_sales: today.s,
      total_users: totalUsers,
      total_sales: totalSales,
      pending_ship: pendingShip,
      pending_refund: pendingRefund,
      low_stock: lowStockCount,
      total_orders: totalOrders
    }));
  } catch(e) {
    console.error('[Dashboard] 查询失败:', e.message);
    return res.json(fail('获取仪表盘数据失败'));
  }
});

router.get('/dashboard/chart', authAdmin, (req, res) => {
  const days = Math.min(365, Math.max(1, parseInt(req.query.days) || 7));
  const chart = all(`SELECT date(created_at) as d, COUNT(*) as orders, COALESCE(SUM(pay_amount),0) as sales 
    FROM orders WHERE created_at >= datetime('now','localtime',?) GROUP BY d ORDER BY d`, [`-${days} day`]);
  return res.json(success(chart));
});


module.exports = { router };
