package com.bcxin.ins.third.tyx.pingan.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.*;
import java.net.URLDecoder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author LIUXING583 2017年6月1日
 *
 */
public class FileDownloadTest extends Thread {

    /**
     * 用于并发测试
     */
    private static final int CONCURRENT_NUMBER = 1;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(50);
        FileDownloadTest test = new FileDownloadTest();
        for (int i = 0; i < CONCURRENT_NUMBER; i++) {
            executorService.execute(test);
        }
        executorService.shutdown();
    }

    @Override
    public void run() {
        System.out.println("start");
        try {
            sendRequest();
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("done");
    }

    private void sendRequest() throws HttpException, Exception {
        // 获取私钥
//         Map<String, Object> keyMap = PaRsaUtils.genKeyPair();
//         String privateKey = PaRsaUtils.getPrivateKey(keyMap);
//         System.out.println("私钥："+privateKey);
//         System.out.println("公钥："+PaRsaUtils.getPublicKey(keyMap));
        String privateKey ="MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCWGTs/R+BFOsiedNKqMyr2zUvUdsIhBCyost4YgMAv9yoCa/m7S2RllBzBe4+8IoNlQ60dw7NE+x6luvzISQDihNaXqSCnXDHrUm11FEd6N1xdjzOG2jOqru7Z8EkYjmGplwNYsWUwS6wJZrDaZEWmqa3Lm7k2rmx5YRp8IAq0FAfi2gu9z/dOWoMZm8DnkyLQpWB5HLoQBVDoDm1USRrQ00WJ4J5zLbTHi0/EP/IuMLuZoZp8bzasr76ta35ZJHJ2ntT766wYAnID334cHvTq/X9uZQg598gUany7NpXfofmVCmrswYo/giLUMniN8jQrQfY73wtjXfyftLepj+PhA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e4tIk6WcyFfjujAoGAeLfWoA6z0j5xirjSEG/LENKqco2JonauzI8227xAZLuQ3qq2aUb99pIhKW/3KlFNNCjY/hfWyJ+omEoVxqQoqpbNrqypTHOYCWdLvSfEeQqi+9UIQC/kZBBCVUL6DkVtiMuTqHm0M6zNyOvyxCKQ8EP2ZT9OeRPPF/ut/1MSXdU=


        JSONObject returnParams = new JSONObject();
        //分配的partnerId

        returnParams.put("partnerId", "PCXM001");
        //调用接口返回的对应的保单或其他文件的fileId
        returnParams.put("fileId", "38a964ad-22bc-45f0-90d1-942d78717897");
        returnParams.put("timestamp", System.currentTimeMillis());

        String params = returnParams.toString();
        System.out.println(params);
        String sign = "";
        try {
            sign = PaRsaUtils.sign(params.getBytes(), privateKey);
        } catch (Exception e) {
            System.out.println("加签失败，请检查私钥【privateKey】和参数【params】");
            e.printStackTrace();
        }

        HttpClient httpClient = new HttpClient();
//        httpClient.getHostConfiguration().setProxy("10.36.232.125", 8080);
        httpClient.getHttpConnectionManager().getParams()
                .setConnectionTimeout(5000);
        //url
        PostMethod method = new PostMethod(
                "https://test-yldap.pa18.com/egis-dap-file/fileDownload.do");

        method.setParameter("params", params);
        method.setParameter("sign", sign);
        httpClient.executeMethod(method);
        Header headerParams = method.getResponseHeader("parameters");

        if (headerParams == null) {
            System.out.println("failed to get a reply");
            return;
        }
        String plaintext = decode(headerParams.getValue());

        System.out.println(plaintext);
//        plaintext="{\"returnCode\":\"0000\",\"fileName\":\"1dbed234-0439-4a41-8cc2-051ece864405.pdf\",\"returnMessage\":\"下载成功\"}";
        JSONObject paramObject = JSON.parseObject(plaintext);
        String returnCode = (String) paramObject.get("returnCode");
        String returnMessage = (String) paramObject.get("returnMessage");

        if (!returnCode.equals("0000")) {
            // 非0000，皆错
            System.out.println(returnMessage);
            return;
        }
        // 密文文件存放路径
        String encryptDir = "E:\\Temp\\encryptDir\\";
        // 明文文件存放路径
        String decryptDir = "E:\\Temp\\decrypted\\";
        String fileName = (String) paramObject.get("fileName");

        File encryptDirFile = new File(encryptDir);
        File decryptDirFile = new File(decryptDir);
        if (!encryptDirFile.exists()) {
            encryptDirFile.mkdirs();
        }
        if (!decryptDirFile.exists()) {
            decryptDirFile.mkdirs();
        }


        try(InputStream bis = method.getResponseBodyAsStream();
            OutputStream fos = new FileOutputStream(encryptDir + fileName);) {
            byte[] arrayOfByte = new byte[1024];
            int i = -1;
            while ((i = bis.read(arrayOfByte)) != -1) {
                fos.write(arrayOfByte, 0, i);
            }
            fos.flush();
        }

        Header parametersEncrypted = method
                .getResponseHeader("parametersEncrypted");
        if (parametersEncrypted == null) {
            System.out.println("密文信息获取失败");
            return;
        }
        JSONObject parametersEncryptedJson = JSON.parseObject(new String(
                PaRsaUtils.decryptByPrivateKey(
                        baseDecode(decode(parametersEncrypted.getValue())),
                        privateKey)));

        System.out.println(parametersEncryptedJson.toString());
        String encryptMode = parametersEncryptedJson
                .getString("encryptMode");
        String encryptKey = parametersEncryptedJson.getString("encryptKey");
        Integer encryptKeySize = parametersEncryptedJson
                .getInteger("encryptKeySize");

        String lastFilePath = null;
        // 文件解密
        if ("AES".equals(encryptMode)) {// AES
            PaAesUtils.decryptFile(encryptKey, encryptDir + fileName,
                    decryptDir + fileName);
            lastFilePath = decryptDir + fileName;
        } else if ("PLAIN".equals(encryptMode)) { // 明文
            // 明文直接使用encryptDir + fileName上的文件
            lastFilePath = encryptDir + fileName;
        }
        System.out.println("文件下载成功：" + lastFilePath);
    }

    private String decode(String data) throws IOException {
        return URLDecoder.decode(data, "GBK");
    }

    private byte[] baseDecode(String data) throws IOException {
        return Base64Utils.decode(data);
    }

}
