package com.kexue.skills.controller;

import com.kexue.skills.common.CommonResult;
import com.kexue.skills.common.util.IDUtils;
import com.kexue.skills.config.CaptchaConfig;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码控制器
 * @author
 */
@RestController
@RequestMapping("/api/captcha")
@CrossOrigin(origins = "*")
@Tag(name = "验证码 Api")
public class CaptchaController {

    @Resource
    private CaptchaConfig captchaConfig;

    @Resource
    private RedissonClient redissonClient;

    /**
     * 生成验证码
     * @throws IOException
     */
    @GetMapping("/generate")
    @Operation(summary = "生成验证码", description = "生成验证码")
    public CommonResult<Map<String, String>> generateCaptcha() {
        // 验证码开关逻辑：只有启用时才生成验证码
        if (!captchaConfig.isEnabled()) {
            return CommonResult.success(new HashMap<>());
        }
        
        // 生成验证码ID
        String captchaId = IDUtils.getUUID();
        
        // 生成验证码
        SpecCaptcha captcha = new SpecCaptcha(130, 48);
        // 设置验证码类型为混合类型（数字+字母）
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        // 设置验证码长度
        captcha.setLen(captchaConfig.getLength());
        // 生成验证码文字
        String captchaText = captcha.text().toLowerCase();
        
        // 将验证码存储到Redis中，使用配置的有效期
        redissonClient.getBucket("captcha:" + captchaId).set(captchaText, captchaConfig.getExpireTime(), java.util.concurrent.TimeUnit.SECONDS);
        
        // 生成验证码图片的Base64编码
        String base64Image = captcha.toBase64();
        
        // 构建返回结果
        Map<String, String> result = new HashMap<>();
        result.put("captchaId", captchaId);
        result.put("captchaImage", base64Image);
        
        return CommonResult.success(result);
    }
    
    /**
     * 验证验证码
     * @param captchaId 验证码ID
     * @param captchaValue 用户输入的验证码
     * @return
     */
    @PostMapping("/verify")
    @Operation(summary = "验证验证码", description = "验证验证码")
    public CommonResult<Boolean> verifyCaptcha(@RequestParam("captchaId") String captchaId, @RequestParam("captchaValue") String captchaValue) {
        // 验证码开关逻辑：只有启用时才验证验证码
        if (!captchaConfig.isEnabled()) {
            return CommonResult.success(true);
        }
        
        if (captchaId == null || captchaValue == null) {
            return CommonResult.failed("验证码ID和验证码值不能为空");
        }
        
        // 从Redis中获取验证码
        String captchaText = (String) redissonClient.getBucket("captcha:" + captchaId).get();
        if (captchaText == null) {
            return CommonResult.failed("验证码已过期");
        }
        
        // 验证验证码
        if (captchaText.equals(captchaValue.toLowerCase())) {
            // 验证成功后，删除验证码
            redissonClient.getBucket("captcha:" + captchaId).delete();
            return CommonResult.success(true);
        } else {
            return CommonResult.failed("验证码错误");
        }
    }
}