package com.trs.project.test;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.trs.project.entity.GcJihuaInfo;
import com.trs.project.entity.GcTenderbidfile;
import com.trs.project.util.RSAUtils;
import com.xxl.job.core.context.XxlJobHelper;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.sql.DataSource;
import java.io.*;
import java.net.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Test {
    public static void main(String[] args) {
//        TaskRecord byId = taskRecordService.getById("GC_NOTICEANDFILE");
//        if(null == byId){
//            byId = new TaskRecord();
//            byId.setTableName("GC_NOTICEANDFILE");
//            byId.setUpdateTime(new Date());
//            byId.setLastDealTime(new Date());
//        }
//        Date startDateTime = byId.getLastDealTime();
////                String startDateStr = Log.getTxtData("time.txt");
////                startDate = sdf.parse(startDateStr).getTime();
//        long startDate = startDateTime.getTime();
//
//        Date afterDate = new Date(startDate + 30*60*1000);//30分钟后的时间
//        //Log.Logger("time.txt",sdf.format(afterDate));
//        byId.setLastDealTime(afterDate);
//        byId.setUpdateTime(new Date());
//        taskRecordService.saveOrUpdate(byId);

        Long timeMillis = System.currentTimeMillis();
        System.out.println("enterTasks定时任务执行时间："+new Date());
        timeMillis = System.currentTimeMillis();
        System.out.println(timeMillis);
        System.out.println("1672543421");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = null;
        try {
            startDate = format.parse("2024-10-10 00:00:00");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        System.out.println(new Date().getTime());
        try{///1724688000000
            ///1724688000000
            ///1724688000000
//            JSONObject jsonObject = httpGetMethod("https://ggzyjy.nmg.gov.cn/adminNmg/api/down.do?platform_code=e64975be&table_name=JSGC_ProjectJHInfo&page=1&page_size=20&startTime="+startDate.getTime()+"  ");
//            JSONObject jsonObject = httpGetMethod("https://ggzyjy.nmg.gov.cn/adminNmg/api/down.do?platform_code=e64975be&table_name=ZFCG_GONGAO&page=1&page_size=1&startTime="+startDate.getTime()+"  ");
            //JSONObject jsonObject = httpGetMethod("https://ggzyjy.nmg.gov.cn/adminNmg/api/down.do?platform_code=e64975be&table_name=GC_TENDERBIDFILEPUBLICITY&page=1&page_size=1&startTime=1724049516000");
            JSONObject jsonObject = httpGetMethod("https://ggzyjy.nmg.gov.cn/adminNmg/api/down.do?platform_code=e64975be&table_name=GC_TENDERBIDFILEPUBLICITY&page=1&page_size=10");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String data = RSAUtils.decrypt(jsonObject.getString("data"));
            JSONArray jsonArray = JSONArray.parseArray(data);
            System.out.println(jsonArray);
            List<GcJihuaInfo> gcJihuaInfos = JSONObject.parseArray(jsonArray.toJSONString(), GcJihuaInfo.class);
            for (GcJihuaInfo gcJihuaInfo : gcJihuaInfos) {
                gcJihuaInfo.setDataTimestamp(Long.parseLong(simpleDateFormat.format(new Date())));
            }
            System.out.println(gcJihuaInfos);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static void main2(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = null;
        try {
            startDate = format.parse("2024-08-27 00:00:00");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        System.out.println(startDate.getTime());
    }


    //http方法
    public static JSONObject httpGetMethod(String uri){
//        JSONObject response = restTemplate.getForObject(uri,JSONObject.class);
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("startTime", "1724688000000");
        String str = sendPost(uri, parameters);
//        String str = sendGet(uri, parameters);
        JSONObject response =JSONObject.parseObject(str);
        return response;
    }

    public static String sendPost(String url, Map<String, String> parameters) {
        String result = "";
        BufferedReader in = null;
        StringBuilder sb = new StringBuilder(); // 使用StringBuilder而不是StringBuffer，因为StringBuilder不保证线程安全，但性能更好
        try {
            // 编码请求参数为表单数据
            if (parameters != null) {
                for (Map.Entry<String, String> entry : parameters.entrySet()) {
                    sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                    sb.append("=");
                    sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                    sb.append("&");
                }
                // 移除最后一个"&"
                String params = sb.toString().substring(0, sb.length() - 1);

                // 创建URL对象
                URL connURL = new URL(url);
                // 打开URL连接
                HttpURLConnection httpConn = (HttpURLConnection) connURL.openConnection();
                // 设置请求方法为POST
                httpConn.setRequestMethod("POST");
                // 设置请求头，内容类型为表单数据
                httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                httpConn.setRequestProperty("Accept", "*/*");
                httpConn.setRequestProperty("Connection", "Keep-Alive");
                httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");

                // 发送POST请求的输出参数
                try (OutputStream os = httpConn.getOutputStream()) {
                    byte[] input = params.getBytes("utf-8");
                    try (DataOutputStream dataOutputStream = new DataOutputStream(os)) {
                        dataOutputStream.write(input, 0, input.length);
                    }
                }

                // 读取响应
                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                    String line;
                    while ((line = in.readLine()) != null) {
                        result += line;
                    }
                }

                // 响应头部获取（如果需要）
                // Map<String, List<String>> headers = httpConn.getHeaderFields();
                // 遍历所有的响应头字段
                // for (String key : headers.keySet()) {
                //     System.out.println(key + " : " + headers.get(key));
                // }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String sendGet(String url, Map<String, String> parameters) {
        String result="";
        BufferedReader in = null;// 读取响应输入流
        StringBuffer sb = new StringBuffer();// 存储参数
        String params = "";// 编码之后的参数
        try {
            // 编码请求参数

            //System.out.println(full_url);
            // 创建URL对象
            java.net.URL connURL = new java.net.URL(url);
            // 打开URL连接
            java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
                    .openConnection();
            // 设置通用属性
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            // 建立实际的连接
            httpConn.connect();
            // 响应头部获取
            Map<String, List<String>> headers = httpConn.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : headers.keySet()) {
                //System.out.println(key + "\t：\t" + headers.get(key));
            }
            // 定义BufferedReader输入流来读取URL的响应,并设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn
                    .getInputStream(), "UTF-8"));
            String line;
            // 读取返回的内容
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result ;
    }

    public static String sendPost(String url, String param,boolean isproxy) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = null;
            if(isproxy){//使用代理模式
                @SuppressWarnings("static-access")
                Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress("ggzyjy.nmg.gov.cn", 443));
                conn = (HttpURLConnection) realUrl.openConnection(proxy);
            }else{
                conn = (HttpURLConnection) realUrl.openConnection();
            }
            // 打开和URL之间的连接

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST"); // POST方法


            // 设置通用的请求属性

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            conn.connect();

            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            if(param!=null&&!param.equals("")){
                out.write(param);
            }

            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }



}
