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

// 生成图片验证码
class ImageCaptcha extends API {
    constructor() {
        super();

        this.setMethod("GET");
        this.setPath("/Captcha/ImageCaptcha");
    }

    async onRequest(req, res) {
        const options = {
            size: 4, // 4个字母
            noise: 2, // 干扰线2条
            color: true, 
            background: "#FFD4DA",
        }
        const captcha = svgCaptcha.create(options) //字母和数字随机验证码
        let { text, data } = captcha

        text = text.toLowerCase() 

        data = Buffer.from(data).toString('base64');
        // 构建Base64编码的Data URL
        data = `data:image/svg+xml;base64,${data}`;

        const id = uuidv4();

        try {
            await Redis.set(`captcha:${id}`, text, {
                EX: 600
            });
        } catch (err) {
            this.logger.error(`获取图片验证码失败！${err.stack}`);
            return res.json({
                ...BaseStdResponse.DATABASE_ERR,
                msg:'获取图片验证码失败！'
            })
        }

        res.json({
            ...BaseStdResponse.OK,
            data: {
                img: data,
                id
            }
        })
    }
}

module.exports.ImageCaptcha = ImageCaptcha;
