package cn.iocoder.yudao.module.server.service.policycommunications;

import cn.iocoder.yudao.module.server.controller.admin.policycommunications.vo.CaptchaImageRespDTO;
import cn.iocoder.yudao.module.system.framework.captcha.core.RedisCaptchaServiceImpl;
import com.anji.captcha.service.CaptchaCacheService;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Base64;
import java.util.UUID;

@Slf4j
@Service
public class TraditionalCaptchaService {

    @Resource(name = "numberCaptchaProducer")
//    @Resource(name = "mathCaptchaProducer")
    private Producer captchaProducer;

    @Resource  // 芋道的RedisService
    private CaptchaCacheService redisService;

    // 验证码缓存前缀
    private static final String CAPTCHA_KEY = "policy:captcha:";
    // 验证码过期时间5分钟
    private static final Long CAPTCHA_EXPIRE = Duration.ofMinutes(5).toMillis();

    /**
     * 生成验证码图片
     */
    public CaptchaImageRespDTO generateCaptchaImage() {
        // 生成验证码文本
        String captchaText = captchaProducer.createText();
        String uuid = UUID.randomUUID().toString();

        log.debug("生成验证码: {}, UUID: {}", captchaText, uuid);

        // 使用芋道的RedisService存储
        String cacheKey = buildCaptchaKey(uuid);
        redisService.set(cacheKey, captchaText, CAPTCHA_EXPIRE);

        // 生成图片
        BufferedImage image = captchaProducer.createImage(captchaText);

        CaptchaImageRespDTO respDTO = new CaptchaImageRespDTO();
        respDTO.setUuid(uuid);
        respDTO.setImg(convertImageToBase64(image));

        return respDTO;
    }

    /**
     * 验证验证码
     */
    public boolean verifyCaptcha(String uuid, String code) {
        if (uuid == null || code == null) {
            return false;
        }

        String cacheKey = buildCaptchaKey(uuid);
        String cachedCode = redisService.get(cacheKey);

        if (cachedCode == null) {
            log.warn("验证码已过期或不存在, UUID: {}", uuid);
            return false;
        }

        // 验证码（忽略大小写）
        boolean success = cachedCode.equalsIgnoreCase(code);

        // 无论成功与否，都删除验证码（一次性使用）
        redisService.delete(cacheKey);

        if (!success) {
            log.warn("验证码验证失败, UUID: {}, 输入: {}, 正确: {}", uuid, code, cachedCode);
        }

        return success;
    }

    /**
     * 构建验证码缓存key
     */
    private String buildCaptchaKey(String uuid) {
        return CAPTCHA_KEY + uuid;
    }

    /**
     * 将BufferedImage转换为base64字符串
     */
    private String convertImageToBase64(BufferedImage image) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", os);
            String base64 = Base64.getEncoder().encodeToString(os.toByteArray());
            return "data:image/jpeg;base64," + base64;
        } catch (IOException e) {
            log.error("转换验证码图片失败", e);
            e.printStackTrace();
        }
        return null;
    }
}