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.core.domain.entity.SysUser;
import com.qianhe.common.utils.DateUtils;
import com.qianhe.common.utils.ServletUtils;
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.*;
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> map1 = new HashMap<>();
        map1.put("UserName", "袁华");
        map1.put("Uid", "yuanh88");
        map1.put("age", 30);
        map1.put("DateTime", DateUtils.getTime());
        map1.put("OrgName", "油气井下作业中心");
        map1.put("DeptName", "滨南作业区");
        map1.put("DeptFullName", "/中国石化/胜利油田/胜利油田分公司/油气井下作业中心/滨南作业区/滨二作业项目部/");
        map1.put("isStudent", false);
        map1.put("Type", "登录");
        map1.put("Status", "成功");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("UserName", "范新静");
        map2.put("Uid", "fanxj888");
        map2.put("age", 30);
        map2.put("DateTime", DateUtils.getTime());
        map2.put("OrgName", "机关管理服务中心");
        map2.put("DeptName", "机关服务部");
        map2.put("DeptFullName", "/中国石化/胜利油田/胜利石油管理局有限公司/机关管理服务中心/机关服务部/领导班子/");
        map2.put("isStudent", false);
        map2.put("Type", "登录");
        map2.put("Status", "成功");
        Map<String, Object> map3 = new HashMap<>();
        map3.put("UserName", "卢新甫");
        map3.put("Uid", "luxf37");
        map3.put("age", 30);
        map3.put("DateTime", DateUtils.getTime());
        map3.put("OrgName", "河口采油厂");
        map3.put("DeptName", "工艺研究所");
        map3.put("DeptFullName", "/中国石化/胜利油田/胜利油田分公司/河口采油厂/工艺研究所/综合管理室/");
        map3.put("isStudent", false);
        map3.put("Type", "登录");
        map3.put("Status", "成功");
        Map<String, Object> map4 = new HashMap<>();
        map4.put("UserName", "刘圆");
        map4.put("Uid", "liuy22795");
        map4.put("age", 30);
        map4.put("DateTime", DateUtils.getTime());
        map4.put("OrgName", "天然气销售公司");
        map4.put("DeptName", "输配气项目部");
        map4.put("DeptFullName", "/中国石化/胜利油田/胜利油田分公司/天然气销售公司/输配气项目部/经营管理室/");
        map4.put("isStudent", false);
        map4.put("Type", "登录");
        map4.put("Status", "成功");
        Map<String, Object> map5 = new HashMap<>();
        map5.put("UserName", "王爱丽");
        map5.put("Uid", "wangal95");
        map5.put("age", 30);
        map5.put("DateTime", DateUtils.getTime());
        map5.put("OrgName", "老年服务管理中心");
        map5.put("DeptName", "科院老年服务部");
        map5.put("DeptFullName", "/中国石化/胜利油田/胜利石油管理局有限公司/老年服务管理中心/科院老年服务部/老年服务站/");
        map5.put("isStudent", false);
        map5.put("Type", "登录");
        map5.put("Status", "成功");
        Map<String, Object> map6 = new HashMap<>();
        map6.put("UserName", "刘海军");
        map6.put("Uid", "liuhj288");
        map6.put("age", 30);
        map6.put("DateTime", DateUtils.getTime());
        map6.put("OrgName", "供水分公司");
        map6.put("DeptName", "采出液处理中心");
        map6.put("DeptFullName", "/中国石化/胜利油田/胜利石油管理局有限公司/供水分公司/采出液处理中心/综合管理室/");
        map6.put("isStudent", false);
        map6.put("Type", "登录");
        map6.put("Status", "成功");
        Map<String, Object> map7 = new HashMap<>();
        map7.put("UserName", "张晓敏");
        map7.put("Uid", "zhangxm673");
        map7.put("age", 30);
        map7.put("DateTime", DateUtils.getTime());
        map7.put("OrgName", "供水分公司");
        map7.put("DeptName", "管理部门");
        map7.put("DeptFullName", "/中国石化/胜利油田/胜利石油管理局有限公司/供水分公司/管理部门/经营管理部（三基工作办公/");
        map7.put("isStudent", false);
        map7.put("Type", "登录");
        map7.put("Status", "成功");
        Map<String, Object> map8 = new HashMap<>();
        map8.put("UserName", "王青海");
        map8.put("Uid", "wangqh1784");
//        map8.put("age", 30);
        map8.put("DateTime", DateUtils.getTime());
//        map8.put("OrgName", "供水分公司");
//        map8.put("DeptName", "管理部门");
        map8.put("DeptFullName", "/中国石化/胜利油田/外部人员改制企业/山东谦和云科技有限公司/");
        map8.put("isStudent", false);
        map8.put("Type", "登录");
        map8.put("Status", "成功");

        List<Map<String, Object>> lm = new ArrayList<>();
        lm.add(map1);
        lm.add(map2);
        lm.add(map3);
        lm.add(map4);
        lm.add(map5);
        lm.add(map6);
        lm.add(map7);
        lm.add(map8);

        for(int i = 7; i < lm.size(); i++) {
            Map map = lm.get(i);

//            JsonObject jsonObject = sendSysLog("LoginLog", map);
//            //获取日志
//            JsonObject sysLog = getSysLog();
//
//            map.put("ResourceName", "分档评价");//月度问题记录
//            map.put("OperationInfo", "新增");
//            map.put("Type", "新增");
//            JsonObject jsonObject2 = sendSysLog("UserOpeLog", map);


            map.put("ErrorMessage", "调用接口异常");
            map.put("Type", "调用接口异常");
            map.put("Level", "1级");//故障
            JsonObject jsonObject3 = sendSysLog("ErrorLog", map);

//            map.put("Type", "Type");
//            map.put("Status", "成功");
//            map.put("CostTime", "1500");
//            map.put("ServerAddress", "http://ydsj.slof.com:9034/prod-api/system/sjGfjsJcdwkhpj/edit");
//            map.put("ClientIP", "10.66.1.17");
//            map.put("IServiceName", "修改分档评价");
//            JsonObject jsonObject4 = sendSysLog("IServiceLog", map);

        }
    }

    //模块日志上传接口
    public static String mkrzsc(SysUser u, String mkmc, String qlj, String czmc, String czlx)
    {

        Map<String, Object> map1 = new HashMap<>();
        map1.put("UserName", u.getNickName());
        map1.put("Uid", u.getUserName());
//                            map1.put("age", 30);
        map1.put("DateTime", DateUtils.getTime());
//                            map1.put("OrgName", orgName);
//                            map1.put("DeptName", dptName);
        map1.put("DeptFullName", u.getRemark());
        map1.put("isStudent", false);
        map1.put("Status", "成功");

        map1.put("ResourceName", mkmc);//月度问题记录  "分档评价"
        map1.put("ResourceFullPath", qlj);//全路径
        map1.put("OperationInfo", czmc);//"新增"
        map1.put("Type", czlx);//"新增"
        try {
            JsonObject jsonObject = sendSysLog("UserOpeLog", map1);
            //获取日志
            JsonObject sysLog = getSysLog();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //模块日志上传接口
    public static String mkrzscErr(SysUser u, String mkmc, String qlj, String czmc, String type, String errorMessage, String level)
    {

        Map<String, Object> map1 = new HashMap<>();
        map1.put("UserName", u.getNickName());
        map1.put("Uid", u.getUserName());
//                            map1.put("age", 30);
        map1.put("DateTime", DateUtils.getTime());
//                            map1.put("OrgName", orgName);
//                            map1.put("DeptName", dptName);
        map1.put("DeptFullName", u.getRemark());
        map1.put("isStudent", false);
        map1.put("Status", "成功");

        map1.put("ResourceName", mkmc);//月度问题记录  "分档评价"
        map1.put("ResourceFullPath", qlj);//全路径
        map1.put("OperationInfo", czmc);//"新增"
        map1.put("Type", type);//"新增"
        map1.put("ErrorMessage", errorMessage);//"新增"
        map1.put("Level", level);//"新增"
        try {
            JsonObject jsonObject = sendSysLog("ErrorLog", map1);
            //获取日志
            JsonObject sysLog = getSysLog();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 发送日志请求
     * @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;
    }
}
