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

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

        this.setPath('/Lepao/GetLepaoData')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        let { uuid, session } = req.query

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

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

        try {
            let selectSql = `
                            SELECT 
                                u.lepao_count,
                                (
                                    SELECT COUNT(*) 
                                    FROM lepao_account a 
                                    WHERE a.create_user = u.uuid
                                ) AS lepao_account_total,
                                (
                                    SELECT COUNT(*) 
                                    FROM lepao_record r 
                                    WHERE r.uuid = u.uuid
                                ) AS lepao_record_total
                            FROM users u
                            WHERE u.uuid = ?;
                        `
            
            let selectRows = await db.query(selectSql, [uuid])
            if (!selectRows || selectRows.length === 0)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '查询用户信息失败'
                })

            res.json({
                ...BaseStdResponse.OK,
                data: selectRows[0]
            })

        } catch (err) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: "查询用户信息失败"
            })
        }
    }
}

module.exports.GetLepaoData = GetLepaoData
