package com.yutou.tools.utils;

import com.alibaba.fastjson.JSONArray;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;

public class Tools {
    /**
     *  设置Cookie
     * @param response
     * @param key
     * @param value
     * @param time
     */
    public static void setCookie(HttpServletResponse response, String key,String value,int time) {
        Cookie cookie = new Cookie(key, value);
        if(time!=-1) {
            cookie.setMaxAge(time);
        }
        cookie.setPath("/");
        response.addCookie(cookie);

    }
    /**
     * 获取Cookie
     * @param request
     * @param key
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request,String key) {
        Cookie[] cookies = request.getCookies();
        try {
            for (Cookie cookie : cookies) {
                if (key!=null&&cookie.getName().equals(key)) {
                    return cookie;
                }
            }
        }catch (Exception ignored){

        }

        return null;
    }
    /**
     * 删除Cookie
     * @param request
     * @param response
     * @param key
     * @return
     */
    public static String deleteCookie(HttpServletRequest request, HttpServletResponse response, String key) {
        for (Cookie cookie : request.getCookies()) {
            if(cookie.getName().equals(key)) {
                System.out.println("删除key="+key);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                cookie.setValue(null);
                response.addCookie(cookie);
            }
        }
        return "ok";
    }
    public static void sendServer(String title,String msg){
        try{
            System.out.println("title="+title+" msg="+msg);
            HttpURLConnection connection= (HttpURLConnection) new URL("https://sc.ftqq.com/SCU64034T5adf5c5940dcecc016e0e9d0cf9b1e725da126ff47475.send?text="
                    + URLEncoder.encode(title,"UTF-8")+"&desp="+URLEncoder.encode(msg,"UTF-8")).openConnection();
            connection.connect();
            InputStream inputStream=connection.getInputStream();
            int i=inputStream.read();
            inputStream.close();
            connection.disconnect();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取项目路径
     * @param request
     * @return
     */
    public static String getPath(HttpServletRequest request) {
        return request.getServletContext().getRealPath("/") + "/";
    }
    /**
     * 获取客户端IP
     *
     * @param request
     * @return
     */
    public static String getRemoteAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    /**
     * N以内的不重复随机数
     *
     * @param min
     *            最小值
     * @param max
     *            最大值
     * @param n
     * @return
     */
    public static int[] randomCommon(int min, int max, int n) {
        int len = max - min + 1;
        if (max < min || n > len) {
            return new int[0];
        }
        // 初始化给定范围的待选数组
        int[] source = new int[len];
        for (int i = min; i < min + len; i++) {
            source[i - min] = i;
        }
        int[] result = new int[n];
        Random rd = new Random();
        int index = 0;
        for (int i = 0; i < result.length; i++) {
            // 待选数组0到(len-2)随机一个下标
            index = Math.abs(rd.nextInt() % len--);
            // 将随机到的数放入结果集
            result[i] = source[index];
            // 将待选数组中被随机到的数，用待选数组(len-1)下标对应的数替换
            source[index] = source[len];
        }
        return result;
    }
    public static int checkWebLogin(HttpServletRequest request,RedisTools redisTools){
        JSONArray array=new JSONArray();
        if(redisTools.get("bean")!=null){
            array=JSONArray.parseArray(redisTools.get("bean"));
        }
        if(array.contains(Tools.getRemoteAddress(request))){
            System.out.println("IP已被封禁");
            return -100;
        }
        Cookie cookie = Tools.getCookie(request, "user");
        if (cookie == null) {
            return -1;
        }
        if (redisTools.get(cookie.getValue()).equals("ok")) {
           return 1;
        }
        return 0;
    }
    public static String get(String url){
        try{
            HttpURLConnection connection= (HttpURLConnection) new URL(url).openConnection();
            BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder str= new StringBuilder();
            String tmp;
            while ((tmp=reader.readLine())!=null){
                str.append(tmp);
            }
            reader.close();
            connection.disconnect();
            return str.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
