package com.malk.boyang;

import com.alibaba.fastjson.JSONObject;
import java.text.MessageFormat;
import java.util.LinkedHashMap;

import com.malk.boyang.utils.HTTPHelper;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;

public class Test {
    public static void main(String[] args) {
        // 应用ID
        String projectId = "1000004";
        // 应用密钥
        String secret = "96Uh7CR83NkN3TA6";
        // 接口调用域名
        String host = "http://122.227.225.202:9011/";

        // 请求签名鉴权-POST请求
        testPost(projectId, secret, host);

        // 请求签名鉴权-GET请求
//        testGet(projectId, secret, host);

        // 请求签名鉴权-POST请求-文件上传
//        testUpload(projectId, secret, host);
    }

    /***
     * 请求签名鉴权-POST请求
     *
     * @param projectId 项目Id
     * @param secret 项目密钥
     * @param host 网关地址
     */
    public static void testPost(String projectId, String secret, String host) {
        // 查询查询内部组织详情地址
        String getInnerOrganizationsDetailApi = "/manage/v1/innerOrganizations/detail";
        // 查询查询内部组织详情请求地址
        String getInnerOrganizationsDetailApiUrl = host + getInnerOrganizationsDetailApi;

        try {
            // 构建请求Body体
            JSONObject reqBodyObj = new JSONObject(true);
            reqBodyObj.put("organizationCode", "");
            reqBodyObj.put("customOrgNo", "");
            reqBodyObj.put("name", "博洋");

            // 请求Body体数据
            String reqBodyData = reqBodyObj.toString();
            // 对请求Body体内的数据计算ContentMD5

            // 构建参与请求签名计算的明文
            String plaintext = reqBodyData;
            // 计算请求签名值
            String reqSignature = sign(plaintext, secret);

            // 构建请求头
            LinkedHashMap<String, String> header = new LinkedHashMap<>();
            // 构建待签名字符串
            String accept = "*/*";
            String contentType = "application/json; charset=UTF-8";
            header.put("X-timevale-project-id", projectId);
            header.put("X-timevale-signature", reqSignature);
            header.put("Accept", accept);
            header.put("Content-Type", contentType);

            // 发送POST请求
            String result = HTTPHelper.sendPOST(getInnerOrganizationsDetailApiUrl, reqBodyData, header, "UTF-8");
            JSONObject resultObj = JSONObject.parseObject(result);
            System.out.println("请求返回信息： " + resultObj.toString());
        } catch (Exception e) {
            e.printStackTrace();
            String msg = MessageFormat.format("请求签名鉴权方式调用接口出现异常: {0}", e.getMessage());
            System.out.println(msg);
        }
    }

    /***
     * 请求签名鉴权-GET请求
     *
     * @param projectId 项目id
     * @param secret 项目密钥
     * @param host 网关地址
     */
    public static void testGet(String projectId, String secret, String host) {
        // 获取签署地址列表API地址
        String getSignFlowApi = "/esign-signs/v1/signFlow/signUrls?signFlowId=" + "24210df8420968c1e785a3b7582295b6";
        // 获取签署地址列表接口请求地址
        String hostGetSignFlowApi = host + getSignFlowApi;

        try {
            // 构建待签名字符串
            String accept = "*/*";
            String contentType = "application/json; charset=UTF-8";

            // 构建参与请求签名计算的明文
            int index = getSignFlowApi.indexOf("?");
            String plaintext = index == -1 ? "" : getSignFlowApi.substring(index + 1);
            // 计算请求签名值
            String reqSignature = sign(plaintext, secret);

            // 构建请求头
            LinkedHashMap<String, String> header = new LinkedHashMap<>();
            header.put("X-timevale-project-id", projectId);
            header.put("X-timevale-signature", reqSignature);
            header.put("Accept", accept);
            header.put("Content-Type", contentType);

            // 发送GET请求
            String result = HTTPHelper.sendGet(hostGetSignFlowApi, header, "UTF-8");
            JSONObject resultObj = JSONObject.parseObject(result);
            System.out.println("请求返回信息： " + resultObj.toString());
        } catch (Exception e) {
            e.printStackTrace();
            String msg = MessageFormat.format("请求签名鉴权方式调用接口出现异常: {0}", e.getMessage());
            System.out.println(msg);
        }
    }

    /**
     * hmac-sha256签名
     *
     * @param content 代签名的内容
     * @param key     签名的key
     * @return 签名
     */
    public static String sign(String content, String key) {
        byte[] bytes = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, key).hmac(content);
        return new String(Hex.encodeHex(bytes));
    }


    /***
     * 请求签名鉴权-POST请求
     *
     * @param projectId 项目Id
     * @param secret 项目密钥
     * @param host 网关地址
     */
    public static void testUpload(String projectId, String secret, String host) {
        // 文件上传接口
        String uploadApi = "/file/v1/pdf/uploadAndSpilt";
        // 文件上传接口请求地址
        String uploadApiUrl = host + uploadApi;

        try {
            // 构建请求Body体
            JSONObject reqBodyObj = new JSONObject(true);
            reqBodyObj.put("file", "测试文件密码123456.pdf");
            reqBodyObj.put("filePwd", "123456");

            // 请求Body体数据
            String reqBodyData = reqBodyObj.toString();

            // 构建参与请求签名计算的明文
            String plaintext = reqBodyData;
            // 计算请求签名值
            String reqSignature = sign(plaintext, secret);

            // 构建文件
            String filePath = "/xxx/xxx/测试文件密码123456.pdf";
            String fileFieldName = "file";

            // 构建请求头
            LinkedHashMap<String, String> header = new LinkedHashMap<>();
            // 构建待签名字符串
            String accept = "*/*";
            header.put("X-timevale-project-id", projectId);
            header.put("X-timevale-signature", reqSignature);
            header.put("Accept", accept);
            // 发送POST请求
            String result = HTTPHelper.uploadFile(uploadApiUrl,  fileFieldName, filePath, reqBodyObj,  header, "UTF-8");
            JSONObject resultObj = JSONObject.parseObject(result);
            System.out.println("请求返回信息： " + resultObj.toString());
        } catch (Exception e) {
            e.printStackTrace();
            String msg = MessageFormat.format("请求签名鉴权方式调用接口出现异常: {0}", e.getMessage());
            System.out.println(msg);
        }
    }
}