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

// 激活教务账号
class ActiveAccount extends API {
    constructor() {
        super();

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

    async checkJwAccount(uuid, username) {
        const sql = 'SELECT password FROM jw_account WHERE create_user = ? AND username = ?'
        const rows = await db.query(sql, [uuid, username]);
        if (!rows || rows.length !== 1 || !rows[0].password)
            return false
        return rows[0].password;
    }

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

        if ([uuid, session, username].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 password = await this.checkJwAccount(uuid, username)
        if (!password)
            res.json({
                ...BaseStdResponse.ERR,
                msg: '教务系统账号未绑定'
            })

        try {
            let cookie = await ic.resetCookie(username, password)
            let user = await ic.getUserInfo(cookie)
            if (user.code === 300) {
                cookie = await ic.resetCookie(username, password)
                user = await ic.getUserInfo(cookie)
            }

            const { trueName, className, deptName } = user

            const time = new Date().getTime()

            let sql = 'UPDATE jw_account SET state = 1, update_time = ?, realname = ?, className = ?, deptName = ? WHERE username = ?'

            let r = await db.query(sql, [time, trueName, className, deptName, username])
            if (r && r.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK,
                    id: r.insertId
                })
            } else {
                res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '激活账号失败！数据库错误' })
            }
        } catch (err) {
            res.json({
                ...BaseStdResponse.ERR,
                msg: `激活账号失败！${err.message || ''}`,
            });
        }
    }
}

module.exports.ActiveAccount = ActiveAccount