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

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

        this.setPath('/Admin/User/GetUserList')
        this.setMethod('get')
    }

    async onRequest(req, res) {
        let { uuid, session, email, user_uuid, username, nickname, pagesize, current } = req.query

        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") && !permission.includes("service"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

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

        let sql = `
            SELECT
                uuid, username, nickname, email, registTime, avatar, lepao_count,
                COALESCE(send_count_auto_approve, 0) AS send_count_auto_approve,
                social_type, lastTime
            FROM
                users
            WHERE 
                1 = 1
        `

        let countSql = `
            SELECT COUNT(*) AS total
            FROM users
            WHERE 1 = 1
        `

        let params = []
        let countParams = []

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

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

        if (username) {
            sql += ` AND username LIKE ?`
            countSql += ` AND username LIKE ?`
            params.push(`%${username}%`)
            countParams.push(`%${username}%`)
        }

        if (nickname) {
            sql += ` AND nickname LIKE ?`
            countSql += ` AND nickname LIKE ?`
            params.push(`%${nickname}%`)
            countParams.push(`%${nickname}%`)
        }

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

        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.GetUserList = GetUserList