package com.ff.weijinxiao.jwt;


import com.ff.weijinxiao.domain.SystemLog;
import com.ff.weijinxiao.domain.User;
import com.ff.weijinxiao.service.SystemLogService;
import com.ff.weijinxiao.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class CorsFilter implements Filter {

    @Resource
    private SystemLogService systemLogService;

    @Resource
    private UserService userService;

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

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String method = request.getMethod();
        if (null != method && "OPTIONS".equals(method)) {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "token,Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true"); //是否支持cookie跨域
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String url = request.getServletPath();
        getRemoteIP(request);
        if (isWhiteListUrl(url)) {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "token,Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true"); //是否支持cookie跨域
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //filterChain.doFilter(servletRequest, servletResponse);//remove after testing

        String token = request.getHeader("token");
        if (null == token || "null".equals(token)) {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "token");
            response.setHeader("Access-Control-Allow-Credentials", "true"); //是否支持cookie跨域
            response.setHeader("Access-Control-Expose-Headers", "sessiontimeout");
            response.setHeader("sessiontimeout", "true");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "登录超时或者未授权");
            return;
        }
        String account = "";
        if (token != null && token.length() > 0) {
            account = JwtHelper.parseToken(token);
            if (null == account || (null != account && account.length() == 0)) {
                response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "token");
                response.setHeader("Access-Control-Allow-Credentials", "true"); //是否支持cookie跨域
                response.setHeader("Access-Control-Expose-Headers", "sessiontimeout");
                response.setHeader("sessiontimeout", "true");
                response.sendError(HttpStatus.UNAUTHORIZED.value(), "登录超时或者未授权");
                return;
            }
        }
        //account = "admin"; for local testing

        if (null != account && account.length() > 0) {
            //记录日志
            if (url.contains("update") || url.contains("create") || url.contains("set") || url.contains("delete") || url.contains("forsale") || url.contains("reject") || url.contains("approve") || url.contains("modify")) {
                SystemLog systemLog = new SystemLog();
                User user = userService.findUserByAccount(account);
                if (null != user) {
                    systemLog.setLogUser(user.getName());
                }
                systemLog.setLogAccount(account);
                systemLog.setLogUrl(url);
                systemLog.setLogIp(getRemoteIP(request));
                systemLogService.save(systemLog);
            }

            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "token,Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true"); //是否支持cookie跨域
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "token");
            response.setHeader("Access-Control-Allow-Credentials", "true"); //是否支持cookie跨域
            response.setHeader("Access-Control-Expose-Headers", "sessiontimeout");
            response.setHeader("sessiontimeout", "true");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "登录超时或者未授权");
        }


    }

    private boolean isWhiteListUrl(String url) {
        if (url.equals("/api/user/login") || url.equals("/api/user/logout") || url.equals("/api/file/getbyattachid") || url.contains("test")
                || url.equals("/api/cuser/wxapi/getopenid") || url.equals("/api/file/getimg") || url.contains("/notify/order") || url.contains("/wxapi/getSmsCode") || url.contains("/wxapi/login")
                || url.startsWith("/swagger") || url.startsWith("/webjars/springfox-swagger-ui") || url.equals("/v2/api-docs")) {
            return true;
        } else {
            return false;
        }

    }

    private boolean hasPermission(String url, String account) {

        return true;
    }

    @Override
    public void destroy() {

    }

    public String getRemoteIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
