package cn.palmte.work.config.interceptor;

import cn.palmte.work.bean.ResponseMsg;
import cn.palmte.work.config.Constant;
import cn.palmte.work.config.log.LogExcluder;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import top.jfunc.token.TokenManager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static cn.palmte.work.config.Constant.HEADER_TOKEN;


/**
 * @author xiongshiyan
 */
public abstract class AbstractLoginInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AbstractLoginInterceptor.class);

    protected void printNeccery(HttpServletRequest request, LogExcluder logExcluder) {
        //拦截特殊字符
        String[] specialStr = {"|", "&", ";", "$", "%", "@", "'", "\"", "\\'", "\\\"", "<", ">", "(", ")", "+", "CR", "LF", ",", "\\"};
        for (String s : specialStr) {
            if (request.getRequestURI().contains(s)) {
                logger.info("uri:" + request.getRequestURI() + "含有特殊字符:" + s);
                return;
            }
        }
        if (logExcluder.needExcluded(request.getRequestURI())) {
            return;
        }

        logger.info("uri:" + request.getRequestURI() + ",token:" + request.getHeader(HEADER_TOKEN));
    }

    protected boolean verifyLogin(HttpServletResponse response, TokenManager<?> tokenManager, String token, boolean cors) throws IOException {
        /// Object o = tokenManager.findByToken(token);
        boolean exist = tokenManager.existByToken(token);
        if (!exist) {
            promptLogin(response, cors);
            return false;
        } else {
            tokenManager.updateExpires(token);
            return true;
        }
    }

    protected boolean verifyLogin(HttpServletResponse response, TokenManager<String> tokenManager, String token, boolean cors, String phone) throws IOException {
        if (null == phone) {
            promptLogin(response, cors);
            return false;
        } else {
            tokenManager.updateExpires(token);
            return true;
        }
    }

    protected void promptLogin(HttpServletResponse response, boolean cors) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (cors) {
            cors(response);
        }
        response.getWriter().write(JSON.toJSONString(ResponseMsg.buildMsg(Constant.Status.STATUS_PROMPT_LOGIN, "login first please", "")));
    }

    protected void promptNoPermission(HttpServletResponse response, boolean cors) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (cors) {
            cors(response);
        }
        response.getWriter().write(JSON.toJSONString(ResponseMsg.buildMsg(Constant.Status.STATUS_PROMPT_UNAUTH, "you have no permission", "")));
    }

    protected void promptLogin(HttpServletResponse response) throws IOException {
        promptLogin(response, false);
    }

    /**
     * 处理跨域
     *
     * @param response HttpServletResponse
     */
    private void cors(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
    }
}