package com.szxgl.nft.filter;

import com.alibaba.fastjson.JSONObject;

import com.szxgl.nft.entity.UserDO;
import com.szxgl.nft.service.UserService;
import com.szxgl.nft.utils.URIUtil;
import com.szxgl.nft.utils.Utility;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;


import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

/**
 * 授权测试
 * @author leiyun
 * @datetime 2017年4月27日 下午4:05:24
 */
@WebFilter("*.html")
@Slf4j
public class WebAuthFilter implements Filter {

	private static final String default_appid = "wx35766a64d73d08a9";

	private static final  String key = "fbc35e02df8a4fae9f9f827156acd91e";

	private static final  String projectId = "20210001000100011";

	private static final  String default_scope = "snsapi_base";

	private static final  String api_domain = "https://wx.xfhd.net/thirdparty";

//    private static String default_appid = "wx35766a64d73d08a9";
//    private static String key = "adsagdagefghfhgffsghdfsgd";
//	private static String projectId = "20210726175101606";
//    private static String default_scope = WxConsts.OAuth2Scope.SNSAPI_USERINFO;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		System.out.println("xxx");
		log.info("微信配置：appid: {} key: {} projectId: {} scope: {} apidomain: {}",default_appid,key,projectId,default_scope,api_domain);
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Cache-Control", "no-store");

        if(request.getServletPath().startsWith("/druid")){
        	chain.doFilter(request, response);
    		return;
        }

//        log.info("default_appid:"+default_appid);
//        log.info("key:"+key);
//        log.info("projectId:"+projectId);
//        log.info("default_scope:"+default_scope);
//        log.info("api_domain:"+api_domain);

        // Mozilla/5.0 (Linux; Android 4.4.4; iToolsVM Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 MicroMessenger/6.3.31.940 NetType/WIFI Language/zh_CN
        // 每次授权成功后发现会有重复的请求进来，IP为微信上海服务器的IP，useragent包含iToolsVM，暂不明原因，所以直接过滤掉
        if(StringUtils.trimToEmpty(request.getHeader("User-Agent")).toLowerCase().contains("itoolsvm")){
        	log.info("请求User-Agent包含iToolsVM，判断为微信服务器发来的请求，直接过滤掉，请求IP为: "+ Utility.getReqIpAddr(request));
        	return;
        }

        String appid = request.getParameter("appid");
        String scope = request.getParameter("scope");
		if(StringUtils.isBlank(appid))appid=default_appid;
        if(StringUtils.isBlank(scope))scope=default_scope;

		ServletContext context = request.getServletContext();
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);

        String httpRequestFullURL = getHttpRequestFullURL(request);
        log.info(httpRequestFullURL);

//        String api_domain = request.getScheme()+"://"+request.getServerName()+(request.getServerPort()==80?"":":"+request.getServerPort())+request.getContextPath();
		String redirectUrl = api_domain+"/webauth/api/oauth"+"?projectId="+projectId+"&appid="+appid+"&redirect_uri="+ URIUtil.encodeURIComponent(httpRequestFullURL)+"&scope="+ scope;
		String code = request.getParameter("code");
    	if(StringUtils.isNotEmpty(code)){
    		String url = api_domain+"/webauth/api/oauthInfo"+"?appid="+appid+"&authCode="+key+"&code="+code+"&scope="+ scope;
			try {
				JSONObject json = httpRequest(url, "POST", null);
				if(json==null || json.getIntValue("errcode") == 40029 || json.getIntValue("errcode") == 40163){ // invalid code 重新发起授权\
					log.info("errcode == 40029|40163, 重新跳转授权 ......");
					response.sendRedirect(redirectUrl);
		    		return;
				}
				log.info("微信授权获取到用户openid: "+json);
				UserDO userDO = JSONObject.parseObject(json.getString("data"), UserDO.class);
				System.out.println(json);
				Utility.addCookie(request, response, "openid", userDO.getOpenid());
				if(ctx != null){
					UserService userService = ctx.getBean(UserService.class);
					UserDO userDo = userService.getUserDo(userDO.getOpenid());
					//用户信息是否存在
					if(userDo == null){
						userDO.setCreateTime(new Date());
						userService.addUser(userDO);
					}
				}else {
					log.error("applicationContext空指针");
				}

			} catch (Exception e) {
				log.error("授权失败：", e);
                throw new RuntimeException(e);
			}
    	}else{
    		response.sendRedirect(redirectUrl);
    		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();
        }
    }


	private static JSONObject httpRequest(String requestUrl, String requestMethod, String postData) throws IOException {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
	//	log.info("httpRequestUrl: "+requestUrl+", postData: "+postData);
		URL url = new URL(requestUrl);
		HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
		httpUrlConn.setConnectTimeout(10000);
		httpUrlConn.setDoOutput(true);
		httpUrlConn.setDoInput(true);
		httpUrlConn.setUseCaches(false);
		//设置请求方式（GET/POST）
		httpUrlConn.setRequestMethod(requestMethod);
		if ("GET".equalsIgnoreCase(requestMethod)){
			httpUrlConn.connect();
		}
		//当有数据需要提交时
		if (postData != null){
			OutputStream outputStream = httpUrlConn.getOutputStream();
			outputStream.write(postData.getBytes("UTF-8"));
			outputStream.close();
			outputStream=null;
		}
		//将返回的输入流转换成字符串
		InputStream inputStream = httpUrlConn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		for (String str = null; (str = bufferedReader.readLine()) != null;)
			buffer.append(str);

		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
		inputStream = null;
		httpUrlConn.disconnect();
		jsonObject = JSONObject.parseObject(buffer.toString());
		return jsonObject;
	}

}