package com.ruoyi.controller;

import com.ruoyi.utils.captcha.ImgVerifyCode;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * 图形验证码
 * @author funcong
 * @create 2021/5/4
 */
@CrossOrigin
@RestController
@RequestMapping("/api/captcha")
@Api(tags = "图形验证码")
public class AppCaptchaController {


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取图形验证码
     * @param response
     * @param key
     * @throws Exception
     */
    @RequestMapping(value = "/captcha", method = RequestMethod.POST)
    public void appCaptcha(HttpServletResponse response,
                           @RequestParam("key") @NotNull(message = "key不能为空") String key) throws Exception {
        ImgVerifyCode ivc = new ImgVerifyCode();     //使用验证码类，生成验证码类对象
        BufferedImage image = ivc.getImage();  //获取验证码
        ivc.output(image, response.getOutputStream());//将验证码图片响应给客户端
        redisTemplate.opsForValue().set(key, ivc.getText(), 3, TimeUnit.MINUTES);
    }
}
