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 ChangeAutoRun extends API {
    constructor() {
        super();

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

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

        if ([uuid, session, id].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
            })

        let selectSql = 'SELECT create_user, target_count, term_num, auto_run FROM lepao_account WHERE id = ?'
        let selectRows = await db.query(selectSql, [id])
        if (!selectRows || selectRows.length === 0)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '切换自动乐跑状态失败！未找到账户信息'
            })

        if (selectRows[0].create_user !== uuid) {
            let permission = await AccessControl.getPermission(uuid)
            if (!permission.includes("admin") && !permission.includes("service"))
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '切换自动乐跑状态失败！未找到账户信息'
                })
        }

        if (selectRows[0].auto_run === 0 && (selectRows[0].target_count <= selectRows[0].term_num) && selectRows[0].target_count !== 0) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '该账号本月跑步里程已达到预设目标里程，请尝试增大目标后再试'
            })
        }

        let sql = 'UPDATE lepao_account SET auto_run = 1 - auto_run WHERE id = ?';
        try {
            let r = await db.query(sql, [id]);

            if (r && r.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK
                })
            } else {
                res.json({
                    ...BaseStdResponse.ERR,
                    msg: '切换自动乐跑状态失败！未找到对应数据或数据库未更新'
                })
            }
        } catch (err) {
            this.logger.error(`切换自动乐跑状态失败！${err.stack}`);
            res.json({
                ...BaseStdResponse.ERR,
                msg: "切换自动乐跑状态失败！数据库异常"
            });
        }
    }
}

module.exports.ChangeAutoRun = ChangeAutoRun;
