package com.xhkjedu.sstudy.interceptors;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.config.MissingParametersException;
import com.xhkjedu.sstudy.utils.JedisUtil;
import com.xhkjedu.sstudy.utils.StudyUtil;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@Slf4j
public class RequestInterceptor extends JedisUtil implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // 请求结束时间
        Long endTime = System.currentTimeMillis();
        // 从HttpServletRequest获取开始时间
        Long startTime = (Long) arg0.getAttribute("_startTime");
        double time = ((endTime - startTime) * 1.000) / 1000;
        // 打印接口信息及耗时
        if (time > 1) {
            log.error(" {}；耗时：{}s", arg0.getRequestURI(), time);
        }
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {

    }

    /**
     * 在调用controller具体方法前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("请求的uri:" + request.getRequestURI());
        response.setHeader("Access-Control-Allow-Origin", "*");
        //response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setContentType("application/json;charset=UTF-8");

        // 记录请求开始时间
        request.setAttribute("_startTime", System.currentTimeMillis());
        String requestURI = request.getRequestURI();
        String key = request.getHeader("Token-Key");
        String token = request.getHeader("Token-Value");
        if (!requestURI.contains("user/login") && !requestURI.endsWith("/get_new")
                && N_Utils.isNotEmpty(key) && N_Utils.isNotEmpty(token)) {//非登录和获取最新版本相关接口验证token
            String redis_token = get(key);//系统缓存中保存的token
            if (!token.equals(redis_token)) {
                ResultVo result = new ResultVo();
                result.setCode(2);
                result.setMsg("登录失效");

                response.getWriter().print(JSON.toJSONString(result));
                return false;
            }
        }

        if (interceptorApi(requestURI)) {//需要拦截的请求
            String encoding = request.getCharacterEncoding();
            int contentLength = request.getContentLength();
            byte buffer[] = new byte[request.getContentLength()];
            request.getInputStream();
            for (int i = 0;i < contentLength;) {

                int readLen = request.getInputStream().read(buffer, i, contentLength - i);
                if (readLen == -1) {
                    break;
                }
                i += readLen;
            }
            if (encoding == null) {
                encoding = "UTF-8";
            }
            String params = new String(buffer, encoding);
            Map<String, String> uriMap = StudyUtil.uriMap;
            String params2 = uriMap.get(requestURI);
            if (N_Utils.isNotEmpty(params2) && params2.equals(params)) {
                log.error("地址：{}，参数：{}",requestURI,params);
                throw new MissingParametersException("提交过快，请稍后重试");
            } else {
                uriMap.put(requestURI, params);
            }
        }
        return true;
    }

    /**
     * 需要拦截的请求
     * @Param [uri]
     * @Author ywx
     * @Date 2020/5/20 14:14
     * @return java.lang.Boolean
     **/
    private Boolean interceptorApi(String uri) {
        boolean rtn = false;
        String[] url = new String[]{
                "/ps/start_paper",//题库作业--开始做作业
                "/ps/sstart_paper",//图片作业--开始做作业
                "/psw/sstart_paper",//图片作业--开始做作业
                "/psw/start_paper",//题库作业--开始做作业
                "/resource/add",//资源--添加
                "/recite/save",//背诵--添加
                "/ps/submit_question",//作业--提交单题
                "/ps/submit_paper",//作业--提交
                "/ps/ssubmit_question",//图片作业--提交单题
                "/ps/ssubmit_paper",//图片作业--提交
                "/ps/scorrect",//答题卡--批改
                "/ps/correc",//试题库--批改
                "/paper/saves",//答题卡--保存
                "/paper/saveq",//试题库--保存
                "/pg/save",//作业--发布
                "/question/add",//试题--添加
                "/basket/add",//试题篮--添加
                "/recites/up",//背诵--学生保存
                "/question_class/end_correct" //试题--批阅完成
        };

        for (int i = 0; i < url.length; i++) {
            String urlstr = "/sstudy"+url[i];
            if (uri.equals(urlstr)) {
                rtn = true;
                break;
            }
        }

        return rtn;
    }

}
