package com.zfire.jiasm.syncdata.gree;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.zfire.jiasm.syncdata.constant.Constant;
import com.zfire.jiasm.syncdata.exception.RemoteServiceException;
import com.zfire.jiasm.syncdata.helper.*;
import com.zfire.jiasm.syncdata.http.HttpUtil;
import com.zfire.jiasm.syncdata.http.HttpUtils;
import com.zfire.jiasm.syncdata.request.FileSub;
import com.zfire.jiasm.syncdata.request.UploadFileInfo;
import com.zfire.jiasm.syncdata.request.UploadImageInfo;
import com.zfire.jiasm.syncdata.response.ExtData;
import com.zfire.jiasm.syncdata.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import javax.activation.MimetypesFileTypeMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import static com.zfire.jiasm.syncdata.utils.HttpUtil.trustAllHttpsCertificates;

/**
 * 格力总部接口
 */
@Slf4j
@Service
public class GreeLogic {
    private static RequestConfig requestConfig = null;
    private static HttpClientBuilder httpBuilder = null;

    @Value("${gree.gz.appid}")
    private String gzAppId;
    @Value("${gree.fs.appid}")
    private String fsAppId;
    @Value("${gree.tm.appid}")
    private String tmAppId;
    @Value("${uploadbaseurl}")
    private String uploadbaseurl;
    @Value("${sevefileurl}")
    private String sevefileurl;
    @Value("${downfileurl}")
    private String downfileurl;
    @Value("${gree.gz.appkey}")
    private String gzAppKey;
    @Value("${gree.fs.appkey}")
    private String fsAppKey;
    @Value("${gree.client.id}")
    private String clientId;
    @Value("${gree.V3.client.secert}")
    private String clientSecert;
    @Value("${gree.V3.gettoken}")
    private String tokenUrl;
    @Value("${imagesign}")
    private String imagesignUrl;
    @Value("${imageurl}")
    private String imageurl;
    @Value("${gree.file.client.id}")
    private String clientFileId;
    @Value("${gree.V3.client.file.secert}")
    private String clientFileSecert;
    @Value("${gree.gettoken}")
    private String tokenFileUrl;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    CommonLogic commonLogic;

    public String getAppId(Integer belongType){
        if(belongType == 1){
            return fsAppId;
        } else if(belongType == 2){
            return gzAppId;
        } else {
            return tmAppId;
        }
    }

    public String getAppKey(Integer belongType){
        if(belongType == 1){
            return gzAppKey;
        }else{
            return fsAppKey;
        }
    }

    /**
     * 获取总部接口的请求token
     * @return
     * @throws RemoteServiceException
     */
    public String getAccessToken() throws RemoteServiceException {
        String redisKey = Constant.RedisPrefix.TOKEN_GREE;
        String token = (String)redisUtil.get(redisKey);
        if(token != null){
            return token;
        }
        MultiValueMap<String, String> forms= new LinkedMultiValueMap<String, String>();

        forms.put("client_id", Collections.singletonList(clientId));
        forms.put("client_secret", Collections.singletonList(clientSecert));
        forms.put("grant_type", Collections.singletonList("client_credentials"));
        String s = HttpUtils.requestXwww(tokenUrl, forms);
        //String s = HttpUtils.requestPostForm(tokenUrl, map, null);
        // log.info("【获取总部token】response:{}",s);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String accessToken = jsonObject.getString("access_token");
        if(StringUtils.isNotEmpty(accessToken)) {
            redisUtil.set(Constant.RedisPrefix.TOKEN_GREE, accessToken, 2 * 60 * 60);
        }
        return accessToken;
    }

    public String getAccessTokenFile() throws RemoteServiceException {
        /*String redisKey = Constant.RedisPrefix.TOKEN_GREE_FILE;
        String token = (String)redisUtil.get(redisKey);
        if(token != null){
            return token;
        }*/
        MultiValueMap<String, String> forms= new LinkedMultiValueMap<String, String>();

        forms.put("client_id", Collections.singletonList(clientFileId));
        forms.put("client_secret", Collections.singletonList(clientFileSecert));
        forms.put("grant_type", Collections.singletonList("client_credentials"));
        String s = HttpUtils.requestXwww(tokenFileUrl, forms);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String accessToken = jsonObject.getString("access_token");
        /*if(StringUtils.isNotEmpty(accessToken)) {
            redisUtil.set(Constant.RedisPrefix.TOKEN_GREE_FILE, accessToken, 2 * 60 * 60);
        }*/
        return accessToken;
    }

    /**
     * 请求总部接口
     * @return
     */
    public String post(String apiPath,Map<String,Object> bizContent,Integer belongType) throws Exception {
        CommonParam commonParam = new CommonParam();
        commonParam.setAppId(this.getAppId(belongType));
        commonParam.setAppKey(this.getAppKey(belongType));
        commonParam.setAppPath(apiPath);
        commonParam.setJson(JSONObject.toJSONString(bizContent));
        OutAppDefaultReq outAppDefaultReq = commonLogic.supplyParam(commonParam);
        Map<String,String> header = new HashMap<>();
        header.put("authorization","Bearer "+this.getAccessToken());
        //log.info("accessToken:{}", "Bearer "+this.getAccessToken());

        //log.info("【请求总部接口】request:{}",JSONObject.toJSONString(outAppDefaultReq));
        String s = HttpUtils.requestPostBody(uploadbaseurl, JSONObject.toJSONString(outAppDefaultReq), header);
        //log.info("【请求总部接口】response:{}",s);
        GreeResponseHelper greeResponseHelper = JSONObject.parseObject(s, GreeResponseHelper.class);
        if(greeResponseHelper.getStatus() != 200){
            throw new RemoteServiceException("对接失败总部接口失败:"+greeResponseHelper.getMsg());
        }
        return (String)greeResponseHelper.getData();
    }

    public JSONObject post(String url,List param){
    	Map<String, String> header = new HashMap<>();
        header.put("authorization", "Bearer " + this.getAccessToken());
        log.info("【总部接口对接】request:{}",  JSON.toJSONString(param));
        String s = HttpUtils.requestPostBody(url, JSON.toJSONString(param), header);
        log.info("【总部接口对接】response:{}",s);

        JSONObject jsonObject = JSONObject.parseObject(s);
        Integer statusCode = jsonObject.getInteger("status");
        if (statusCode != 200) {
            log.error("接口地址：{}，对接总部接口失败",url);
            return null;
        }
        return jsonObject;
    }

    private JSONObject post(String url,Map<String,Object> map){
        Map<String, String> header = new HashMap<>();
        header.put("authorization", "Bearer " + this.getAccessToken());
        log.info("【总部接口对接】request:{}",JSONObject.toJSONString(map));
        String s = HttpUtils.requestPostBody(url, JSONObject.toJSONString(map), header);
        log.info("【总部接口对接】response:{}",s);
        JSONObject jsonObject = JSONObject.parseObject(s);
        Integer statusCode = jsonObject.getInteger("statusCode");
        if (statusCode != 200) {
            log.error("接口地址：{}，对接总部接口失败",url);
            return null;
        }
        return jsonObject;
    }

    /**
     * 请求总部接口
     * @return
     */
    public GreeResponseHelper greePost(String apiPath,String bizContent,Integer belongType) throws Exception {
        CommonParam commonParam = new CommonParam();
        commonParam.setAppId(this.getAppId(belongType));
        commonParam.setAppKey(this.getAppKey(belongType));
        commonParam.setAppPath(apiPath);
        commonParam.setJson(bizContent);
        OutAppDefaultReq outAppDefaultReq = commonLogic.supplyParam(commonParam);
        Map<String,String> header = new HashMap<>();
        header.put("authorization","Bearer "+this.getAccessToken());
        // log.info("【请求总部接口】request:{}",JSONObject.toJSONString(outAppDefaultReq));

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        for(String str : header.keySet()){
            headers.set(str,header.get(str));
        }

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(outAppDefaultReq), headers);
        //获取返回数据
        try {
            String body = restTemplate.postForObject(uploadbaseurl, httpEntity, String.class);
            //log.info("【请求总部接口】response:{}",body);
            return JSONObject.parseObject(body, GreeResponseHelper.class);
        }catch(HttpStatusCodeException ex) {
            log.error("rawStatusCode = {}",ex.getRawStatusCode());
            GreeResponseHelper greeResponseHelper = new GreeResponseHelper();
            greeResponseHelper.setStatus(ex.getRawStatusCode());
//        	greeResponseHelper.setMsg(GreeResponseCodeEnum.valueOf(ex.getRawStatusCode()));
            greeResponseHelper.setMsg(ex.getMessage());
            ex.printStackTrace();
            return greeResponseHelper;
        }catch(Exception e){
            GreeResponseHelper greeResponseHelper = new GreeResponseHelper();
            greeResponseHelper.setStatus(ResponseHelper.ResponseCode_COMMON);
            greeResponseHelper.setMsg("非法请求");
            e.printStackTrace();
            return greeResponseHelper;
        }
    }

    public GreeFileSaveHelper greePostSaveFile(Map<String,String> req) throws Exception {
        GreeFileSaveHelper greeResponseHelper = new GreeFileSaveHelper();

        Map<String,String> header = new HashMap<>();
        header.put("authorization","Bearer "+this.getAccessTokenFile());

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        for(String str : header.keySet()){
            headers.set(str,header.get(str));
        }

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(req), headers);
        //获取返回数据
        try {
            String body = restTemplate.postForObject(sevefileurl, httpEntity, String.class);
            log.info("【请求总部接口保存文件】request:{}",body);
            greeResponseHelper = JSONObject.parseObject(body, GreeFileSaveHelper.class);

            return greeResponseHelper;
        }catch(HttpStatusCodeException ex) {
            log.error("rawStatusCode = {}",ex.getRawStatusCode());
            greeResponseHelper.setStatusCode(ex.getRawStatusCode());
            greeResponseHelper.setMsg(ex.getMessage());
            ex.printStackTrace();
            return greeResponseHelper;
        }catch(Exception e){
            greeResponseHelper.setStatusCode(ResponseHelper.ResponseCode_COMMON);
            greeResponseHelper.setMsg("非法请求");
            e.printStackTrace();
            return greeResponseHelper;
        }
    }

    // 下载文件
    public String greeFileUrl(String id) throws Exception {
        return  String.format(downfileurl,id,this.getAccessTokenFile());
    }






    /**
     * 请求总部接口
     * @return
     */
    public GreeResponseHelper greePostImage(String apiPath, String bizContent,Integer belongType) throws Exception {
        CommonParam commonParam = new CommonParam();
        commonParam.setAppId(this.getAppId(belongType));
        commonParam.setAppKey(this.getAppKey(belongType));
        commonParam.setAppPath(apiPath);
        commonParam.setJson(bizContent);
        OutAppDefaultReq outAppDefaultReq = commonLogic.supplyParam(commonParam);
        Map<String,String> header = new HashMap<>();

        // this.getSignImage();


        header.put("authorization","Bearer ");

        //log.info("【请求总部接口】request:{}",JSONObject.toJSONString(outAppDefaultReq));
        //log.info("imageurl:{}",imageurl);
        //log.info("apiPath:{}",apiPath);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        for(String str : header.keySet()){
            headers.set(str,header.get(str));
        }

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(outAppDefaultReq), headers);
        //获取返回数据
        try {
            String body = restTemplate.postForObject(imageurl, httpEntity, String.class);
            //log.info("【请求总部接口】response:{}",body);
            return JSONObject.parseObject(body, GreeResponseHelper.class);
        }catch(HttpStatusCodeException ex) {
            log.error("rawStatusCode = {}",ex.getRawStatusCode());
            GreeResponseHelper greeResponseHelper = new GreeResponseHelper();
            greeResponseHelper.setStatus(ex.getRawStatusCode());
//        	greeResponseHelper.setMsg(GreeResponseCodeEnum.valueOf(ex.getRawStatusCode()));
            greeResponseHelper.setMsg(ex.getMessage());
            ex.printStackTrace();
            return greeResponseHelper;
        }catch(Exception e){
            GreeResponseHelper greeResponseHelper = new GreeResponseHelper();
            greeResponseHelper.setStatus(ResponseHelper.ResponseCode_COMMON);
            greeResponseHelper.setMsg("非法请求");
            e.printStackTrace();
            return greeResponseHelper;
        }
    }

    /**
     * 请求总部接口
     * @return
     */
    // 上传文件
    public GreeResponseHelper greePostImageUpload(String fileName, ExtData data) throws IOException {
        UploadImageInfo req = new UploadImageInfo();
        UploadFileInfo reqIfo = new UploadFileInfo();
        FileSub sub = new FileSub();

        reqIfo.getMultipart().clear();

        // 文件数组
         byte[] fileBinary = getBytesFile(fileName);
        // String fileBinary = getFileBinary(fileName);

        // 生成对象
        getReq(data, req, fileBinary);
        sub.setName("key");
        sub.setContents(data.getDir());
        reqIfo.getMultipart().add(sub);
        FileSub sub1 = new FileSub();
        sub1.setName("OSSAccessKeyId");
        sub1.setContents(data.getAccessid());
        reqIfo.getMultipart().add(sub1);
        FileSub sub2 = new FileSub();
        sub2.setName("policy");
        sub2.setContents(data.getPolicy());
        reqIfo.getMultipart().add(sub2);
        FileSub sub3 = new FileSub();
        sub3.setName("Signature");
        sub3.setContents(data.getSignature());
        reqIfo.getMultipart().add(sub3);
        FileSub sub4 = new FileSub();
        sub4.setName("Expires");
        sub4.setContents(data.getExpire());
        reqIfo.getMultipart().add(sub4);
        FileSub sub5 = new FileSub();
        sub5.setName("success_action_status");
        sub5.setContents(200);
        reqIfo.getMultipart().add(sub5);



        FileSub sub6 = new FileSub();

        sub6.setName("file");
        sub6.setContents(getFileBinary(fileName));


        reqIfo.getMultipart().add(sub6);
        log.info("url:{}",data.getHost());
        // 设置请求头
        Map<String,String> headers = new HashMap<>();
        headers.put("Content-Type", "multipart/form-data");

        //获取返回数据
        try {
            String s = HttpUtils.requestPostBodyt(data.getHost(), JSON.toJSONString(reqIfo), headers);
            log.info("【上传文件结束】response:{}",s);
            return JSONObject.parseObject(s, GreeResponseHelper.class);
        }catch(HttpStatusCodeException ex) {
            log.error("rawStatusCode = {}",ex.getRawStatusCode());
            GreeResponseHelper greeResponseHelper = new GreeResponseHelper();
            greeResponseHelper.setStatus(ex.getRawStatusCode());
            greeResponseHelper.setMsg(ex.getMessage());
            ex.printStackTrace();
            return greeResponseHelper;
        }catch(Exception e){
            GreeResponseHelper greeResponseHelper = new GreeResponseHelper();
            greeResponseHelper.setStatus(ResponseHelper.ResponseCode_COMMON);
            greeResponseHelper.setMsg("非法请求");
            e.printStackTrace();
            return greeResponseHelper;
        }

    }

    public GreeResponseHelper greePostImageUploadt(String fileName, ExtData data) throws IOException {
        Map<String,Object> request = new HashMap<>();
        // 生成报文
        getReqx(data, request,fileName);

        log.info("url:{}",data.getHost());
        // 设置请求头
        Map<String,String> headers = new HashMap<>();
        headers.put("Content-Type", "multipart/form-data");

        //获取返回数据
        try {

            String s = HttpUtils.requestPostBody(data.getHost(), JSON.toJSONString(request), headers);

            log.info("【上传文件结束】response:{}",s);
            return JSONObject.parseObject(s, GreeResponseHelper.class);
        }catch(HttpStatusCodeException ex) {
            log.error("rawStatusCode = {}",ex.getRawStatusCode());
            GreeResponseHelper greeResponseHelper = new GreeResponseHelper();
            greeResponseHelper.setStatus(ex.getRawStatusCode());
            greeResponseHelper.setMsg(ex.getMessage());
            ex.printStackTrace();
            return greeResponseHelper;
        }catch(Exception e){
            GreeResponseHelper greeResponseHelper = new GreeResponseHelper();
            greeResponseHelper.setStatus(ResponseHelper.ResponseCode_COMMON);
            greeResponseHelper.setMsg("非法请求");
            e.printStackTrace();
            return greeResponseHelper;
        }

    }


    public String greePostImageUploadtt(String fileName, ExtData data) throws RemoteServiceException, IOException {
        MultiValueMap<String, String> forms= new LinkedMultiValueMap<String, String>();
        Map<String,String> headers = new HashMap<>();

        forms.put("key",Collections.singletonList(data.getDir()));
        forms.put("OSSAccessKeyId",Collections.singletonList(data.getAccessid()));
        forms.put("policy",Collections.singletonList(data.getPolicy()));
        forms.put("Signature",Collections.singletonList(data.getSignature()));
        forms.put("Expires",Collections.singletonList(data.getExpire()));
        forms.put("success_action_status",Collections.singletonList("200"));
        forms.put("file",Collections.singletonList(getFileBinary(fileName)));

        // 设置请求头
        headers.put("Content-Type", "multipart/form-data");

        // requestPostForm
        String s = HttpUtils.requestXwww(data.getHost(), forms);
        log.info("【上传文件结束】response:{}",s);

        return s;
    }


    public String greePostImageUploadttt(String fileName, ExtData data) throws IOException {
        Map<String, String> forms= new HashMap<>();
        Map<String,String> headers = new HashMap<>();

        forms.put("key",data.getDir());
        forms.put("OSSAccessKeyId",data.getAccessid());
        forms.put("policy",data.getPolicy());
        forms.put("Signature",data.getSignature());
        forms.put("Expires",data.getExpire());
        forms.put("success_action_status","200");
        forms.put("file",getFileBinary(fileName));

        // 设置请求头
        headers.put("Content-Type", "multipart/form-data");

        // requestPostForm
        String s = HttpUtils.requestPostForm(data.getHost(), forms,headers);
        log.info("【上传文件结束】response:{}",s);

        return s;
    }


    public String greePostImageUploadz(String fileName, ExtData data) throws IOException {
        Map<String,Object> request = new HashMap<>();
        Map<String,String> headers = new HashMap<>();
        String resultData = "";

        // 生成报文
        getReqx(data, request,fileName);

        // 设置请求头
        headers.put("Content-Type", "multipart/form-data");

        log.info("url:{}",data.getHost());

        //获取返回数据
        try {
            // HttpRequest requestt =cn.hutool.http.HttpUtil.createPost(data.getHost());
            // resultData = HttpUtils.sendData(data.getHost(),JSONObject.toJSONString(request));

            resultData = cn.hutool.http.HttpUtil.post(data.getHost(),request);

            log.info("【上传文件结束】response: {}",resultData);
            return resultData;
        }catch(HttpStatusCodeException ex) {
            log.error("rawStatusCode = {}",ex.getRawStatusCode());
            ex.printStackTrace();
            return ex.getMessage();
        }catch(Exception e){
            e.printStackTrace();
            return "非法请求";
        }

    }



    public String greePostImageUploado(String fileName, ExtData data) throws RemoteServiceException, IOException {
        MultiValueMap<String, String> forms= new LinkedMultiValueMap<String, String>();

        forms.put("key",Collections.singletonList(data.getDir()));
        forms.put("OSSAccessKeyId",Collections.singletonList(data.getAccessid()));
        forms.put("policy",Collections.singletonList(data.getPolicy()));
        forms.put("Signature",Collections.singletonList(data.getSignature()));
        forms.put("Expires",Collections.singletonList(data.getExpire()));
        forms.put("success_action_status",Collections.singletonList("200"));
        forms.put("file",Collections.singletonList(getFileBinary(fileName)));

        String s = HttpUtils.requestXww(data.getHost(), forms);
        log.info("【文件上传】response:{}",s);
        // JSONObject jsonObject = JSONObject.parseObject(s);
        // String accessToken = jsonObject.getString("access_token");

        return s;
    }


    public void greePostImagefile(String fileName, ExtData data) throws RemoteServiceException, IOException {
        MultiValueMap<String, Object> forms= new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate = new RestTemplate();

        // multipart/form-data
        headers.setContentType(MediaType.valueOf("multipart/form-data"));

        forms.put("key",Collections.singletonList(data.getDir()));
        forms.put("OSSAccessKeyId",Collections.singletonList(data.getAccessid()));
        forms.put("policy",Collections.singletonList(data.getPolicy()));
        forms.put("Signature",Collections.singletonList(data.getSignature()));
        forms.put("Expires",Collections.singletonList(data.getExpire()));
        forms.put("success_action_status",Collections.singletonList(200));
        log.info("forms: {}",forms);

        forms.put("file",Collections.singletonList(getFileBinary(fileName)));
        HttpEntity<MultiValueMap<String, Object>> requestParams = new HttpEntity<>(forms,headers);
        ResponseEntity<String> response = restTemplate.postForEntity(data.getHost(),requestParams,String.class);


        log.info("【文件上传结果】response:{}",response);

    }


    public String greePostImagefilet(String fileName, ExtData data) throws RemoteServiceException, IOException {
        String strResult = "";
        Map<String,Object> map = new HashMap<>();
        map.put("key",data.getDir());
        map.put("OSSAccessKeyId",data.getAccessid());
        map.put("policy",data.getPolicy());
        map.put("Signature",data.getSignature());
        map.put("Expires",data.getExpire());
        map.put("success_action_status",200);
        map.put("file",getFileBinary(fileName));
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(data.getHost());
        httpPost.setHeader("Content-Type","multipart/form-data");
        List<NameValuePair> paramPairs = new ArrayList<>();
        Set<String> keySet = map.keySet();
        for (String key : keySet){
            Object val = map.get(key);
            paramPairs.add(new BasicNameValuePair(key,val.toString()));
        }
        UrlEncodedFormEntity entity;
        try{
            entity = new UrlEncodedFormEntity(paramPairs,"UTF-8");
            log.info("参数：{}", entity);
            httpPost.setEntity(entity);
            CloseableHttpResponse resp = client.execute(httpPost);
            try {
                log.info("resp：{}", resp);

                HttpEntity respEntity = (HttpEntity) resp.getEntity();
                strResult = EntityUtils.toString((org.apache.http.HttpEntity) respEntity,"UTF-8");
            } finally {
                resp.close();
            }
        } catch (ClientProtocolException e){
            e.printStackTrace();
        } catch (UnsupportedEncodingException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (Exception e){
                e.printStackTrace();
            }
            log.info("end ：{}", strResult);
            return strResult;
        }

    }



    /**
     * 测试上传图片
     *
     */
    public static void testUploadImage(String fileName, ExtData data){
        String url = data.getHost();

        Map<String, String> textMap = new HashMap<String, String>();
        //可以设置多个input的name，value
        textMap.put("key",data.getDir());
        textMap.put("OSSAccessKeyId",data.getAccessid());
        textMap.put("policy",data.getPolicy());
        textMap.put("Signature",data.getSignature());
        textMap.put("Expires",data.getExpire());
        textMap.put("success_action_status","200");

        //设置file的name，路径
        Map<String, String> fileMap = new HashMap<String, String>();
        fileMap.put("upfile", fileName);
        String contentType = "";//image/png
        String ret = formUpload(url, textMap, fileMap,contentType);
        log.info("ret: {}",ret);
    }

    /**
     * 上传图片
     * @param urlStr
     * @param textMap
     * @param fileMap
     * @param contentType 没有传入文件类型默认采用application/octet-stream
     * contentType非空采用filename匹配默认的图片类型
     * @return 返回response数据
     */
    @SuppressWarnings("rawtypes")
    public static String formUpload(String urlStr, Map<String, String> textMap,
                                    Map<String, String> fileMap,String contentType) {
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            // conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
            // file
            if (fileMap != null) {
                Iterator iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    File file = new File(inputValue);
                    String filename = file.getName();

                    //没有传入文件类型，同时根据文件获取不到类型，默认采用application/octet-stream
                    contentType = new MimetypesFileTypeMap().getContentType(file);
                    //contentType非空采用filename匹配默认的图片类型
                    if(!"".equals(contentType)){
                        if (filename.endsWith(".png")) {
                            contentType = "image/png";
                        }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                            contentType = "image/jpeg";
                        }else if (filename.endsWith(".gif")) {
                            contentType = "image/gif";
                        }else if (filename.endsWith(".ico")) {
                            contentType = "image/image/x-icon";
                        }
                    }
                    if (contentType == null || "".equals(contentType)) {
                        contentType = "application/octet-stream";
                    }
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    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();
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.out.println("发送POST请求出错。" + urlStr);
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }


    private void getReq(ExtData data, UploadImageInfo req, byte[] bytesArray) {
        req.setKey(data.getDir());
        req.setOSSAccessKeyId(data.getAccessid());
        req.setPolicy(data.getPolicy());
        req.setSignature(data.getSignature());
        req.setExpires(data.getExpire());
        req.setSuccess_action_status(200);

        log.info("req: {}",req);

        // req.setFile(bytesArray);
    }


    private void getReqx(ExtData data, Map<String,Object> req, String fileName) throws IOException {
        req.put("key",data.getDir());
        req.put("OSSAccessKeyId",data.getAccessid());
        req.put("policy",data.getPolicy());
        req.put("Signature",data.getSignature());
        req.put("Expires",data.getExpire());
        req.put("success_action_status",200);

        req.put("file",getFileBinary(fileName));
    }


    @NotNull
    private byte[] getBytesFile(String fileName) throws IOException {
        File file = new File(fileName);
        byte[] bytesArray = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(bytesArray);
        fis.close();
        return bytesArray;
    }

    @NotNull
    public static String getFileBinary(String fileName) throws IOException {
        File file = new File(fileName);
        String string = FileUtil.readUtf8String(file);
        return string;

    }

    /**
     * 请求总部接口-获取签名
     *
     * @return
     */
    public GreeFileResponseHelper ossGetSignt (String wdno, String requestMethod) throws Exception {
        StringBuffer buffer = new StringBuffer();
        HttpURLConnection httpUrlConn = null;
        GreeFileResponseHelper greeResponseHelper = new GreeFileResponseHelper();

        try {
            trustAllHttpsCertificates();
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            URL url = new URL(String.format(imagesignUrl,wdno));
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setConnectTimeout(30000);
            httpUrlConn.setReadTimeout(30000);
            httpUrlConn.setRequestProperty("Authorization", "Bearer " + this.getAccessTokenFile());
            httpUrlConn.setRequestProperty("Accept", "*/*");
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }
            InputStream inputStream;
            if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpUrlConn.getInputStream();
            } else {
                inputStream = httpUrlConn.getErrorStream();
            }

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();
            String result = buffer.toString();
            //log.info("【请求总部接口】response:{}", result);
            greeResponseHelper = JSONObject.parseObject(result, GreeFileResponseHelper.class);
            return greeResponseHelper;
        } catch (HttpStatusCodeException ex) {
            httpUrlConn.disconnect();
            log.error("rawStatusCode = {}", ex.getRawStatusCode());
            greeResponseHelper.setStatusCode(ex.getRawStatusCode());
            greeResponseHelper.setMsg(ex.getMessage());
            ex.printStackTrace();
            return greeResponseHelper;
        } catch (Exception e) {
            httpUrlConn.disconnect();
            greeResponseHelper.setStatusCode(ResponseHelper.ResponseCode_COMMON);
            greeResponseHelper.setMsg("非法请求");
            e.printStackTrace();
            return greeResponseHelper;
        }
    }

    /**
     * 请求总部接口-获取签名
     * @return
     */
    public JSONObject greeGetSign(String requestUrl, String requestMethod) throws Exception{
        JSONObject jsonresult = null;
        StringBuffer buffer = new StringBuffer();
        HttpURLConnection httpUrlConn = null;

        try {
            trustAllHttpsCertificates();
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            URL url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setConnectTimeout(30000);
            httpUrlConn.setReadTimeout(30000);
            httpUrlConn.setRequestProperty("Authorization", "Bearer "+this.getAccessTokenFile());
            httpUrlConn.setRequestProperty("Accept", "*/*");
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod)){
                httpUrlConn.connect();
            }

            log.info("获取签名 Url: {}",requestUrl);
            InputStream inputStream;
            if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpUrlConn.getInputStream();
            } else {
                inputStream = httpUrlConn.getErrorStream();
            }

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();
            String result = buffer.toString();

            log.info("获取答名结果：{}",result);

            jsonresult = JSONObject.parseObject(result);
        } catch (ConnectException ce) {
            log.error("发生错误", ce);
            throw ce;
        } catch (Exception e) {
            log.error("发生错误", e);
            throw e;
        } finally {
            try {
                httpUrlConn.disconnect();
            } catch (Exception e) {
                log.error("发生错误", e);
            }
        }
        return jsonresult;
    }






    /**
     * 请求总部接口-获取签名
     * @return
     */
    public JSONObject greeGetSignBack(String requestUrl, String requestMethod) throws Exception{
        JSONObject jsonresult = null;
        StringBuffer buffer = new StringBuffer();
        HttpURLConnection httpUrlConn = null;

        try {
            trustAllHttpsCertificates();
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            URL url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setConnectTimeout(30000);
            httpUrlConn.setReadTimeout(30000);
            httpUrlConn.setRequestProperty("Authorization", "Bearer "+this.getAccessTokenFile());
            httpUrlConn.setRequestProperty("Accept", "*/*");
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod)){
                httpUrlConn.connect();
            }

            log.info("获取签名 Url: {}",requestUrl);
            InputStream inputStream;
            if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpUrlConn.getInputStream();
            } else {
                inputStream = httpUrlConn.getErrorStream();
            }

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();
            String result = buffer.toString();

            log.info("获取答名结果：{}",result);

            jsonresult = JSONObject.parseObject(result);
        } catch (ConnectException ce) {
            log.error("发生错误", ce);
            throw ce;
        } catch (Exception e) {
            log.error("发生错误", e);
            throw e;
        } finally {
            try {
                httpUrlConn.disconnect();
            } catch (Exception e) {
                log.error("发生错误", e);
            }
        }
        return jsonresult;
    }


    public static Map<String, Object> httpGet(String url) throws Exception {
        log.info("url：{}",url);
        return HttpUtil.httpGet(url);
    }


    /**
     * 获取http客户端连接
     *
     * @return http客户端连接
     */
    public static CloseableHttpClient getConnection() {
        return httpBuilder.build();
    }



    /**
     * 请求总部接口
     * @return
     */
    public GreeResponseHelperOther greePostOther(String url,String bizContent) throws Exception {
        Map<String,String> header = new HashMap<>();
        header.put("authorization","Bearer "+this.getAccessToken());
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        for(String str : header.keySet()){
            headers.set(str,header.get(str));
        }

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> httpEntity = new HttpEntity<>(bizContent, headers);

        //获取返回数据
        try {
            String body = restTemplate.postForObject(url, httpEntity, String.class);
            return JSONObject.parseObject(body, GreeResponseHelperOther.class);
        }catch(HttpStatusCodeException ex) {
            log.error("rawStatusCode = {}",ex.getRawStatusCode());
            GreeResponseHelperOther greeResponseHelper = new GreeResponseHelperOther();
            greeResponseHelper.setStatusCode(ex.getRawStatusCode());
            greeResponseHelper.setMessage(ex.getMessage());
            ex.printStackTrace();
            return greeResponseHelper;
        }catch(Exception e){
            GreeResponseHelperOther greeResponseHelper = new GreeResponseHelperOther();
            greeResponseHelper.setStatusCode(ResponseHelper.ResponseCode_COMMON);
            greeResponseHelper.setMessage("非法请求");
            e.printStackTrace();
            return greeResponseHelper;
        }
    }


    /**
     * 请求总部接口
     * @return
     */
    public String greeGetT() throws Exception {
        return this.getAccessToken();
    }


}
