package com.app.framework.core.web.captcha;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.img.ImgUtil;
import com.app.framework.core.utils.request.SessionUtil;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;

/**
 * 图形验证码工具类
 *
 * 图形验证码用法：在全局配置中注册，如下：
 *
 * 	@Bean
 * 	public ServletRegistrationBean captchaServletRegistration() {
 * 		ServletRegistrationBean registration = new ServletRegistrationBean(CaptchaUtils.buildServlet());
 * 		registration.addUrlMappings("/web/captcha.jpg");
 * 		return registration;
 * 	}
 *
 * 前端用法：
 * 	<img src="${contextPath}/web/captcha.jpg" width="92" height="40" alt="点击刷新验证码"
 * 		onclick="$(this).attr('src','${contextPath}/web/captcha.jpg?timestamp='+new Date());">
 *
 * 后端输入验证：
 * 	CaptchaUtil.check(request, code);
 *
 */
public class CaptchaUtil {

    private static final String SESSION_NAME = "CaptchaCode";

    private static final int WIDTH = 100;//生成的图片的宽度
    private static final int HEIGHT = 40;//生成的图片的高度

    /**
     * 创建图形验证码Servlet
     * @return Servlet
     */
    public static Servlet buildServlet() {
        return buildServlet(WIDTH, HEIGHT);
    }

    /**
     * 创建图形验证码Servlet
     * @return Servlet
     */
    public static Servlet buildServlet(int width, int height) {
        return new HttpServlet() {
            @Override
            protected void doGet(HttpServletRequest request,
                                 HttpServletResponse response) throws IOException {
                response.setContentType("image/jpeg");
                String codeLength = request.getParameter("codeLength");
                if(StringUtils.isBlank(codeLength))codeLength = "4";

                // 产生验证码
                String code = new RandomGenerator(Integer.parseInt(codeLength)).generate();

                // 将验证码存储起来，便于用户输入之后的验证
                SessionUtil.set(request, SESSION_NAME, code);

                // 生成图形验证码
                //CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(width, height);
                LineCaptcha captcha = cn.hutool.captcha.CaptchaUtil.createLineCaptcha(width, height);
                Image image = captcha.createImage(code);

                ImgUtil.writeJpg(image, response.getOutputStream());
            }
        };
    }

    /**
     * 校验用户输入的验证码是否正确
     * @param request
     * @param code  用户输入的验证码
     * @return
     */
    public static boolean check(HttpServletRequest request, String code) {
        Object o = SessionUtil.get(request, SESSION_NAME);
        boolean equals = ObjectUtils.equals(o, code);
        if (equals) {
            SessionUtil.remove(request, SESSION_NAME);
        }
        return equals;
    }
}
