package com.qianhe.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.qianhe.common.utils.ip.IpUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

public class LogUtil {

    @Value("${Log_caKey}")
    private String Key;

    public static void main(String[] args) throws Exception {
        //发送日志请求
        Map<String, Object> map = new HashMap<>();
        map.put("name", "John");
        map.put("age", 30);
        map.put("isStudent", false);
        JsonObject jsonObject = sendSysLog("LoginLog", map);
        //获取日志
        JsonObject sysLog = getSysLog();
    }


    /**
     * 发送日志请求
     * @param tag 日志类型（LoginLog、UserOpeLog、ErrorLog、IServiceLog、ComponentOpeLog、DBOpeLog、BusinessLog）
     * @param map 日志内容
     */
    public static JsonObject sendSysLog(String tag, Map<String,Object> map) throws Exception {
        //本地ip
        String ip = IpUtils.getHostIp();
        //客户端ip
//        String ip = IpUtils.getIpAddr();
        String url="http://api.ssco.sinopec.com/PUBService.log.transferLogs?appname=APP_SLYT_SJGLXT&tag="+tag+"&hostname=" + ip;
        Gson gson = new Gson();
        String input = gson.toJson(map);
        URL targetUrl = new URL(url);
        HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
        httpConnection.setDoOutput(true);
        httpConnection.setRequestMethod("POST");
        httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8;");
        httpConnection.setRequestProperty("X-Ca-API-Key", "ee8d6cdbda2548f391a4b9389718abf7");
        OutputStream outputStream = httpConnection.getOutputStream();
        outputStream.write(input.getBytes("UTF-8"));
        outputStream.flush();
        if (httpConnection.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + httpConnection.getResponseCode());
        }
        InputStream inputStream = httpConnection.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, bytesRead);
        }
        buffer.flush();
        byte[] binaryData = buffer.toByteArray();

        // 将二进制数据转换为字符串（假设是 UTF-8 编码的 JSON）
        String jsonString = new String(binaryData, "UTF-8");

        // 使用 Gson 解析 JSON 字符串
        JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();

        System.out.println(jsonObject);
        httpConnection.disconnect();
        return jsonObject;
    }



    /**
     * 获取日志
     */
    public static JsonObject getSysLog() throws Exception {
        String apiUrl = "http://api.ssco.sinopec.com/api/v2/search/sheets/";
        String query = "appname:APP_SLYT_SJGLXT";
        String timeRange = "-1h,now";
        boolean timeline = false;
        String searchMode = "simple";
        String url = apiUrl + "?query=" + query
                + "&time_range=" + timeRange
                + "&timeline=" + timeline
                + "&searchMode=" + searchMode;
        URL targetUrl = new URL(url);
        HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
        httpConnection.setRequestMethod("GET");
        httpConnection.setRequestProperty("X-Ca-API-Key", "ee8d6cdbda2548f391a4b9389718abf7");
        httpConnection.setRequestProperty("Authorization","apikey lih2365:OYeEzLnOZiSPTNlKouAgeEQuTsokAvLA");
        if (httpConnection.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + httpConnection.getResponseCode());
        }
        InputStream inputStream = httpConnection.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, bytesRead);
        }
        buffer.flush();
        byte[] binaryData = buffer.toByteArray();

        // 将二进制数据转换为字符串（假设是 UTF-8 编码的 JSON）
        String jsonString = new String(binaryData, "UTF-8");

        // 使用 Gson 解析 JSON 字符串
        JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
        httpConnection.disconnect();
        return jsonObject;
    }
}