package com.yem.wm.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.file.IOUtils;
import com.yem.ia.intebilllogon.Utils.ObjectToJsonUtils;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.validate.ErrorLevel;
import kd.bos.entity.validate.ValidationErrorInfo;
import kd.bos.exception.KDBizException;
import kd.bos.exception.KDException;
import kd.bos.id.ID;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.drp.mem.yzj.config.SSLClient;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class YunzhijiaUtils {
    public static String yzjurl = "http://10.64.113.120:8080";//测试
    public static String getOpenId(String phonNum) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        String req ="{\"type\":0,\"array\":[\""+phonNum+"\"]}";
        String openId = null;
        String retstr = doPost(yzjurl + "/cmmpapi/cmmp/person.do?tokenId=D4EB05B9FE9C41D0868D33EC92AAEDB4", req);
        JSONObject retJson = JSONObject.parseObject(retstr);
        JSONArray datas = retJson.getJSONArray("data");
        for (int i = 0; i < datas.size(); i++) {
            JSONObject data = datas.getJSONObject(i);
            openId = data.getString("openId");
        }
        return openId;
    }
    public static String doPost(String url, String param) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        httpClient = new SSLClient();
//			httpClient = new DefaultHttpClient();
        httpPost = new HttpPost(url);

        StringEntity se = new StringEntity(param, "UTF-8");
        se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
        se.setContentType("application/json");
        httpPost.setEntity(se);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) result = EntityUtils.toString(resEntity, "UTF-8");
        }
        return result;
    }

    /**
     * 文件上传
     *
     * @param url
     * @param bytes
     * @param accessToken
     * @param filename
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static String doPost(String url, byte[] bytes, String accessToken, String filename) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, filename.getBytes(StandardCharsets.UTF_8).toString());
        builder.addTextBody("bizkey", "cloudflow");
        builder.setCharset(Charset.forName("utf-8"));
        HttpClient httpClient = HttpClientBuilder.create().build();
        httpPost.setEntity(builder.build());
        httpPost.addHeader("Cache-Control", "no-cache");
        httpPost.addHeader("x-accessToken", accessToken);
        httpPost.addHeader("ContentType", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) result = EntityUtils.toString(resEntity, "utf-8");
        }
        // 处理服务器返回的响应结果
        return result;
    }

    /**
     * 提交创建云之家审批流程
     *
     * @param operationResult 操作结果参数
     * @param passDataEntitys 通过校验数据数组
     * @param dataEntity      传输数据
     */
    public static void submit2YZJ(OperationResult operationResult, List<ExtendedDataEntity> passDataEntitys, ExtendedDataEntity dataEntity) {
        DynamicObject dynamicObject = dataEntity.getDataEntity();
        dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.getLong("id"), dynamicObject.getDynamicObjectType().getName());
        Map map = new HashMap<>();
        map.put("entityName", dynamicObject.getDynamicObjectType().getName());
        if (dynamicObject.containsProperty("yem_billtype")) {
            map.put("billtype", dynamicObject.getString("yem_billtype.number"));
        }
        //TODO 订单产品需求单特殊处理
        if ("yem_orderproreqbill".equals(dynamicObject.getDynamicObjectType().getName())&&"yem_orderproreqbill_DB".equals(dynamicObject.getString("yem_billtype.number"))) {
            map.put("Stashtype", dynamicObject.getString("yem_isvmi"));
        }
        if("yem_placeexamine".equals(dynamicObject.getDynamicObjectType().getName())){
            map.put("yem_salesordertype",dynamicObject.getString("yem_salesordertype"));
        }
        //end by zhouc 2024-01-11
        if("yem_es_contactbook".equals(dynamicObject.getDynamicObjectType().getName())){
            map.put("yem_procbilltype",dynamicObject.getString("yem_procbilltype"));
        }
//        DynamicObject[] load = BusinessDataServiceHelper.load("yem_ia_intebilllogon", "id", new QFilter[]{null});
//        for (DynamicObject obj : load) {
//            obj = BusinessDataServiceHelper.loadSingle(obj.get("id"),"yem_ia_intebilllogon");
//            if(((MulBasedataDynamicObjectCollection)obj.get("yem_billtype")).size()>0){
//                System.out.println();
//            }
//        }
        JSONObject json = ObjectToJsonUtils.ObjectToJson(dynamicObject.get("id"), map);
        if (json.containsKey("errmessage")) {
            passDataEntitys.add(dataEntity);
            return;
        }
        try {
            String s = YunzhijiaUtils.doPost(YunzhijiaUtils.yzjurl+"/cmmpapi/cmmp/flowCreate.do?tokenId=0C89F5DBEB704C1F8671721B148E8224", json.toString());
            System.out.println(s);
            JSONObject retJson = JSONObject.parseObject(s);
            Boolean success = retJson.getBoolean("success");
            if (success) {
                JSONObject data = retJson.getJSONObject("data");
                String formInstId = data.getString("formInstId");//表单定义ID
                String flowInstId = data.getString("flowInstId");//流程实例ID
                dynamicObject.set("yem_synfalt",null);
                dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.get("id"), dynamicObject.getDynamicObjectType().getName());
                dynamicObject.set("yem_forminstid", formInstId);
                dynamicObject.set("yem_flowinstid", flowInstId);
                dynamicObject.set("yem_isyzjreject", false);
                SaveServiceHelper.update(dynamicObject, OperateOption.create());
                // 根据实体名构建元数据并创建DynamicObject
                MainEntityType entityType = EntityMetadataCache.getDataEntityType("yem_ialog");
                DynamicObject yemIalog = new DynamicObject(entityType);
                yemIalog.getDataEntityType().getPrimaryKey().setValueFast(yemIalog, ID.genLongId());
                yemIalog.set("billno", dynamicObject.get("billno"));//单据编号
                DynamicObject yem_billtype = BusinessDataServiceHelper.loadSingle("bos_entityobject", new QFilter[]{new QFilter("number", QCP.equals, dynamicObject.getDynamicObjectType().getName())});
                yemIalog.set("yem_billtype", yem_billtype);//单据类型
                yemIalog.set("yem_success", success);//是否成功
                yemIalog.set("yem_req", json.toString());//请求参数
                yemIalog.set("billstatus", "A");//请求参数

                yemIalog.set("yem_response", s);//返回参数
                yemIalog.set("yem_flowinstid", flowInstId);//流程实例ID
                yemIalog.set("yem_forminstid", formInstId);//表单实例ID
                SaveServiceHelper.save(new DynamicObject[]{yemIalog});
                passDataEntitys.add(dataEntity);
            } else {
                // 根据实体名构建元数据并创建DynamicObject
                MainEntityType entityType = EntityMetadataCache.getDataEntityType("yem_ialog");
                DynamicObject yemIalog = new DynamicObject(entityType);
                yemIalog.getDataEntityType().getPrimaryKey().setValueFast(yemIalog, ID.genLongId());
                yemIalog.set("billstatus", "A");//请求参数
                yemIalog.set("billno", dynamicObject.get("billno"));//单据编号
                DynamicObject yem_billtype = BusinessDataServiceHelper.loadSingle("bos_entityobject", new QFilter[]{new QFilter("number", QCP.equals, dynamicObject.getDynamicObjectType().getName())});
                yemIalog.set("yem_billtype", yem_billtype);//单据类型
                yemIalog.set("yem_success", false);//是否成功
                yemIalog.set("yem_req", json.toString());//请求参数
                yemIalog.set("yem_response", s);//返回参数
                SaveServiceHelper.save(new DynamicObject[]{yemIalog});
                addErrMessage(operationResult, dataEntity, "云之家生成流程异常：" + s);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            // 根据实体名构建元数据并创建DynamicObject
            MainEntityType entityType = EntityMetadataCache.getDataEntityType("yem_ialog");
            DynamicObject yemIalog = new DynamicObject(entityType);
            yemIalog.getDataEntityType().getPrimaryKey().setValueFast(yemIalog, ID.genLongId());
            yemIalog.set("billstatus", "A");//请求参数
            yemIalog.set("billno", dynamicObject.get("billno"));//单据编号
            DynamicObject yem_billtype = BusinessDataServiceHelper.loadSingle("bos_entityobject", new QFilter[]{new QFilter("number", QCP.equals, dynamicObject.getDynamicObjectType().getName())});
            yemIalog.set("yem_billtype", yem_billtype);//单据类型
            yemIalog.set("yem_success", false);//是否成功
            yemIalog.set("yem_req", json.toString());//请求参数
            if (ex instanceof KDException) {
                yemIalog.set("yem_error", ((KDException) ex).getStackTraceMessage());//异常信息
                addErrMessage(operationResult, dataEntity, "云之家接口调用异常：" + ((KDException) ex).getStackTraceMessage());
            } else {
                yemIalog.set("yem_error", ex.toString());//异常信息
                addErrMessage(operationResult, dataEntity, "云之家接口调用异常：" + ex.toString());
            }
            SaveServiceHelper.save(new DynamicObject[]{yemIalog});
        }
    }
    public static void submit2YZJ(OperationResult operationResult, List<DynamicObject> passDataEntitys, DynamicObject dynamicObject) {
        String billstatus = dynamicObject.getString("billstatus");
        dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.getLong("id"), dynamicObject.getDynamicObjectType().getName());

        Map map = new HashMap<>();
        map.put("entityName", dynamicObject.getDynamicObjectType().getName());
        if (dynamicObject.containsProperty("yem_billtype")) {
            map.put("billtype", dynamicObject.getString("yem_billtype.number"));
        }
        //TODO 订单产品需求单特殊处理
        if ("yem_orderproreqbill".equals(dynamicObject.getDynamicObjectType().getName())&&"yem_orderproreqbill_DB".equals(dynamicObject.getString("yem_billtype.number"))) {
            map.put("Stashtype", dynamicObject.getString("yem_isvmi"));
        }
        if("yem_placeexamine".equals(dynamicObject.getDynamicObjectType().getName())){
            map.put("yem_salesordertype",dynamicObject.getString("yem_salesordertype"));
        }
        //end by zhouc 2024-01-11
        if("yem_es_contactbook".equals(dynamicObject.getDynamicObjectType().getName())){
            map.put("yem_procbilltype",dynamicObject.getString("yem_procbilltype"));
        }
//        DynamicObject[] load = BusinessDataServiceHelper.load("yem_ia_intebilllogon", "id", new QFilter[]{null});
//        for (DynamicObject obj : load) {
//            obj = BusinessDataServiceHelper.loadSingle(obj.get("id"),"yem_ia_intebilllogon");
//            if(((MulBasedataDynamicObjectCollection)obj.get("yem_billtype")).size()>0){
//                System.out.println();
//            }
//        }
        JSONObject json = ObjectToJsonUtils.ObjectToJson(dynamicObject.get("id"), map);

//        dynamicObject.set("yem_synfalt",null);
        if (json.containsKey("errmessage")) {
            dynamicObject.set("billstatus",billstatus);
            SaveServiceHelper.update(dynamicObject);
            passDataEntitys.add(dynamicObject);
            return;
        }
        DynamicObject yem_billtype = BusinessDataServiceHelper.loadSingle("bos_entityobject", new QFilter[]{new QFilter("number", QCP.equals, dynamicObject.getDynamicObjectType().getName())});
        MainEntityType entityType = EntityMetadataCache.getDataEntityType("yem_ialog");
        DynamicObject yemIalog = new DynamicObject(entityType);
        try {
            String s = YunzhijiaUtils.doPost(YunzhijiaUtils.yzjurl+"/cmmpapi/cmmp/flowCreate.do?tokenId=0C89F5DBEB704C1F8671721B148E8224", json.toString());
            System.out.println(s);
            JSONObject retJson = JSONObject.parseObject(s);
            Boolean success = retJson.getBoolean("success");

            if (success) {
                dynamicObject.set("yem_synfalt",null);
                JSONObject data = retJson.getJSONObject("data");
                String formInstId = data.getString("formInstId");//表单定义ID
                String flowInstId = data.getString("flowInstId");//流程实例ID
                dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.get("id"), dynamicObject.getDynamicObjectType().getName());
                dynamicObject.set("yem_forminstid", formInstId);
                dynamicObject.set("yem_flowinstid", flowInstId);
                dynamicObject.set("yem_isyzjreject", false);
                SaveServiceHelper.update(dynamicObject, OperateOption.create());
                // 根据实体名构建元数据并创建DynamicObject
//                DynamicObject yemIalog = new DynamicObject(entityType);
                yemIalog.getDataEntityType().getPrimaryKey().setValueFast(yemIalog, ID.genLongId());
                yemIalog.set("billno", dynamicObject.get("billno"));//单据编号
//                DynamicObject yem_billtype = BusinessDataServiceHelper.loadSingle("bos_entityobject", new QFilter[]{new QFilter("number", QCP.equals, dynamicObject.getDynamicObjectType().getName())});
                yemIalog.set("yem_billtype", yem_billtype);//单据类型
                yemIalog.set("yem_success", success);//是否成功
                yemIalog.set("yem_req", json.toString());//请求参数
                yemIalog.set("billstatus", "A");//请求参数

                yemIalog.set("yem_response", s);//返回参数
                yemIalog.set("yem_flowinstid", flowInstId);//流程实例ID
                yemIalog.set("yem_forminstid", formInstId);//表单实例ID

                passDataEntitys.add(dynamicObject);
            } else {
                // 根据实体名构建元数据并创建DynamicObject
//                MainEntityType entityType = EntityMetadataCache.getDataEntityType("yem_ialog");
                yemIalog.getDataEntityType().getPrimaryKey().setValueFast(yemIalog, ID.genLongId());
                yemIalog.set("billstatus", "A");//请求参数
                yemIalog.set("billno", dynamicObject.get("billno"));//单据编号
//                DynamicObject yem_billtype = BusinessDataServiceHelper.loadSingle("bos_entityobject", new QFilter[]{new QFilter("number", QCP.equals, dynamicObject.getDynamicObjectType().getName())});
                yemIalog.set("yem_billtype", yem_billtype);//单据类型
                yemIalog.set("yem_success", false);//是否成功
                yemIalog.set("yem_req", json.toString());//请求参数
                yemIalog.set("yem_response", s);//返回参数
                JSONObject Json = JSONObject.parseObject(s);
//                SaveServiceHelper.save(new DynamicObject[]{yemIalog});
                addErrMessage(operationResult, dynamicObject, "云之家生成流程异常：\r\n异常编码为【"+Json.getString("errorCode")+"】异常信息为：" + Json.getString("error"));
            }
        } catch (Exception ex) {

            ex.printStackTrace();
            // 根据实体名构建元数据并创建DynamicObject
//            MainEntityType entityType = EntityMetadataCache.getDataEntityType("yem_ialog");
//            DynamicObject yemIalog = new DynamicObject(entityType);
            yemIalog.getDataEntityType().getPrimaryKey().setValueFast(yemIalog, ID.genLongId());
            yemIalog.set("billstatus", "A");//请求参数
            yemIalog.set("billno", dynamicObject.get("billno"));//单据编号

            yemIalog.set("yem_billtype", yem_billtype);//单据类型
            yemIalog.set("yem_success", false);//是否成功
            yemIalog.set("yem_req", json.toString());//请求参数
            if (ex instanceof KDException) {
                yemIalog.set("yem_error", ((KDException) ex).getStackTraceMessage());//异常信息
                addErrMessage(operationResult, dynamicObject, "云之家接口调用异常：" + ((KDException) ex).getStackTraceMessage());
            } else {
                yemIalog.set("yem_error", ex.toString());//异常信息
                addErrMessage(operationResult, dynamicObject, "云之家接口调用异常：" + ex.toString());
            }
            SaveServiceHelper.save(new DynamicObject[]{yemIalog});
        }
        SaveServiceHelper.save(new DynamicObject[]{yemIalog});
    }
    /**
     * 向操作结果，添加一条错误提示
     *
     * @param operationResult 操作结果参数
     * @param dataEntity      校验数据
     * @param errMsg          异常信息
     * @return
     */
    private static void addErrMessage(OperationResult operationResult, DynamicObject dataEntity, String errMsg) {
        operationResult.setSuccess(false);
        Object pkId = dataEntity.getPkValue();
        int rowIndex = 0;
        ErrorLevel errorLevel = ErrorLevel.Error;

        ValidationErrorInfo errInfo = new ValidationErrorInfo("",
                pkId, 0, rowIndex,
                "BeforeExecuteOperationTransactionSample",
                "接口调用异常",
                "单据编号：【" + dataEntity.get("billno") + "】" + errMsg,
                errorLevel);
        operationResult.setMessage("提交失败");
        operationResult.addErrorInfo(errInfo);
    }
    /**
     * 向操作结果，添加一条错误提示
     *
     * @param operationResult 操作结果参数
     * @param dataEntity      校验数据
     * @param errMsg          异常信息
     * @return
     */
    private static void addErrMessage(OperationResult operationResult, ExtendedDataEntity dataEntity, String errMsg) {
        operationResult.setSuccess(false);
        Object pkId = dataEntity.getDataEntity().getPkValue();
        int dataIndex = dataEntity.getDataEntityIndex();
        int rowIndex = 0;
        ErrorLevel errorLevel = ErrorLevel.Error;

        ValidationErrorInfo errInfo = new ValidationErrorInfo("",
                pkId, dataIndex, rowIndex,
                "BeforeExecuteOperationTransactionSample",
                "接口调用异常",
                "单据编号：【" + dataEntity.getDataEntity().get("billno") + "】" + errMsg,
                errorLevel);

        operationResult.addErrorInfo(errInfo);
    }

    /**
     * 获取云之家Token
     *
     * @return
     */
    public static String getYzhToken() {
        //获取云之家token
        String url = YunzhijiaUtils.yzjurl+"/cmmpapi/cmmp/fileToken.do?tokenId=D4EB05B9FE9C41D0868D33EC92AAEDB4";
        String accessToken = null;
        try {
            String Token = YunzhijiaUtils.doPost(url, "");
            JSONObject json = JSONObject.parseObject(Token);
            Boolean success = json.getBoolean("success");
            if (success) {
                JSONObject data = json.getJSONObject("data");
                accessToken = data.getString("accessToken");
            }
        } catch (Exception ex) {
            throw new KDBizException(ex.toString());
        }
        return accessToken;
    }

    /**
     * 云之家文件上传
     *
     * @param fileurl     文件下载地址
     * @param accessToken 云之家Token
     * @param filename    附件名称
     * @return 请求结果
     */
    public static String uploadfile(String fileurl, String accessToken, String filename) {
        String result = null;
        try {
            byte[] byt = getUrlFileData(fileurl);
            MultipartFile multipartFile = getMultipartFile(filename, byt);
            Map<String, String> map = new HashMap<>();
            map.put("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.24");
            map.put("ContentType", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
            map.put("x-accessToken", accessToken);
            map.put("Cache-Control", "no-cache");
            String url = "https://yunzhijia.com/docrest/doc/file/uploadfile";
            //  result = YunzhijiaUtils.doPost("https://yunzhijia.com/docrest/doc/file/uploadfile", byt, accessToken, filename);
            result = doPostFormData(url, "file", multipartFile, new HashMap<>(), map);
        } catch (Exception ex) {
            String message = ex.getMessage();
            throw new KDBizException(message);
        }
        return result;
    }

    /**
     *  文件下载
     * @param fileId  文件id
     * @param accessToken 调用接口Token
     * @return
     */
    public static byte[] downloadfile(String fileId, String accessToken) {
        byte[] result = null;
        try {
            Map<String, String> map = new HashMap<>();
            map.put("Cache-Control", "no-cache");
            map.put("x-accessToken", accessToken);
            String url = "https://yunzhijia.com/docrest/doc/user/downloadfile?fileId=" + fileId;
            result = doGet(url, map);
        } catch (Exception ex) {
            String message = ex.getMessage();
            throw new KDBizException(message);
        }
        return result;
    }

    /**
     * 获取下载地址文件流
     *
     * @param fileUrl
     * @return
     * @throws Exception
     */
    public static byte[] getUrlFileData(String fileUrl) throws Exception {
        URL url = new URL(fileUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.connect();
        InputStream cin = httpConn.getInputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = cin.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        cin.close();
        byte[] fileData = outStream.toByteArray();
        outStream.close();
        return fileData;
    }

    /**
     * 二进制文件转MultipartFile
     *
     * @param name  文件名称
     * @param bytes 二进制流
     * @return
     */
    public static MultipartFile getMultipartFile(String name, byte[] bytes) {
        MultipartFile mfile = null;
        ByteArrayInputStream in = null;
        try {
            in = new ByteArrayInputStream(bytes);
            FileItemFactory factory = new DiskFileItemFactory(16, null);
            FileItem fileItem = factory.createItem("mainFile", "text/plain", false, name);
            IOUtils.copy(new ByteArrayInputStream(bytes), fileItem.getOutputStream());
            mfile = new CommonsMultipartFile(fileItem);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mfile;
    }

    /**
     * 以post方式调用第三方接口,以form-data 形式  发送 MultipartFile 文件数据
     *
     * @param url           post请求url
     * @param fileParamName 文件参数名称
     * @param multipartFile 文件
     * @param paramMap      表单里其他参数
     * @param map           头参数
     * @return
     */
    public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, String> paramMap, Map<String, String> map) {
        // 创建Http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建HttpPost实例
        HttpPost httpPost = new HttpPost(url);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
        // 请求参数配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);

        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            String fileName = multipartFile.getOriginalFilename();
            // 文件流
            builder.addTextBody("bizkey", "cloudflow");
            builder.addBinaryBody(fileParamName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            //表单中其他参数
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
            }

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
                return res;
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用HttpPost失败！" + e.toString());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    System.out.println("关闭HttpPost连接失败！");
                }
            }
        }
        return null;
    }


    /**
     * 发送 GET 请求（HTTP），K-V形式
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static byte[] doGet(String url, Map<String, String> params) throws IOException {
        byte[] result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            //表单中其他参数
            for (Map.Entry<String, String> entry : params.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
            response = httpclient.execute(httpGet);

            entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = org.apache.commons.io.IOUtils.toByteArray(instream);
//                result = org.apache.commons.io.IOUtils.toString(instream, "UTF-8");
            }
        } finally {
            // 最后别忘了关闭应该关闭的资源，适当的释放资源
            try {
                // 这个方法也可以把底层的流给关闭了
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 字节转FileInputStream
     *
     * @param bytes
     * @return
     */
    public static FileInputStream byteToFile(byte[] bytes, String fileName) {
        File file = new File(fileName);
        FileInputStream fileInputStream = null;
        try {
            OutputStream output = new FileOutputStream(file);
            BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
            bufferedOutput.write(bytes);
            fileInputStream = new FileInputStream(file);
            file.deleteOnExit();
            return fileInputStream;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileInputStream;
    }

}
