package com.nbclass.szxgl.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.nbclass.shiro.config.MyUsernamePasswordToken;
import com.nbclass.szxgl.constant.ActivityConstants;
import com.nbclass.util.CommonUtils;
import com.nbclass.util.HttpUtils;

/**
 * 企业微信OA页面授权
 * @author Leon
 * @datetime 2019年4月23日 下午3:01:57
 */
/*@WebFilter("*.html")*/
public class WxWorkFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(WxWorkFilter.class);

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        response.setHeader("Cache-Control", "no-store");
//
//        String httpRequestFullURL = getHttpRequestFullURL(request);
//        String redirect_uri = ActivityConstants.qywx_api_domain + "/api/oauth?agentid="+ActivityConstants.qywx_agentid+"&redirect_uri="+httpRequestFullURL;
//
//        Subject subject = SecurityUtils.getSubject();
//
//       // String userkey = (String) request.getSession().getAttribute(ActivityConstants.session_key_user_id);
//       // logger.info("[企业微信授权拦截器] userkey="+userkey+", requrl: "+httpRequestFullURL);
//
//        if(subject.isAuthenticated()){ // 已登录状态
//        	chain.doFilter(request, response);
//        	return;
//        }
//
//        String key = StringUtils.trimToEmpty(request.getParameter("key"));
//        if("xglgg".equals(key)){ // 测试时传key绕过登录
//    		MyUsernamePasswordToken token = new MyUsernamePasswordToken("liixi"); // 免密登录
//    		token.setRememberMe(true);
//            try {
//    			subject.login(token);
//    		} catch (AuthenticationException e) {
//    			outPrintError(response, "该登录账号不存在，如有疑问请联系企业管理员！");
//    			return;
//    		}
//        	chain.doFilter(request, response);
//        	return;
//        }
//
//
//    	String code = request.getParameter("code");
//    	if(StringUtils.isBlank(code)){
//    		response.sendRedirect(redirect_uri);
//    		return;
//    	}
//
//		String url = ActivityConstants.qywx_api_domain + "/api/oauthInfo?agentid="+ActivityConstants.qywx_agentid+"&code=" + code;
//		JSONObject result = HttpUtils.httpGet(url);
//		if(result != null && result.getIntValue("ret") == 0 && StringUtils.isNotBlank(result.getString("userid"))
//				&& !"null".equalsIgnoreCase(result.getString("userid"))){
//			logger.info("企业微信授权获取到用户信息: "+result.toString());
//			String userid = result.getString("userid");
//			request.getSession().setAttribute(ActivityConstants.session_key_user_id, userid);
//
//			// OA系统shiro登录
//			MyUsernamePasswordToken token = new MyUsernamePasswordToken(userid); // 免密登录
//			token.setRememberMe(true);
//            try {
//				subject.login(token);
//			} catch (AuthenticationException e) {
//				outPrintError(response, "该登录账号不存在，如有疑问请联系企业管理员！");
//				return;
//			}
//		}else{
//			if(result!=null && (result.getIntValue("errcode") == 40029 || result.getIntValue("errcode") == 40163)){
//				logger.info("授权失败, 将重新跳转到微信授权, RedirectURL : " + redirect_uri);
//				redirect_uri = CommonUtils.removeParamValue(redirect_uri, "code");
//				response.sendRedirect(redirect_uri);
//				return;
//			}
//			outPrintError(response, "微信授权失败，你可能未关注该企业号，请关注后重试！");
//			return;
//		}
//
    	chain.doFilter(request, response);
	}

    @Override
    public void destroy() {

    }

    public static String getHttpRequestFullURL(HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
        String queryString = request.getQueryString();
        if (queryString == null) {
            return requestURL.toString();
        } else {
            return requestURL.append('?').append(queryString).toString();
        }
    }

    /**
     * 输出错误信息到页面
     * @param response
     * @param result
     */
	public void outPrintError(HttpServletResponse 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>授权失败</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: 18px; line-height:35px; color: red;\">";
			html += result;
			html+="</div></center></body></html>";
			out = response.getWriter();
			out.print(html);
		} catch (IOException e) {
			throw new RuntimeException("IO工作流出现异常!");
		} finally {
			if(out!=null){
				out.close();
				out = null;
			}
		}
    }


}
