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

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

        this.setPath('/Admin/IndexData')
        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,
                endpoint: 1513126
            })
        }

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

        let sql = `
                    SELECT
                        (SELECT COUNT(*) FROM jw_account WHERE create_user = ?) AS accounts,
                        (SELECT COUNT(*) FROM ic_rule) AS rules
                `

        try {
            let r = await db.query(sql, [uuid])
            if (!r)
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR
                })
            
            let { accounts, rules } = r[0]

            sql = `
            SELECT 
                a.id,
                a.title,
                a.\`describe\`,
                a.views,
                a.type,
                a.time,
                u.username AS author
            FROM 
                article a
            LEFT JOIN 
                users u 
            ON 
                a.author = u.uuid
            WHERE 
                a.state = 1 
                AND a.type = 'news'
            ORDER BY 
                a.id DESC
            LIMIT 9
        `

            r = await db.query(sql)
            if(!r)
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR
                })

            res.json({
                ...BaseStdResponse.OK,
                data: {
                    accounts,
                    rules,
                    article: r
                }
            })

        } catch (err) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: `获取数据失败！${err.message || ''}`
            })
        }
    }
}

module.exports.IndexData = IndexData;
