package cn.quantgroup.xyqb.service.captcha.impl;

import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.service.captcha.IQuantgroupCaptchaService;
import cn.quantgroup.xyqb.thirdparty.jcaptcha.AbstractManageableImageCaptchaService;
import com.octo.captcha.service.CaptchaServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

/**
 * @author xufei on 2018/1/30.
 */
@Slf4j
@Service
public class QuantgroupCaptchaServiceImpl implements IQuantgroupCaptchaService {

    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;

    @Override
    public Map<String, String> fetchQuantgroupCaptcha(Locale locale) {
        String imageId = UUID.randomUUID().toString();
        BufferedImage challenge = imageCaptchaService.getImageChallengeForID(Constants.IMAGE_CAPTCHA_KEY + imageId, locale);
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(challenge, IMAGE_FORMAT_PNG, jpegOutputStream);
        } catch (IOException e) {
            log.error("生成QG图形验证码", e);
            return null;
        }
        String imageBase64 = Base64.encodeBase64String(jpegOutputStream.toByteArray());
        Map<String, String> data = new HashMap<>(2);
        data.put("imageId", imageId);
        data.put("image", String.format(IMG_BASE64_PATTREN, imageBase64));
        return data;
    }

    @Override
    public boolean validQuantgroupCaptcha(String captchaId, String captchaValue) {
        boolean validCaptcha = false;
        if (StringUtils.isNotBlank(captchaId) && StringUtils.isNotBlank(captchaValue)) {
            // 验证码校验(忽略用户输入的大小写)
            try {
                validCaptcha = imageCaptchaService.validateResponseForID(Constants.IMAGE_CAPTCHA_KEY + captchaId, captchaValue.toLowerCase());
            } catch (CaptchaServiceException e) {
                log.error("校验QG图形验证码：key:{}, code:{}", captchaId, captchaValue, e);
            }
        }
        return validCaptcha;
    }

}
