package shop.alien.gateway.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import shop.alien.entity.result.R;
import shop.alien.gateway.config.BaseRedisService;
import shop.alien.gateway.util.Base64;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author ssk
 * @version 1.0
 * @date 2025/10/31 14:12
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaImageController {

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

    @Autowired
    private BaseRedisService redisCache;

    /**
     * 5分钟
     */
    private Long CAPTCHA_EXPIRATION = 5 * 60 * 1000L;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Mono<R<Map<String, String>>> getCode() {
        Map<String, String> resultMap = new HashMap<>();
        // 保存验证码信息
        String uuid = UUID.randomUUID().toString();
        String verifyKey = "captcha_codes:" + uuid;
        String capStr, code;
        BufferedImage image;
        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);
        redisCache.setString(verifyKey, code, CAPTCHA_EXPIRATION);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return Mono.just(R.fail("验证码生成失败"));
        }
        resultMap.put("uuid", uuid);
        resultMap.put("img", "data:image/gif;base64," + Base64.encode(os.toByteArray()));
        return Mono.just(R.data(resultMap));
    }

}