package com.schisandra.auth.application.controller;

import cn.hutool.core.lang.UUID;
import com.schisandra.auth.application.dto.SchisandraCaptchaDTO;
import com.schisandra.auth.common.entity.CaptchaResult;
import com.schisandra.auth.common.redis.RedisUtil;
import com.schisandra.auth.common.utils.RotateImageUtils;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnailator;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/ReactRotateCaptcha/")
@Slf4j
public class ReactRotateCaptchaController {

    @Resource
    private RedisUtil redisUtil;

    public final String authRotateCaptchaPrefix = "auth.rotate.captcha";


    /**
     * @description: 获取图片
     * @param: []
     * @return: java.lang.String
     * @author zlg
     * @date: 2024/5/10 16:28
     */
    @GetMapping("get")
    public CaptchaResult get() throws Exception {
        RotateImageUtils rotateImageUtils = new RotateImageUtils();
        CompletableFuture<HashMap> futurePrice = CompletableFuture.supplyAsync(() -> {
            HashMap<String, String> map = new HashMap<>();
            try {
                SecureRandom random = new SecureRandom();
                double randomNumber = random.nextInt(280) + 40;
                InputStream inputStream = ReactRotateCaptchaController.class.getClassLoader().getResourceAsStream("image/cropped_image.png");
                BufferedImage image = ImageIO.read(inputStream);
                String token = UUID.randomUUID().toString();
                String prefix = redisUtil.buildKey(authRotateCaptchaPrefix, token);
                redisUtil.setNx(prefix, String.valueOf(randomNumber), 60L, TimeUnit.SECONDS);
                BufferedImage image1 = rotateImageUtils.rotateImage(image, randomNumber);
                String img = RotateImageUtils.BufferedImageToBase64(image1);
                map.put("token", token);
                map.put("str", img);
            } catch (Exception e) {
                log.error("ReactRotateCaptchaController.get.error:{}", e.getMessage(), e);
            }
            return map;
        });
        return CaptchaResult.ok(futurePrice.join());
    }


    /**
     * @description: 验证图片
     * @param: [token, num]
     * @return: com.schisandra.auth.common.bo.Result
     * @author zlg
     * @date: 2024/5/10 17:25
     */
    @PostMapping("verfiy")
    public CaptchaResult verfiy(@RequestBody SchisandraCaptchaDTO schisandraCaptchaDTO) {

        if (schisandraCaptchaDTO.getDeg() == null && schisandraCaptchaDTO.getToken() == null) {
            return CaptchaResult.fail();
        }
        String prefix = redisUtil.buildKey(authRotateCaptchaPrefix, schisandraCaptchaDTO.getToken());
        if (redisUtil.exist(prefix)) {
            double realNum = Double.parseDouble(redisUtil.get(prefix));
            if (Math.abs(realNum - schisandraCaptchaDTO.getDeg()) / realNum < 0.05) {
                redisUtil.del(prefix);
                return CaptchaResult.ok();
            } else {
                return CaptchaResult.fail();
            }
        } else {
            return CaptchaResult.fail();
        }
    }
}
