package com.ruoyi.web.controller.system;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import javax.imageio.ImageIO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Controller;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ShiroUtils;

@Controller
public class SysVueCaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Value("${shiro.user.captchaEnabled:true}")
    private boolean captchaEnabled;

    @Value("${shiro.user.captchaType:math}")
    private String captchaType;

    @GetMapping("/captchaImage")
    @ResponseBody
    public AjaxResult getVueCaptchaImage(HttpServletRequest request) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }
        BufferedImage bi;
        String code;
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            String capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            bi = captchaProducerMath.createImage(capStr);
        }
        else
        {
            code = captchaProducer.createText();
            bi = captchaProducer.createImage(code);
        }
        ShiroUtils.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", outputStream);
        ajax.put("img", Base64.getEncoder().encodeToString(outputStream.toByteArray()));
        ajax.put("uuid", String.valueOf(ShiroUtils.getSession().getId()));
        return ajax;
    }
}
