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

class AddAccount extends API {
    constructor() {
        super()

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

    async onRequest(req, res) {
        let { uuid, session, area, building, room, email, lowest, notes, id } = req.body

        if ([uuid, session, area, building, lowest, room].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
            })

        const time = new Date().getTime()

        let sql, r

        if (!id) {
            let balance, koufei_date
            try {
                const endpoint = `https://hqpay.ctbu.edu.cn/weixin/ashx/frmuser.ashx?test=lastlist&pid=${room}&dyid=${building}`
                const res = await axios.get(endpoint, {
                    proxy: false
                })

                if (!res || !res.data || !res.data[0])
                    return res.json({
                        ...BaseStdResponse.ERR,
                        msg: '获取电费信息失败！请稍后再试'
                    })
                balance = res.data[0][1]
                koufei_date = res.data[0][2]

            } catch (error) {
                this.logger.error(`获取电费信息失败！${error.stack}`)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '获取电费信息失败！请稍后再试'
                })
            }

            sql = 'INSERT INTO power_task (create_user, create_time, update_time, area, building, room, email, lowest, notes, balance, koufei_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
            r = await db.query(sql, [uuid, time, time, area, building, room, email, lowest, notes ?? '', balance, koufei_date])
        } else {
            sql = 'UPDATE power_task SET area = ?, building = ?, room = ?, email = ?, lowest = ?, notes = ?, is_notice = 0 WHERE id = ?'
            r = await db.query(sql, [area, building, room, email, lowest, notes ?? '', id])
        }

        try {
            if (r && r.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK
                })
            } else {
                return res.json({ ...BaseStdResponse.ERR, msg: '添加电费提醒任务失败！数据库错误' })
            }
        } catch (err) {
            this.logger.error(`添加电费提醒任务失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: "添加电费提醒任务失败！",
            })
        }
    }
}

module.exports.AddAccount = AddAccount