const API = require("../../../lib/API")
const { v4: uuidv4 } = require('uuid')
const Redis = require('../../../plugin/DataBase/Redis')
const db = require("../../../plugin/DataBase/db")
const { BaseStdResponse } = require("../../../BaseStdResponse");

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

        this.setPath('/User/qqLoginStep2')
        this.setMethod('POST')
    }

    async onRequest(req, res) {
        let { qq, code, location, deviceInfo } = req.body

        if ([qq, code].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })

        if (String(qq).length < 6 || String(qq).length > 10)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '请输入正确的QQ号'
            })

        const email = `${qq}@qq.com`

        try {
            const VerifyCode = await Redis.get(`email:${email}`)
            if (!VerifyCode || VerifyCode != code)
                return res.json({
                    ...BaseStdResponse.SMS_CHECK_FAIL,
                    msg: '验证码输入错误或已过期'
                })
        } catch (err) {
            this.logger.error(`验证验证码失败！${err.stack}`)
            return res.json({
                ...BaseStdResponse.DATABASE_ERR,
                msg: '验证失败！'
            })
        }

        const session = uuidv4()
        const time = new Date().getTime()

        let selectSql = 'SELECT uuid, username, permission, avatar FROM users WHERE email = ?'
        let selectRows = await db.query(selectSql, [email])

        let uuid, username, permission, avatar

        // 用户不存在 执行注册操作
        if (selectRows.length == 0) {
            uuid = uuidv4()
            username = `用户${uuid.slice(0, 8)}`
            avatar = `https://q1.qlogo.cn/g?b=qq&nk=${qq}&s=640`

            let regSql = 'INSERT INTO users (uuid, username, session, registTime, avatar, email) VALUES (?,?,?,?,?,?) '
            let regRows = await db.query(regSql, [uuid, username, session, time, avatar, email])
            if (!regRows || regRows.affectedRows !== 1) {
                this.logger.error(`用户注册失败！数据库错误`)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '用户注册失败！'
                })
            }
        }

        else {
            let updateSql = 'UPDATE users SET session = ?, lastTime = ? WHERE email = ?'
            let updateRows = await db.query(updateSql, [session, time, email])
            if (!updateRows || updateRows.affectedRows !== 1) {
                this.logger.error(`用户登录失败！数据库错误`)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '用户登录失败！请稍后再试'
                })
            }

            uuid = selectRows[0].uuid
            avatar = selectRows[0].avatar
            username = selectRows[0].username
            permission = selectRows[0].permission
        }

        res.json({
            ...BaseStdResponse.OK,
            data: {
                uuid,
                username,
                session,
                roles: permission || [],
                avatar
            }
        })

        await Redis.del(`email:${email}`)

        // 增加登录记录
        try {
            let ip = req.headers['x-forwarded-for']?.split(',')[0].trim() || req.connection.remoteAddress
            if (ip.startsWith('::ffff:')) {
                ip = ip.replace('::ffff:', '');
            }

            let insertSql = 'INSERT INTO login_history (uuid, time, location, deviceInfo, type, ip) VALUES (?, ?, ?, ?, ?, ?)'
            await db.query(insertSql, [uuid, time, location, deviceInfo, 'qq', ip])
        } catch (error) {
            this.logger.error(`写入登录记录失败！${error}`)
        }
    }
}

module.exports.qqLoginStep2 = qqLoginStep2