package com.jeeplus.human.signature.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

//import com.jeeplus.sys.utils.Global;

/**
 * @author: 徐滕
 * @create: 2021-11-02 14:20
 **/
public class SignaturePostUtil {

    //竖版模板templateId
    private static final String VERTICALTEMPLATEID = Global.getConfig("vertical_templateId");
    //横板模板templateId
    private static final String ACROSSTEMPLATEID = Global.getConfig("across_templateId");
    private static final String HTTPTOP = Global.getConfig("signature_http_top");

    private final static String apptoken = Global.getConfig("apptoken");
//    private final static String appsecret = Global.getConfig("appsecret");
    private final static String signature = Global.getConfig("signature");


    /**
     * 发送get请求
     *
     * @param requestUrl
     *      请求url
     * @param requestHeader
     *      请求头
     * @param responseEncoding
     *      响应编码
     * @return 页面响应html
     */
    public static String sendGet(String requestUrl, Map<String, String> requestHeader, String responseEncoding) {
        String result = "";
        BufferedReader reader = null;
        try {
            if (requestUrl == null || requestUrl.isEmpty()) {
                return result;
            }
            URL realUrl = new URL(requestUrl);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.connect();
            if (responseEncoding == null || responseEncoding.isEmpty()) {
                responseEncoding = "UTF-8";
            }
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEncoding));
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！");
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        result = decodeUnicode(result);
        return result;
    }

    /**
     * 发送下载压缩包get请求
     * @param requestUrl 请求url
     * @param requestHeader 请求头
     * @param fileName 下载文件名称
     * @param responseEncoding 响应编码
     * @return 页面响应html
     */
    public static String downloadZipGet(String requestUrl, Map<String, String> requestHeader, String fileName, String responseEncoding, HttpServletResponse response) {
        String result = "";
        BufferedReader reader = null;
        try {
            if (requestUrl == null || requestUrl.isEmpty()) {
                return result;
            }
            URL realUrl = new URL(requestUrl);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.setRequestProperty("Content-Type", "application/zip");
            connection.connect();
            if (responseEncoding == null || responseEncoding.isEmpty()) {
                responseEncoding = "UTF-8";
            }
            InputStream inputStream = connection.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);

            //设置HTTP响应头
            response.reset();//重置 响应头
            response.setContentType("application/x-download");//告知浏览器下载文件，而不是直接打开，浏览器默认为打开
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            response.addHeader("Content-Disposition" ,"attachment;filename=" +fileName+ "");//下载文件的名称
            // 循环取出流中的数据
            response.getOutputStream().write(getData);
            response.getOutputStream().close();

            if(inputStream!=null){
                inputStream.close();
            }

        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！");
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 下载文件并保存到指定位置
     * @param requestUrl 请求url
     * @param requestHeader 请求头
     * @param fileName 下载文件名称
     * @param responseEncoding 响应编码
     * @return 页面响应html
     */
    public static Map<String,Object> downloadZipDesignated(String requestUrl, Map<String, String> requestHeader, String fileName, String responseEncoding) {
        Map<String,Object> map = new HashMap<>();
        BufferedReader reader = null;
        try {
            if (requestUrl == null || requestUrl.isEmpty()) {
                map.put("success",false);
                map.put("message",fileName + " 的请求路径为空");
                map.put("fileName",fileName);
                map.put("filePath","");
                return map;
            }
            URL realUrl = new URL(requestUrl);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.setRequestProperty("Content-Type", "application/zip");
            connection.connect();
            if (responseEncoding == null || responseEncoding.isEmpty()) {
                responseEncoding = "UTF-8";
            }
            InputStream inputStream = connection.getInputStream();

            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            String filePath = null;
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                filePath = "D:/attachment-file/";
            }else{
                filePath = "/attachment-file/";
            }
            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）
            fileName = fileName.replaceAll("\\\\","");
            fileName = fileName.replaceAll("/","");
            fileName = fileName.replaceAll("\\*","");
            fileName = fileName.replaceAll("\\?","");
            fileName = fileName.replaceAll("\"","");
            fileName = fileName.replaceAll("<","");
            fileName = fileName.replaceAll(">","");
            fileName = fileName.replaceAll("\\|","");
            fileName = fileName.replaceAll("\\’","'");
            fileName = fileName.replaceAll("\\”","\"");
            fileName = fileName.replaceAll("【","(");
            fileName = fileName.replaceAll("\\{","(");
            fileName = fileName.replaceAll("】",")");
            fileName = fileName.replaceAll("}",")");
            fileName = fileName.replaceAll("，",",");
            fileName = fileName.replaceAll("：",":");
            fileName = fileName.replaceAll("—","-");
            fileName = fileName.replaceAll("……","");
            fileName = fileName.replaceAll("±","");
            fileName = fileName.replaceAll("#","");
            fileName = fileName.replaceAll("%","");
            fileName = fileName.replaceAll("Π","");

            FileOutputStream fileOut = new FileOutputStream(filePath + fileName);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while(length != -1)
            {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            //response.getOutputStream().close();
            bos.close();
            fileOut.close();
            bis.close();
            if(inputStream!=null){
                inputStream.close();
            }
            map.put("success",true);
            map.put("message","下载成功");
            map.put("fileName",fileName);
            map.put("filePath",filePath);
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！");
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    /**
     * 发送post请求
     *
     * @param requestUrl 请求url
     * @param requestHeader 请求头
     * @param formTexts 表单数据
     * @param files 上传文件
     * @param requestEncoding 请求编码
     * @param responseEncoding 响应编码
     * @return 页面响应html
     */
    public static String sendPost(String requestUrl, Map<String, String> requestHeader, Map<String, String> formTexts, File[] files, String requestEncoding, String responseEncoding) {
        OutputStream out = null;
        BufferedReader reader = null;
        String result = "";
        try {
            if (requestUrl == null || requestUrl.isEmpty()) {
                return result;
            }
            URL realUrl = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            if (requestEncoding == null || requestEncoding.isEmpty()) {
                requestEncoding = "UTF-8";
            }
            if (responseEncoding == null || responseEncoding.isEmpty()) {
                responseEncoding = "UTF-8";
            }
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            if (files == null || files.length == 0) {
                String boundary = "-----------------------------" + String.valueOf(new Date().getTime());
                connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
                out = new DataOutputStream(connection.getOutputStream());
                if (formTexts != null && formTexts.size() > 0) {
                    StringBuilder sbFormData = new StringBuilder();
                    for (Entry<String, String> entry : formTexts.entrySet()) {
                        sbFormData.append("--" + boundary + "\r\n");
                        sbFormData.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                        sbFormData.append(entry.getValue() + "\r\n");
                    }
                    out.write(sbFormData.toString().getBytes(requestEncoding));
                }
            } else {
                String boundary = "-----------------------------" + String.valueOf(new Date().getTime());
                connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
                out = new DataOutputStream(connection.getOutputStream());
                if (formTexts != null && formTexts.size() > 0) {
                    StringBuilder sbFormData = new StringBuilder();
                    for (Entry<String, String> entry : formTexts.entrySet()) {
                        sbFormData.append("--" + boundary + "\r\n");
                        sbFormData.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                        sbFormData.append(entry.getValue() + "\r\n");
                    }
                    out.write(sbFormData.toString().getBytes(requestEncoding));
                }
                for (File file : files) {
                    if (!file.exists()) {
                        continue;
                    }
                    out.write(("--" + boundary + "\r\n").getBytes(requestEncoding));
                    out.write(("Content-Disposition: form-data; name=\" file \"; filename=\"" + file.getName() + "\"\r\n").getBytes(requestEncoding));
                    out.write(("Content-Type: application/x-msdownload\r\n\r\n").getBytes(requestEncoding));
                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                    out.write(("\r\n").getBytes(requestEncoding));
                }
                out.write(("--" + boundary + "--").getBytes(requestEncoding));
            }
            out.flush();
            out.close();
            out = null;
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEncoding));
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！");
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        result = decodeUnicode(result);
        return result;
    }

    /**
     * ApplicationJson的post请求
     * @return
     */
    public static String sendPostApplicationJson(String url, String jsonString) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头鉴权
        httpPost.setHeader("x-qys-accesstoken", apptoken);
        httpPost.setHeader("x-qys-signature", signature);
        httpPost.setHeader("x-qys-timestamp", "0");
        // 包含内容格式设置
        httpPost.addHeader("Content-Type", "application/json");
        // 封装post请求参数
        if (null != jsonString) {
            // 为httpPost设置封装好的请求参数
            System.out.println("添加到实体------");
            httpPost.setEntity(new StringEntity(jsonString, "UTF-8"));
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        result = decodeUnicode(result);
        System.out.println(result);
        return result;
    }
    /**
     * imagePng的post请求
     * @return
     */
    public static String sendPostImagePng(String url, String jsonString) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头鉴权
        httpPost.setHeader("x-qys-accesstoken", apptoken);
        httpPost.setHeader("x-qys-signature", signature);
        httpPost.setHeader("x-qys-timestamp", "0");
        // 包含内容格式设置
        httpPost.addHeader("Content-Type", "image/png");
        // 封装post请求参数
        if (null != jsonString) {
            // 为httpPost设置封装好的请求参数
            System.out.println("添加到实体------");
            httpPost.setEntity(new StringEntity(jsonString, "UTF-8"));
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        result = decodeUnicode(result);
        System.out.println(result);
        return result;
    }

    public static String decodeUnicode(String asciicode) {
        String[] asciis = asciicode.split ("\\\\u");
        String nativeValue = asciis[0];
        try
        {
            for ( int i = 1; i < asciis.length; i++ )
            {
                String code = asciis[i];
                nativeValue += (char) Integer.parseInt (code.substring (0, 4), 16);
                if (code.length () > 4)
                {
                    nativeValue += code.substring (4, code.length ());
                }
            }
        }
        catch (NumberFormatException e)
        {
            return asciicode;
        }
        return nativeValue;
    }

    /**
     * 根据文件创建合同信息
     * @param srcFile
     * @return
     */
    public static HashMap getDocument(File srcFile) {
        //截取文件后缀名
        String substring = srcFile.getName().substring(srcFile.getName().lastIndexOf(".")+1, srcFile.getName().length());
        //截取文件名称
        String fileName = srcFile.getName().substring(0,srcFile.getName().lastIndexOf("."));
        //添加请求头
        Map<String,String> requestHeaderMap = new HashMap<>();
        requestHeaderMap.put("x-qys-accesstoken", apptoken);
        requestHeaderMap.put("x-qys-signature", signature);
        requestHeaderMap.put("x-qys-timestamp", "0");
        //添加文件参数
        Map<String,String> formTextsMap = new HashMap<>();
        formTextsMap.put("title",fileName);
        formTextsMap.put("fileType",substring);
        //创建文件数组
        File[] files = new File[]{srcFile};
        //访问方法
        String documentResult = sendPost(HTTPTOP + "/v2/document/createbyfile", requestHeaderMap, formTextsMap, files, "", "");
        HashMap hashMap = JSON.parseObject(documentResult, HashMap.class);

        return hashMap;
    }

    /**
     * 运行无效合同信息
     * @param fileName
     * @param invalidFile
     * @return
     */
    public static String getVerticalInvalidDocument(String fileName,File invalidFile){
        File[] files = new File[]{invalidFile};
        //添加请求头
        Map<String,String> requestHeaderMap = new HashMap<>();
        requestHeaderMap.put("x-qys-accesstoken", apptoken);
        requestHeaderMap.put("x-qys-signature", signature);
        requestHeaderMap.put("x-qys-timestamp", "0");
        //添加文件参数
        Map<String,String> formTextsMap = new HashMap<>();
        formTextsMap.put("title",fileName);
        formTextsMap.put("templateId",VERTICALTEMPLATEID);
        //访问方法
        String documentResult = sendPost(HTTPTOP + "/document/createbytemplate", requestHeaderMap, formTextsMap, files, "", "");
        HashMap hashMap = JSON.parseObject(documentResult, HashMap.class);
        String code = hashMap.get("code").toString();
        if("0".equals(code)){
            String documentId = hashMap.get("documentId").toString();
            return documentId;
        }
        return "";
    }

    /**
     * 运行无效合同信息
     * @param fileName
     * @param invalidFile
     * @return
     */
    public static String getAcrossVerticalInvalidDocument(String fileName,File invalidFile){
        File[] files = new File[]{invalidFile};
        //添加请求头
        Map<String,String> requestHeaderMap = new HashMap<>();
        requestHeaderMap.put("x-qys-accesstoken", apptoken);
        requestHeaderMap.put("x-qys-signature", signature);
        requestHeaderMap.put("x-qys-timestamp", "0");
        //添加文件参数
        Map<String,String> formTextsMap = new HashMap<>();
        formTextsMap.put("title",fileName);
        formTextsMap.put("templateId",ACROSSTEMPLATEID);
        //访问方法
        String documentResult = sendPost(HTTPTOP + "/document/createbytemplate", requestHeaderMap, formTextsMap, files, "", "");
        HashMap hashMap = JSON.parseObject(documentResult, HashMap.class);
        String code = hashMap.get("code").toString();
        if("0".equals(code)){
            String documentId = hashMap.get("documentId").toString();
            return documentId;
        }
        return "";
    }


    public static String doGet(Map<String, String> paramMap, String url){
        String result = "";
        HttpGet get = new HttpGet(url);
        try{
            // 设置请求头鉴权
            get.setHeader("x-qys-accesstoken", apptoken);
            get.setHeader("x-qys-signature", signature);
            get.setHeader("x-qys-timestamp", "0");
            CloseableHttpClient httpClient = HttpClients.createDefault();
            List<NameValuePair> params = setHttpParams(paramMap);
            String param = URLEncodedUtils.format(params, "UTF-8");
            get.setURI(URI.create(url + "?" + param));
            HttpResponse response = httpClient.execute(get);
            result = getHttpEntityContent(response);

            if(response.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){
                result = "服务器异常";
            }
        } catch (Exception e){
            System.out.println("请求异常");
            throw new RuntimeException(e);
        } finally{
            get.abort();
        }
        result = decodeUnicode(result);
        return result;
    }

    public static List<NameValuePair> setHttpParams(Map<String, String> paramMap){
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Set<Entry<String, String>> set = paramMap.entrySet();
        for(Entry<String, String> entry : set){
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return params;
    }

    public static String getHttpEntityContent(HttpResponse response) throws UnsupportedOperationException, IOException{
        String result = "";
        HttpEntity entity = response.getEntity();
        if(entity != null){
            InputStream in = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber= new StringBuilder();
            String line = null;
            while((line = br.readLine())!=null){
                strber.append(line+'\n');
            }
            br.close();
            in.close();
            result = strber.toString();
        }

        return result;
    }

    /**
     * 根据合同编号查询签章合同对应的url访问界面
     * @param contractId 签章合同id
     * @param contact 签章人手机号
     * @return
     */
    public static String getSignatureContractUrl( String contractId,String contact ){
        Map map = new HashMap();
        map.put("contractId",contractId);
        map.put("tenantType","COMPANY");
        map.put("tenantName","江苏兴光项目管理有限公司");
        map.put("contact",contact);
        String jsonString = JSON.toJSONString(map);
        String contractIdUrl = SignaturePostUtil.sendPostApplicationJson(HTTPTOP + "/contract/signurl", jsonString);
        HashMap signUrlHashMap = JSON.parseObject(contractIdUrl, HashMap.class);
        String code = signUrlHashMap.get("code").toString();
        if("0".equals(code)){
            String signUrl = signUrlHashMap.get("signUrl").toString();
            return signUrl;
        }
        return "";
    }

    /**
     * zip文件解压
     * @param file 需解压的文件
     * @param destDirPath 解压文件地址
     */
    public static void unZipFile(File file,String destDirPath){
        // 开始解压
        ZipFile zipFile = null;
        try {
            //zipFile = new ZipFile(file);
            //添加解压编码，解决解压报错问题
            zipFile = new ZipFile(file, Charset.forName("GBK"));
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                System.out.println("解压" + entry.getName());
                // 如果是文件夹，就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if(!targetFile.getParentFile().exists()){
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(zipFile != null){
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    e.printStackTrace();
                }
            }
        }
    }
}

