package com.ozs.gateway.filter;

import javax.servlet.http.HttpServletRequest;

import com.ozs.gateway.util.AccountService;
import com.ozs.gateway.util.IPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

public class AccessFilter extends ZuulFilter {

	private final Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private AccountService accountService;

	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		log.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());
		log.info("发送请求的IP: {}", IPUtil.getIPAddress(request));
		log.info("判断header中有没有数据：{}", request.getHeader("Accept"));
		Boolean isLoginUrl = false;

		ctx.getResponse().setHeader("Access-Control-Allow-Origin", "*");
		ctx.getResponse().setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
		ctx.getResponse().setHeader("Access-Control-Max-Age", "3600");
		ctx.getResponse().setHeader("Access-Control-Allow-Headers",
				"Cache-Control,Content-Type,Authorization,X-Requested-With,token");
		ctx.getResponse().setHeader("Access-Control-Allow-Credentials", "true");
		ctx.getResponse().setHeader("Access-Control-Expose-Headers", "Cache-Control,token");
		if (request.getRequestURL().toString().contains("accountInfo/loginChecking")
				&& request.getHeader("Accept").equals("*/*")) {
			isLoginUrl = true;
		}
		if (request.getMethod().equals("OPTIONS") || isLoginUrl) {

			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(200);
			return null;
		}

		if (request.getRequestURL().toString().contains("swagger")
				|| request.getRequestURL().toString().contains("api-docs")
				|| request.getRequestURL().toString().contains("/account/parseTokenId")
				|| request.getRequestURL().toString().contains("/account/ifAuthCodeCorrect")// 验证码接口
				|| request.getRequestURL().toString().contains("/account/authCode")// 验证码接口
				|| request.getRequestURL().toString().contains("storageManage/downloadTemplateColums")// 向导建表模板下载接口
				|| request.getRequestURL().toString().contains("dataQuality/downloadTemplateData")// 数据质量管理数据模板下载接口
				|| request.getRequestURL().toString().contains("account/login")
				|| request.getRequestURL().toString().contains("/appshow/chartInfo/loadRichTextFile")// 富文本文件上传
				|| request.getRequestURL().toString().contains("/appshow/import/")// 文件读取
				|| request.getRequestURL().toString().contains("/iframe/report/")
				|| request.getRequestURL().toString().contains("/report/view")
				|| request.getRequestURL().toString().contains("/report/getReportData")
				|| request.getRequestURL().toString().contains("report/downloadReportFile")
		) {
			return null;
		}
		boolean result = true;
		// redis中验证请求中用户名和token是否正确，不正确返回到登录页面
		String token = request.getHeader("token");

		String accountId = null;
		Object tokenNow = null;
		if (token != null && !token.equals("{token}")) {
			accountId = accountService.parseTokenId(token);
			if (accountId != null) {
				tokenNow = accountService.getTokenByAccountId(accountId);
			}
			log.info("run token: {}", token);
			log.info("run tokenNow: {}", tokenNow);
			log.info("result: {}", result);
		}
		if (token == null || accountId == null || tokenNow == null || !tokenNow.toString().equals(token)) {
			result = false;
		}
		if (!result) {
			// 跳转回登录页面
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(200);
			ctx.setResponseBody("{\"msg\":\"token或秘钥不正确!\",\"code\":\"403\"}");
			ctx.getResponse().setContentType("application/json;charset=UTF-8");
			return null;
		}
		ctx.addZuulRequestHeader("token", token);
		// 刷新token时间
		accountService.refreshToken(accountId, 30);
		ctx.getResponse().setHeader("token", token);
		return null;
	}

	@Override
	public boolean shouldFilter() {

		return true;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public String filterType() {
		return "pre";
	}

}
