const express = require('express');
const router = express.Router();
const db = require('../db');
const { verifyToken, isSystemAdmin } = require('../middleware/auth');

// 获取所有操作说明列表
router.get('/descriptions', verifyToken, isSystemAdmin, async (req, res) => {
    try {
        const result = await db.query('SELECT DISTINCT description FROM audit_logs WHERE description IS NOT NULL AND description != \'\' ORDER BY description');
        res.json(result.rows.map(row => row.description));
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取系统日志 (超管 + 维护员)
router.get('/', verifyToken, isSystemAdmin, async (req, res) => {
    const { page = 1, limit = 20, username, startDate, endDate, description } = req.query;
    const offset = (page - 1) * limit;

    let query = 'SELECT * FROM audit_logs WHERE 1=1';
    let countQuery = 'SELECT COUNT(*) FROM audit_logs WHERE 1=1';
    const params = [];

    if (username) {
        query += ` AND (username ILIKE $${params.length + 1} OR real_name ILIKE $${params.length + 1})`;
        countQuery += ` AND (username ILIKE $${params.length + 1} OR real_name ILIKE $${params.length + 1})`;
        params.push(`%${username}%`);
    }

    if (startDate) {
        query += ` AND created_at >= $${params.length + 1}`;
        countQuery += ` AND created_at >= $${params.length + 1}`;
        params.push(startDate);
    }

    if (endDate) {
        // 结束日期通常需要加一天或者设为当天的 23:59:59，这里假设前端传的是日期字符串
        // 简单处理：如果传的是 YYYY-MM-DD，则数据库比较时会自动转为 00:00:00，所以可能需要处理
        // 这里假设前端传的是完整时间或者后端直接比较
        query += ` AND created_at <= $${params.length + 1}`;
        countQuery += ` AND created_at <= $${params.length + 1}`;
        params.push(endDate);
    }

    if (description) {
        query += ` AND description = $${params.length + 1}`;
        countQuery += ` AND description = $${params.length + 1}`;
        params.push(description);
    }

    query += ` ORDER BY created_at DESC LIMIT $${params.length + 1} OFFSET $${params.length + 2}`;
    
    try {
        const countRes = await db.query(countQuery, params);
        const total = parseInt(countRes.rows[0].count);

        const result = await db.query(query, [...params, limit, offset]);
        
        res.json({
            logs: result.rows,
            total,
            page: parseInt(page),
            totalPages: Math.ceil(total / limit)
        });
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: '服务器错误' });
    }
});

module.exports = router;
