package com.erp.user.service.auth.impl;

import com.erp.user.service.auth.CaptchaService;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.time.Duration;
import java.util.UUID;

/**
 * 图形验证码服务实现
 */
@Slf4j
@Service
public class CaptchaServiceImpl implements CaptchaService {
    
    private static final String CAPTCHA_PREFIX = "captcha:";
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;
    private static final int EXPIRY_MINUTES = 5;
    
    private final RedisTemplate<String, Object> redisTemplate;
    
    public CaptchaServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    
    @Override
    public CaptchaData generate() {
        // 生成验证码
        SpecCaptcha captcha = new SpecCaptcha(WIDTH, HEIGHT, CODE_LENGTH);
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        captcha.setLen(CODE_LENGTH);
        
        // 获取验证码文本
        String code = captcha.text();
        String key = UUID.randomUUID().toString();
        
        // 存储到Redis
        String redisKey = CAPTCHA_PREFIX + key;
        redisTemplate.opsForValue().set(redisKey, code.toLowerCase(), Duration.ofMinutes(EXPIRY_MINUTES));
        
        // 使用out方法获取图片字节
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        captcha.out(baos);
        byte[] imageBytes = baos.toByteArray();
        
        // 将字节数组转换为BufferedImage（用于后续处理）
        BufferedImage image = null;
        try {
            image = javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(imageBytes));
        } catch (Exception e) {
            log.error("图片转换失败", e);
        }
        
        log.debug("图形验证码生成: key={}, code={}", key, code);
        
        return new CaptchaData(image, key);
    }
    
    @Override
    public boolean verify(String key, String code) {
        if (key == null || code == null) {
            return false;
        }
        
        String redisKey = CAPTCHA_PREFIX + key;
        Object value = redisTemplate.opsForValue().get(redisKey);
        
        if (value == null) {
            log.warn("图形验证码不存在或已过期: key={}", key);
            return false;
        }
        
        String expectedCode = value.toString().toLowerCase();
        String inputCode = code.toLowerCase().trim();
        
        // 验证后删除
        redisTemplate.delete(redisKey);
        
        if (expectedCode.equals(inputCode)) {
            log.debug("图形验证码验证成功: key={}", key);
            return true;
        }
        
        log.warn("图形验证码错误: key={}, expected={}, input={}", key, expectedCode, inputCode);
        return false;
    }
}
