package com.tzy.framework.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.tzy.common.dto.InDto;
import com.tzy.common.dto.OutDTO;
import com.tzy.common.utils.StringUtils;
import com.tzy.common.utils.http.HttpUtils;
import com.tzy.common.utils.spring.SpringUtils;
import com.tzy.framework.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
//@Component
public class ApiVersionAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        init(response);//设置跨域等问题
        System.out.println("拦截器访问方法："+request.getServletPath());
        String hversion = request.getHeader("version");
        if(StringUtils.isEmpty(hversion)){
            //没有版本号 判定为异常请求
            OutDTO outDTO = OutDTO.error(900, "异常请求");
            response.getWriter().println( JSONObject.toJSONString(outDTO));
            response.getWriter().flush();
            return false;
        }
        //请求数据
        RequestWrapper requestWrapper = new RequestWrapper(request);
        String body = requestWrapper.getBody();
        if(StringUtils.isNotEmpty(body)){
            try{
                InDto inDto = JSONObject.parseObject(body, InDto.class);
                String version = inDto.getVersion();
                if(StringUtils.isEmpty(version)){
                    //没有版本号 判定为异常请求
                    OutDTO outDTO = OutDTO.error(901, "异常请求");
                    response.getWriter().println( JSONObject.toJSONString(outDTO));
                    response.getWriter().flush();
                    return false;
                }
                //判断请求的版本的状态
                String versionStatus = (String) redisUtils.get("version_status_" + version);
                if(StringUtils.isEmpty(versionStatus)){
                    OutDTO outDTO = OutDTO.error(901, "异常请求");
                    response.getWriter().println( JSONObject.toJSONString(outDTO));
                    response.getWriter().flush();
                    return false;
                }
                if("private".equals(versionStatus)){
                    //如果是私有更新包 跳转到测试服务
                    Enumeration<String> headerNames = request.getHeaderNames();
                    Map<String, String> map = new HashMap<String, String>();
                    while (headerNames.hasMoreElements()) {
                        String key = headerNames.nextElement();
                        String value = request.getHeader(key);
                        map.put(key, value);
                    }
                    String post = HttpUtils.httpRequest("", "POST", body, map);
                    response.getWriter().println(post);
                    response.getWriter().flush();
                    return false;
                }

            }catch (Exception e ){
                e.printStackTrace();
                OutDTO outDTO = OutDTO.error(901, "异常请求");
                response.getWriter().println( JSONObject.toJSONString(outDTO));
                response.getWriter().flush();
                return false;
            }
        }
        System.out.println("请求参数>> "+body);
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
    {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    private HttpServletResponse init(HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        return response;
    }

}
