package com.fdage.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * Created by Hb_zzZ on 2019/4/29.
 */
public class VerifyCodeUtil {

    public static String validImage(HttpServletRequest request, HttpSession session) {
        String code = request.getParameter("code");
        Object verCode = session.getAttribute("verCode");
        if (null == verCode) {
            request.setAttribute("errmsg", "验证码已失效，请重新输入");
            return "-1";
//            return "验证码已失效，请重新输入";
        }
        String verCodeStr = verCode.toString();
        LocalDateTime localDateTime = (LocalDateTime) session.getAttribute("codeTime");
        long past = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        if (verCodeStr == null || code == null || code.isEmpty() || !verCodeStr.equalsIgnoreCase(code)) {
            request.setAttribute("errmsg", "验证码错误");
            return "-2";
//            return "验证码错误";
        } else if ((now - past) / 1000 / 60 > 5) {
            request.setAttribute("errmsg", "验证码已过期，重新获取");
            return "-3";
//            return "验证码已过期，重新获取";
        } else {
            //验证成功，删除存储的验证码
            session.removeAttribute("verCode");
            return "200";
        }
    }
}
