package com.nbclass.shiro.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 找回密码链接验证
 * @author Leon
 * @datetime 2019年5月2日 下午6:59:01
 */
public class ResetPwdUrlFilter extends AccessControlFilter {

	protected static Logger logger = LoggerFactory.getLogger(ResetPwdUrlFilter.class);
	
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    	logger.info("ResetPwdUrlFilter.isAccessAllowed ......");
    	String verifyCode = request.getParameter("verifyCode");
    	if(StringUtils.isBlank(verifyCode)){
    		logger.info("进入重置密码页面，参数[verifyCode]为null ......");
    		outPrintError(response, "The requested URL was not found on this server.");
        	return false;
    	}
    	/*
    	CustomerMapper customerMapper = SpringContextHolder.getBean(CustomerMapper.class);
    	try{
	    	// 查询验证码是否有效，半小时重置密码才有效
			CustomerResetPwd customerResetPwd = customerMapper.selectResetPwd(verifyCode);
			if(customerResetPwd == null || customerResetPwd.getStatus() == null || customerResetPwd.getStatus() != 1){
				logger.info("进入重置密码页面，验证码已失效[verifyCode="+verifyCode+"].");
	    		outPrintError(response, "The requested URL was not found on this server.");
	        	return false;
			}
    	}finally{
    		customerMapper = null;
    	}
    	*/
    	return true;
    }

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		return false;
	}
    
	public void outPrintError(ServletResponse response, String result) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = null;
		try {
			String html = "<!DOCTYPE html><html><head>";
			html += "<title>Error 404 (Not Found)</title>";
			html += "<meta charset=\"utf-8\">";
			html += "<meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1\">";
			html += "</head><body>";
			html+="<center><div style=\"width:85%; text-align:center; font-size: 16px; line-height:35px;\">";
			html += result;
			html+="</div></center></body></html>";
			out = response.getWriter();
			out.print(html);
		} catch (IOException e) {
			logger.error("IO工作流出现异常!", e);
		} finally {
			if(out!=null){
				out.close();
				out = null;
			}
		}
    }


}
