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

// 发布/修改文章
class PostArticle extends API {
    constructor() {
        super()

        this.setPath('/Admin/Article')
        this.setMethod('POST')
    }

    async onRequest(req, res) {

        let {
            uuid,
            session,
            id,
            title,
            cover,
            describe,
            content,
            type,
            state
        } = req.body

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

        // 检查 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("article"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

        const time = new Date().getTime()
        let sql, r
        if (!id) {
            sql = 'INSERT INTO article (title, cover, time, content, author, state, \`describe\`, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
            r = await db.query(sql, [title, cover, time, content, uuid, state, describe, type])
        } else {
            sql = 'UPDATE article SET title = ?, cover = ?, content = ?, state = ?, \`describe\` = ?, type = ? WHERE id = ?'
            r = await db.query(sql, [title, cover, content, state, describe, type, id])
        }

        try {
            if (r && r.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK,
                    id: r.insertId
                })
            } else {
                res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '发表文章失败！数据库错误' })
            }
        } catch (err) {
            this.logger.error(`发表文章失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: "发表文章失败！",
            });
        }
    }

}

module.exports.PostArticle = PostArticle;