const API = require("../../../lib/API")
const db = require("../../../plugin/DataBase/db")
const AccessControl = require("../../../lib/AccessControl")
const { BaseStdResponse } = require("../../../BaseStdResponse")

class GetReqLog extends API {
    constructor() {
        super();

        this.setPath('/Admin/User/GetReqLog')
        this.setMethod('post')
    }

    async onRequest(req, res) {
        let { uuid, session, create_user, begin_time, end_time, url, ip, pagesize, current } = req.body

        if ([uuid, session, pagesize, current].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })

        // 校验分页参数
        if (isNaN(pagesize) || pagesize <= 0 || pagesize > 50) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '参数错误'
            })
        }

        if (isNaN(current) || current <= 0) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '参数错误'
            })
        }

        // 检查 session
        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED
            })

        // 检查权限
        let permission = await AccessControl.getPermission(uuid)
        if (!permission.includes("admin"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

        // 计算分页的 offset
        const offset = (current - 1) * pagesize

       let sql = `
                SELECT 
                    l.id,
                    l.create_time,
                    l.method,
                    l.code,
                    l.ip,
                    l.location,
                    l.url,
                    l.deviceType,
                    u.username,
                    u.avatar
                FROM 
                    requestLog l
                LEFT JOIN 
                    users u
                ON 
                    l.create_user = u.uuid
                WHERE 
                    1 = 1
            `

        let countSql = `
            SELECT COUNT(*) AS total
            FROM 
                requestLog l
            LEFT JOIN 
                users u
            ON 
                l.create_user = u.uuid
            WHERE 1 = 1
        `

        let params = []
        let countParams = []

        if (create_user) {
            sql += ` AND l.create_user = ?`
            countSql += ` AND l.create_user = ?`
            params.push(create_user)
            countParams.push(create_user)
        }

        if (begin_time) {
            sql += ` AND l.create_time > ?`
            countSql += ` AND l.create_time > ?`
            params.push(begin_time)
            countParams.push(begin_time)
        }

        if (end_time) {
            sql += ` AND l.create_time < ?`
            countSql += ` AND l.create_time < ?`
            params.push(end_time)
            countParams.push(end_time)
        }

        if (url) {
            sql += ` AND l.url = ?`
            countSql += ` AND l.url = ?`
            params.push(url)
            countParams.push(url)
        }

        if (ip) {
            sql += ` AND l.ip = ?`
            countSql += ` AND l.ip = ?`
            params.push(ip)
            countParams.push(ip)
        }

        sql += `
            ORDER BY l.id DESC
            LIMIT ? OFFSET ?;
        `
        params.push(String(pagesize), String(offset))

        // 临时调大缓存
        // await db.query("SET SESSION sort_buffer_size = 8*1024*1024;")

        let rows = await db.query(sql, params)
        let countResult = await db.query(countSql, countParams)

        if (!rows || !countResult)
            return res.json({
                ...BaseStdResponse.MISSING_FILE,
                msg: '获取日志数据失败！'
            })

        let total = countResult[0].total

        res.json({
            ...BaseStdResponse.OK,
            data: rows,
            pagination: {
                current,
                pagesize,
                total
            }
        })
    }
}

module.exports.GetReqLog = GetReqLog