package org.springblade.common.interceptor;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.IPUtils;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * 拦截站外请求过滤器
 */
@Component
@Slf4j
public class IPHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String remoteIp = IPUtils.getIP(request);
        String ipMonitorBaseUrl = "https://ip.taobao.com/outGetIpInfo?";
        String url = ipMonitorBaseUrl + "ip="+remoteIp + "&accessKey=alibaba-inc";
        String result = HttpUtil.get(url);
        JSONObject resultJSON = JSONUtil.parseObj(result);
        JSONObject data = resultJSON.getJSONObject("data");
        String country = data.getStr("country");
        String isp = data.getStr("isp");
        log.error("=======================当前登录IP为：" + remoteIp + "=======================");
        if(StringUtil.isNotBlank(country) && country.equals("中国")){
            return true;
        }else if(StringUtil.isNotBlank(isp) && isp.equals("内网IP")){
            return true;
        }else{
            log.error("=======================当前非法登录IP为：" + remoteIp + "=======================");
            return setResponse(JsonUtil.toJson(R.fail("访问IP不允许，请更换中国境内IP访问")), response);
        }
    }

    private boolean setResponse(String message, HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = null;
        try {
            response.setHeader("Content-type", "application/json; charset=utf-8");
            outputStream = response.getOutputStream();
            outputStream.write(message.getBytes("UTF-8"));
        } catch (Exception ex) {
            return false;
        } finally {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        }
        return false;
    }
}
