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


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.util.GlobalResources;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URLDecoder;

/**
 *
 * @author LIUXING583 2017年6月1日
 *
 */
public class FileDownload  {
    private static Logger logger =  LoggerFactory.getLogger(FileDownload.class);

    public  String getFileAddress(String fileId){
        try {
            String path=this.sendRequest(fileId);
            if(path==null){
                return null;

            }else{
                return "/getResource.do?path="+path;
            }
        }catch (Exception ex){
            logger.error("FD-ERROR-00007:路径处理异常",ex);
        }
        return null;
    }

    public  String sendRequest(String fileId) 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 ="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDNGfgGuwz7/HqvddI6ADkEj7nNYbCnjGhNDMbgVQeUcFaQLN98A5ilZmBi4BSM2qilR3e2ZAsE3nvAga+BZS25xwsDoQStaCmxtAmPnd0Wk6L68smJFUBjCqT6As9svTq3gwcArid8tVavQT0zi57kXaOMxiyg72r4EXo13UG5klDLasHTxbke8/AsvOtFdkFImJWWoqNT4fx90nUlGo1v1RAYVsvUcmCR6P2cZ6or4I4pd/Vt5BxGsqHNmFjKmP8aD0VcHGsoRnF1qm1ZjV//rYiFs9eGQhbJwQLOUv7QU1GR8I7857sOQYRCXLMmM+l8XbHYieGx8Ab2vAt9/wAhAgMBAAECggEBAJlFEct91ussN0aNxqdfaTyWZ2Qq38elrn/9z1TvVfXAqX+eePgE+/qGcfsRt2m3MZYpvTVI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/kZBBCVUL6DkVtiMuTqHm0M6zNyOvyxCKQ8EP2ZT9OeRPPF/ut/1MSXdU=";
        String privateKey =GlobalResources.PN_POLICY_FILE_KEY;
        //测试环境私钥：MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCWGTs/R+BFOsiedNKqMyr2zUvUdsIhBCyost4YgMAv9yoCa/m7S2RllBzBe4+8IoNlQ60dw7NE+x6luvzISQDihNaXqSCnXDHrUm11FEd6N1xdjzOG2jOqru7Z8EkYjmGplwNYsWUwS6wJZrDaZEWmqa3Lm7k2rmx5YRp8IAq0FAfi2gu9z/dOWoMZm8DnkyLQpWB5HLoQBVDoDm1USRrQ00WJ4J5zLbTHi0/EP/IuMLuZoZp8bzasr76ta35ZJHJ2ntT766wYAnID334cHvTq/X9uZQg598gUany7NpXfofmVCmrswYo/giLUMniN8jQrQfY73wtjXfyftLepj+PhAgMBAAECggEATncaNdaJMyerwMopZrgg+awQvBzpFwFrpzT6TazgyzJWT7XKc1LSRRfMgIjrdtpD/igG08x+Zs0wFEtP4hPn1oLC+716SIM1xWLtvYrAYu+V5YL62MAwykVwr5WhYKjt/Q3ovfDeiQTGBpQcV86baqjBJfNeO2urYTiV89V8Qu5x49SjaysPg2julyrSFRBaqQWPPallhAz45kgiQ+gdKgZSQ1BGB4kkgSvhfZB2ohYaTDQ3TzUS+2LAMRk55BrLZerT/STczeUYgxYENZcaTv1jZ/rMijVb0jL7c6VZrrfnGlN6pqIkqFRKZg8TFg8HsluMoTuNTTiYzzdV8IQ7UQKBgQD9/CvCI7BGB0dyQXmqa6e/2cdMqTZIOZzMUqEW/yFT3BQragVNaKwSXi+PusnJ5WA5akdX7X/iwmt86Jn94E0XxsaTZ4mzky+G4bi7uX1syr7sOBw5F094N6R0trPSnNBNOXSnXYC34+OiLDwiE00D6QGYq42cf06F9vUXMCY8xwKBgQCXShKwx9Xn/HAnxLl/IGkpcowAAGAhGKdeF5YaE3D/VzwgPU7yiH68IPbTIBKv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KW/3KlFNNCjY/hfWyJ+omEoVxqQoqpbNrqypTHOYCWdLvSfEeQqi+9UIQC/kZBBCVUL6DkVtiMuTqHm0M6zNyOvyxCKQ8EP2ZT9OeRPPF/ut/1MSXdU=
        JSONObject returnParams = new JSONObject();
        //分配的partnerId
        returnParams.put("partnerId", "PCXM001");
        //调用接口返回的对应的保单或其他文件的fileId
        returnParams.put("fileId", fileId);
        returnParams.put("timestamp", System.currentTimeMillis());
        String params = returnParams.toString();
        String sign = "";
        try {
            sign = PaRsaUtils.sign(params.getBytes(), privateKey);
        } catch (Exception e) {
            logger.error("FD-ERROR-00001:加签失败，请检查私钥【privateKey】和参数【params】",e);
            return  null;

        }

        HttpClient httpClient = new HttpClient();
//        httpClient.getHostConfiguration().setProxy("10.36.232.125", 8080);
        httpClient.getHttpConnectionManager().getParams()
                .setConnectionTimeout(5000);
        //url
        PostMethod method = new PostMethod(GlobalResources.PN_POLICY_FILE);
//        PostMethod method = new PostMethod("https://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) {
            logger.error("FD-ERROR-00002:failed to get a reply");
            return null;
        }
        String plaintext = decode(headerParams.getValue());

        JSONObject paramObject = JSON.parseObject(plaintext);
        String returnCode = (String) paramObject.get("returnCode");
        String returnMessage = (String) paramObject.get("returnMessage");

        if (!returnCode.equals("0000")) {
            // 非0000，皆错
            logger.error("FD-ERROR-00006:非0000，皆错");
            return null;
        }
        // 密文文件存放路径
        String encryptDir = "\\encryptDir\\";
        // 明文文件存放路径
        String decryptDir = "\\decrypted\\";
        String fileName = (String) paramObject.get("fileName");

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

        try(InputStream bis = method.getResponseBodyAsStream();
            OutputStream fos = new FileOutputStream(GlobalResources.COM_IMG_RE+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) {
            logger.error("FD-ERROR-00005:密文信息获取失败");
            return null;
        }
        JSONObject parametersEncryptedJson = JSON.parseObject(new String(
                PaRsaUtils.decryptByPrivateKey(
                        baseDecode(decode(parametersEncrypted.getValue())),
                        privateKey)));
        logger.info("(FileDownload),parametersEncryptedJson:"+parametersEncryptedJson.toJSONString());
        String encryptMode = parametersEncryptedJson
                .getString("encryptMode");
        String encryptKey = parametersEncryptedJson.getString("encryptKey");
        Integer encryptKeySize = parametersEncryptedJson
                .getInteger("encryptKeySize");

        String lastFilePath = null;
        logger.info("(FileDownload),encryptKey:"+encryptKey);
        // 文件解密
        if ("AES".equals(encryptMode)) {
            // AES
            logger.info("(FileDownload),encryptDir-url:"+GlobalResources.COM_IMG_RE+encryptDir + fileName);
            logger.info("(FileDownload),decryptDir-url:"+GlobalResources.COM_IMG_RE+decryptDir + fileName);
            PaAesUtils.decryptFile(encryptKey, GlobalResources.COM_IMG_RE+encryptDir + fileName,
                    GlobalResources.COM_IMG_RE+decryptDir + fileName);
            lastFilePath = decryptDir + fileName;
            return  lastFilePath;
        } else if ("PLAIN".equals(encryptMode)) {
            // 明文
            // 明文直接使用encryptDir + fileName上的文件
            lastFilePath = encryptDir + fileName;
            return  lastFilePath;
        }
        return  null;
    }

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

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

}
