const API = require("../../../lib/API")
const { BaseStdResponse } = require("../../../BaseStdResponse")
const Redis = require('../../../plugin/DataBase/Redis')
const EmailTemplate = require('../../../plugin/Email/emailTemplate')

// 发送邮箱验证码
class qqLoginStep1 extends API {
    constructor() {
        super()

        this.setMethod("POST")
        this.setPath("/User/qqLoginStep1")
    }

    async onRequest(req, res) {
        const { qq } = req.body

        if ([qq].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`
        const code = Math.random().toFixed(6).slice(-6)

        try {
            await Redis.set(`email:${email}`, code, {
                EX: 600
            })
        } catch (err) {
            this.logger.error(`发送邮箱验证码失败！${err.stack}`)
            return res.json({
                ...BaseStdResponse.SMS_SEND_FAIL,
                msg: '请检查邮箱格式后再试！'
            })
        }

        res.json({
            ...BaseStdResponse.OK
        })

        // 先返回后发送
        EmailTemplate.checkEmail(email, code)
    }
}

module.exports.qqLoginStep1 = qqLoginStep1
