package com.bcxin.ins.third.gzzrx.pingancai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 调用openApi demo
 */
public class OpenApiPost {

    // 测试环境url前缀
    private static final String baseUrl = "https://test-api.pingan.com.cn:20443";
    // 生产环境url前缀
    //private static final String baseUrl = "https://api.pingan.com.cn";

    public static void main(String[] args) throws Exception {
        String tokenResult = OpenApiPost.getToken();
        JSONObject tokenJson = JSON.parseObject(tokenResult);
        String token;
        if ("0".equals(tokenJson.getString("ret"))) {
            token = tokenJson.getJSONObject("data").getString("access_token");
        } else {
            System.out.println("获取token出错，code:" + tokenJson.getString("ret") + ", message:" + tokenJson.getString("msg"));
            return;
        }
        // 此外替换成您要调用的url后缀
        String uri = "/interface/uploadFileOpenApi/fileUploadToken?access_token=" + token + "&request_id=fileUploadToken" + System.currentTimeMillis();
        String apiResult = OpenApiPost.post(baseUrl + "/open/appsvr/property" + uri, "");
        JSONObject apiJson = JSON.parseObject(apiResult);
        if ("0".equals(apiJson.getString("ret"))) {
            System.out.println("调用openApi成功，返回结果：" + apiJson.get("data"));
        } else if ("13012".equals(apiJson.getString("ret"))) { //token过期，重新获取token并再次调用一次openApi接口
            tokenResult = OpenApiPost.getToken();
            tokenJson = JSON.parseObject(tokenResult);
            if ("0".equals(tokenJson.getString("ret"))) {
                token = tokenJson.getJSONObject("data").getString("access_token");
                // 再次调用openApi
            } else {
                System.out.println("获取token出错，code:" + tokenJson.getString("ret") + ", message:" + tokenJson.getString("msg"));
                return;
            }
            System.out.println("调用openApi出错，code:" + apiJson.getString("ret") + ", message:" + apiJson.getString("msg"));
        } else {
            System.out.println("调用openApi出错，code:" + apiJson.getString("ret") + ", message:" + apiJson.getString("msg"));
        }
    }

    public static String post(String url, String postBody) throws Exception {
        String result;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000).setConnectionRequestTimeout(2000)
                // 报案接口超时时间建议设置为40秒
                .setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        // 构造消息头，这个参数很重要，如果去掉，则返回的数据不能被json工具解析
        httpPost.setHeader("Accept", "application/json;charset=utf-8");

        // 构建消息实体
        StringEntity entity = new StringEntity(postBody, Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        CloseableHttpResponse response = httpClient.execute(httpPost);
        result = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println("result:" + result);
        response.close();
        httpClient.close();
        return result;
    }

    /**
     * 获取应用token。建议将token缓存在本地，如redis、mongodb等，过期后再重新获取
     *
     * @return
     */
    public static String getToken() throws Exception {
        String clientId = "替换成您申请应用的client_id"; //应用clientId，开放平台-我的应用-CLIENT_ID
        // 如丢失应用密码，请在开放平台系统-我的应用-管理应用页面重置密码，审核通过后新密码将通过短信发送到注册账号手机
        String clientSecret = "替换成您申请应用的client_secret"; //应用密码，创建应用后系统生成。
        String tokenUrl = OpenApiPost.baseUrl + "/oauth/oauth2/access_token";
        Map<String, String> postMap = new HashMap<>();
        postMap.put("client_id", clientId);
        postMap.put("client_secret", clientSecret);
        postMap.put("grant_type", "client_credentials");
        String result = OpenApiPost.post(tokenUrl, JSON.toJSONString(postMap));
        return result;
    }

}
