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

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

        this.setPath('/JW/Account')
        this.setMethod('POST')
    }

    async onRequest(req, res) {
        let { uuid, session, username, password, id } = req.body

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

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

        const time = new Date().getTime()
        password = atob(password)

        let sql, r
        if (!id) {
            sql = 'INSERT INTO jw_account (username, password, create_user, create_time) VALUES (?, ?, ?, ?)'
            r = await db.query(sql, [username, password, uuid, time])
        } else {
            sql = 'UPDATE jw_account SET username = ?, password = ?, update_time = ?, state = ? WHERE id = ?'
            r = await db.query(sql, [username, password, time, 0, 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.GetType = GetType;