package cn.quantgroup.xyqb.controller.external.captcha;

import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.aspect.captcha.CaptchaValidator;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.thirdparty.jcaptcha.AbstractManageableImageCaptchaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 类名称：ImgCaptchaController
 * 类描述：图形验证码控制器
 *
 * @author 李宁
 * @version 1.0.0 创建时间：15/11/17 11:49 修改人： 修改时间：15/11/17 11:49 修改备注：
 */
@Api(value = "/api", description = "叫Api, 实际上是图形验证码. 你说神奇不神奇...")
@Slf4j
@RestController
@RequestMapping("/api")
public class ImageCaptchaController {

    @Autowired
    @Qualifier("stringRedisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    private static final String IMAGE_FORMAT_PNG = "png";
    private static final String IMG_BASE64_PATTREN = "data:image/" + IMAGE_FORMAT_PNG + ";base64,%s";

    @Autowired
    @Qualifier("customCaptchaService")
    private AbstractManageableImageCaptchaService imageCaptchaService;

    /**
     * 获取验证码
     * 默认匹配 GET /captcha, 提供4位数字和字母混合图片验证码
     */
    @RequestMapping(value = "/captcha")
    @ApiOperation(value = "获取验证码", notes = "获取图形验证码接口, 会返回一个base64的图形验证码", httpMethod = "GET")
    public JsonResult fetchCaptcha(HttpServletRequest request) {
        String imageId = UUID.randomUUID().toString();
        BufferedImage challenge = imageCaptchaService.getImageChallengeForID(Constants.IMAGE_CAPTCHA_KEY + imageId, request.getLocale());
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(challenge, IMAGE_FORMAT_PNG, jpegOutputStream);
        } catch (IOException e) {
            log.error("图形验证码图片流返回失败", e);
            return JsonResult.buildErrorStateResult("", Constants.CHECK_FAIL);
        }
        String imageBase64 = Base64.encodeBase64String(jpegOutputStream.toByteArray());
        Map<String, String> data = new HashMap<>();
        data.put("imageId", imageId);
        data.put("image", String.format(IMG_BASE64_PATTREN, imageBase64));
        redisTemplate.opsForValue().set(Constants.IMAGE_CAPTCHA_REDIS_CACHE_KEY.concat(imageId),"1",Constants.IMAGE_CAPTCHA_REDIS_CACHE_TIME_OUT,TimeUnit.MINUTES);
        return JsonResult.buildSuccessResult("", data);
    }

    /**
     * 图片验证码验证
     * 注意：本方法有中间层在用，用于QG图形验证码检验
     */
    @CaptchaValidator
    @RequestMapping("/verification_image_code")
    @ApiOperation(value = "验证图形验证码", notes = "验证图形验证码", httpMethod = "POST")
    public JsonResult verificationImageCode() {
        return JsonResult.buildSuccessResult("", null);
    }
}
