package com.seeyon.apps.src_hxinvoice.util;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.common.plugin.vo.ConfigVo;
import com.seeyon.apps.src_hxinvoice.constants.HxinvoiceConstants;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import www.seeyon.com.utils.StringUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;

public class ProtUtil {
    public String getPluginId() {return HxinvoiceConstants.getPluginId();}

    public static String uploadFile(String targetUrl, String filePath) throws IOException {
        String boundary = Long.toHexString(System.currentTimeMillis()); // 随机边界
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        String CRLF = "\r\n"; // 换行符
        URL url = new URL(targetUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (
                OutputStream output = connection.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
        ) {
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"title\"").append(CRLF);
            writer.append(CRLF).append("测试11").append(CRLF).flush();
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"fileType\"").append(CRLF);
            writer.append(CRLF).append("pdf").append(CRLF).flush();
            // 发送文件数据
            File file = new File(filePath);
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append(CRLF);
            writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append(CRLF);
            writer.append(CRLF).flush();

            Files.copy(file.toPath(), output);
            output.flush(); // 确保文件数据发送完毕

            writer.append(CRLF).flush(); // 结束行
            writer.append("--" + boundary + "--").append(CRLF);
        }

        int responseCode = connection.getResponseCode();
        // 连接对象获取一个输入流，向远程读取
        if (connection.getResponseCode() == 200) {

            is = connection.getInputStream();
            // 对输入流对象进行包装:charset根据工作项目组的要求来设置
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            StringBuffer sbf = new StringBuffer();
            String temp = null;
            // 循环遍历一行一行读取数据
            while ((temp = br.readLine()) != null) {
                sbf.append(temp);
                sbf.append("\r\n");
            }
            result = sbf.toString();
            System.out.println(result);
        }
        // 关闭资源
        if (null != br) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        connection.disconnect();
        return result;
    }

    /**
     * 调用post接口
     *
     * @param str    调用接口传递的参数json
     * @param urlStr 需要调用的url对应的参数文件中的编码
     * @return
     */
    public static JSONObject doPost(String str, String urlStr) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(urlStr);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            if (!("".equals(str) || str == null)) {
                os.write(str.getBytes("UTF-8"));
            }
            // 连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        JSONObject json = JSONObject.parseObject(result);
        return json;

    }


    public static void downloadFile(String urlStr, String filePath){
        String accesstoken = "T3KbU3zlRL";
        String appSecret = "owmMX93AfGZQBF2NCuH9a7i9TOeF5x";
        HttpURLConnection conn = null;
        OutputStream out = null;
        try {

            StringBuilder urlBuilder = new StringBuilder(urlStr);

            URL url = new URL(urlBuilder.toString());
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Host", url.getHost());
            conn.setRequestProperty("Accept", "text/plain,application/json");
            conn.setRequestProperty("User-Agent", "privateapp-java-api-client");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);


            int statusCode = conn.getResponseCode();
            StringBuilder response = new StringBuilder();
            if (statusCode == 200) {
                try (InputStream ins = conn.getInputStream()){
                    try (OutputStream outputStream = new FileOutputStream(filePath)) {
                        int bytesRead;
                        byte[] buffer = new byte[4096];
                        while ((bytesRead = ins.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                    //process response data
                } catch (Exception e){
                    // 处理异常情况
                }
            } else {
                // 处理异常情况
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取一个token
     *
     * @return
     * @throws IOException
     * @throws FileNotFoundException
     */
    private String getToken(String oatokenurl,String restName,String restPassword,String loginName) throws FileNotFoundException, IOException {
        String address = oatokenurl + restName + "/" + restPassword;
        if(StringUtil.isNotEmpty(loginName)){
            address = address +"?loginName="+loginName;
        }
        DefaultHttpClient client = new DefaultHttpClient();
        String result = "";
        HttpGet get = new HttpGet(address);
        // 添加 Headers 信息
        get.addHeader(new BasicHeader("Accept", "application/json"));
        try {
            HttpResponse res = client.execute(get);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(res.getEntity());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String token = "";
        if(result.contains("{")) {
            JSONObject jsObj = JSONObject.parseObject(result);
            token = jsObj.get("id").toString();
        }else {
            token = result;
        }
        return token;
    }


    /**
     * 调用post接口
     * @return
     */
    public String   sendPostNotification(String params, String urlParam, String token, ConfigVo configVo) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;

        try {
            String oatoken = getToken(configVo.getParamVal(HxinvoiceConstants.localipport.name())+configVo.getParamVal(HxinvoiceConstants.getTokenUrl.name())
                    ,configVo.getParamVal(HxinvoiceConstants.localRestName.name())
                    ,configVo.getParamVal(HxinvoiceConstants.localRestPwd.name())
                    ,null);
            URL url = new URL(configVo.getParamVal(HxinvoiceConstants.localipport.name())+urlParam+ token+"?token="+oatoken);
            System.out.println(configVo.getParamVal(HxinvoiceConstants.localipport.name())+urlParam+ token+"?token="+oatoken);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            if (!("".equals(params) || params == null)) {
                os.write(params.getBytes("UTF-8"));
            }
            System.out.println(connection.getResponseCode());
            // 连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
//                System.out.println(result);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
//		JSONObject json = JSONObject.parseObject(result);
        return result;

    }



}
