package com.jwipc.contract.controller.pc;

import com.alibaba.fastjson2.JSONObject;
import com.jwipc.api.dto.SubjectDTO;
import com.jwipc.api.esign.HTTPHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.SecureRandom;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 功能描述:
 *
 * @Author: zx
 * @Date: 2024/4/10 0010 15:36
 */
@RestController
@RequestMapping("/api/sign/")
@RequiredArgsConstructor
@Slf4j
public class SignApiController {

    /**
     * 接口地址：http://eqbtest.jwipc.com:8199
     * 蓝凌接口项目id：1000000
     * 蓝凌接口项目密钥：JZkaKU4k9J7Z9L7N
     *
     * SRM接口项目ID：1000001
     * SRM接口项目密钥：86qiIW67N6F2rVMF
     */

    //天印服务器接口信息
    private static String ProjectID="1000000";
    private static String ProjectSecret="JZkaKU4k9J7Z9L7N";

    private static String ProjectID1="1000001";
    private static String ProjectSecret1="86qiIW67N6F2rVMF";

    private static String ServerIP="http://eqbtest.jwipc.com:8199";
    private static String Port="";

    /**
     * 1、签约组织：esigntest--Enterprise-YiChuan、
     *  签约人：张雨豪；
     * 2、乙方组织：杭州天谷信息科技有限公司、
     *  乙方签约人：张雨豪；
     * 3、印章ID：1778003745947381762，
     * esigntest--Enterprise-YiChuan组织的公章，
     * 用印人张雨豪
     * @param length32
     * @return
     */

    // 上传文件链接 接口
    public static String testPost1(String length32) {
        String getInnerOrganizationsDetailApi = "/file/v1/generateUploadUrl";
        String uploadApiUrl = ServerIP + getInnerOrganizationsDetailApi;

        try {
            // 构建请求Body体
            JSONObject reqBodyObj = new JSONObject();
            reqBodyObj.put("requestID", length32);
            reqBodyObj.put("type", "1");
            reqBodyObj.put("expire", "5");


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

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


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

            System.out.println("请求信息： " + reqBodyData);
            // 发送POST请求
            String result = HTTPHelper.sendPOST(uploadApiUrl, reqBodyData, header, "UTF-8");

            JSONObject resultObj = JSONObject.parseObject(result);
            System.out.println("请求返回信息： " + resultObj.toString());
            Integer code = resultObj.getIntValue("code");
            if(code ==200){
                String url = JSONObject.toJSONString(resultObj.getString("data"));
                return url ;
            }
        } catch (Exception e) {
            e.printStackTrace();
            String msg = MessageFormat.format("请求签名鉴权方式调用接口出现异常: {0}", e.getMessage());
            System.out.println(msg);
        }
        return null;
    }


    //文件直传
    public static void testPost() {

        String getInnerOrganizationsDetailApi = "/file/v1/upload";
        String uploadApiUrl = ServerIP + getInnerOrganizationsDetailApi;

        try {
            // 构建请求Body体
            JSONObject reqBodyObj = new JSONObject();
//            reqBodyObj.put("requestID", length32);
            reqBodyObj.put("file", "HT20211202-114558.pdf");
            reqBodyObj.put("hash", sign256("","HT20211202-114558"));

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

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

            String filePath = "D:\\po\\sign\\HT20211202-114558.pdf";
            String fileFieldName = "file";

            // 构建请求头
            LinkedHashMap<String, String> header = new LinkedHashMap<>();
            // 构建待签名字符串
            String accept = "*/*";
            header.put("X-timevale-project-id", ProjectID1);
            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);
        }
    }


    //一步发起签署
    public static void testPost3() {

        String getInnerOrganizationsDetailApi = "/esign-signs/v1/signFlow/createAndStart";
        String uploadApiUrl = ServerIP + getInnerOrganizationsDetailApi;

        try {
            // 构建请求Body体
            SubjectDTO subjectDTO = new SubjectDTO();
            subjectDTO.setSubject("test-E签宝签署");
            subjectDTO.setBusinessTypeCode("fb5c9f2c27e6cfd5ed5bd7514fa8b1a4");
            subjectDTO.setReadComplete(1);
            subjectDTO.setRemark("ceshi");
            subjectDTO.setSignNotifyUrl("");
            subjectDTO.setRedirectUrl("www.baidu.com");

            SubjectDTO.InitiatorInfo initiatorInfo = new SubjectDTO.InitiatorInfo();
            initiatorInfo.setUserCode("zhoux");
            initiatorInfo.setOrganizationCode("a8eaa73758c4476cb4065b49cb8c2480");
            subjectDTO.setInitiatorInfo(initiatorInfo);

            List<SubjectDTO.SignFiles> signFiles = new ArrayList<>();
            SubjectDTO.SignFiles signFile = new SubjectDTO.SignFiles();
            signFile.setFileKey("$f6e5891c-a067-4e41-9338-72350e21b24c$2222561460");
            signFiles.add(signFile);
            subjectDTO.setSignFiles(signFiles);


            SubjectDTO.ManualConfig manualConfig = new SubjectDTO.ManualConfig();
            manualConfig.setStartMode(0);
            manualConfig.setFinishMode(0);
            subjectDTO.setManualConfig(manualConfig);

            List<SubjectDTO.SignerInfos> signerInfos = new ArrayList<>();
            SubjectDTO.SignerInfos signerInfoJf = new SubjectDTO.SignerInfos();
            signerInfoJf.setUserType(1);
            signerInfoJf.setUserCode("zhoux");
            signerInfoJf.setOrganizationCode("a8eaa73758c4476cb4065b49cb8c2480");
            //指定印章类型
//            signerInfoJf.setSealTypeCode("PERSONNEL");
            signerInfoJf.setSignMode(0);
            signerInfoJf.setSignNode(1);
            signerInfoJf.setSignOrder(1);
            //签署任务信
            List<SubjectDTO.SealInfos> sealInfosJf = new ArrayList<>();
            SubjectDTO.SealInfos sealInfoJf = new SubjectDTO.SealInfos();

            sealInfoJf.setFileKey("$f6e5891c-a067-4e41-9338-72350e21b24c$2222561460");
            List<SubjectDTO.SignConfigs> signConfigsJf = new ArrayList<>();
            SubjectDTO.SignConfigs signConfigJf = new SubjectDTO.SignConfigs();
            signConfigJf.setSealId("1780482834373406721");
            //指定签署印章类型：PERSON-SEAL-个人印章、COMMON-SEAL-企业授权印章、LEGAL-PERSON-SEAL-法人章
            signConfigJf.setSignatureType("COMMON-SEAL");

            //设置关键字
            SubjectDTO.KeywordInfo keywordInfoJf = new SubjectDTO.KeywordInfo();
            keywordInfoJf.setKeywordIndex(-1);
            keywordInfoJf.setKeyword("甲方");
            signConfigJf.setKeywordInfo(keywordInfoJf);
            signConfigJf.setSignFieldType(0);
            signConfigJf.setAllowMove(0);
            signConfigJf.setSignType("KEYWORD-SIGN");
            sealInfoJf.setSignConfigs(signConfigsJf);
            signConfigsJf.add(signConfigJf);
            sealInfosJf.add(sealInfoJf);
            signerInfoJf.setSealInfos(sealInfosJf);
            signerInfos.add(signerInfoJf);



            SubjectDTO.SignerInfos signerInfoYf = new SubjectDTO.SignerInfos();
            signerInfoYf.setUserType(2);
            signerInfoYf.setUserCode("zhangyh");
            signerInfoYf.setOrganizationCode("971cb2d189034cda888b92298d78ecca");
            //指定印章类型
            signerInfoYf.setSealTypeCode("");
            signerInfoYf.setSignMode(0);
            signerInfoYf.setSignNode(2);
            signerInfoYf.setSignOrder(2);
//            签署任务信
            List<SubjectDTO.SealInfos> sealInfosYf = new ArrayList<>();
            SubjectDTO.SealInfos sealInfoYf = new SubjectDTO.SealInfos();

            sealInfoYf.setFileKey("$f6e5891c-a067-4e41-9338-72350e21b24c$2222561460");
            List<SubjectDTO.SignConfigs> signConfigsYf = new ArrayList<>();
            SubjectDTO.SignConfigs signConfigYf = new SubjectDTO.SignConfigs();
//            signConfigYf.setSealId("1778003745947381762");
            signConfigYf.setSignatureType("COMMON-SEAL");
            //设置关键字
            SubjectDTO.KeywordInfo keywordInfoYf = new SubjectDTO.KeywordInfo();
            keywordInfoYf.setKeywordIndex(-1);
            keywordInfoYf.setKeyword("乙方");
            signConfigYf.setKeywordInfo(keywordInfoYf);
            signConfigYf.setSignFieldType(0);
            signConfigYf.setAllowMove(0);
            signConfigYf.setSignType("KEYWORD-SIGN");
            sealInfoYf.setSignConfigs(signConfigsYf);
            signConfigsYf.add(signConfigYf);
            sealInfosYf.add(sealInfoYf);

            signerInfoYf.setSealInfos(sealInfosYf);

            signerInfos.add(signerInfoYf);
            subjectDTO.setSignerInfos(signerInfos);

            // 请求Body体数据
            String reqBodyData = JSONObject.toJSONString(subjectDTO);

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

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

            System.out.println("请求信息： " + reqBodyData);
            // 发送POST请求
            String result = HTTPHelper.sendPOST(uploadApiUrl, 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);
        }
    }


    //组织架构
    public static void testPost4() {
        String getInnerOrganizationsDetailApi = "/manage/v1/innerOrganizations/members/list";
        String uploadApiUrl = ServerIP + getInnerOrganizationsDetailApi;

        try {
            // 构建请求Body体
            JSONObject reqBodyObj = new JSONObject();
            reqBodyObj.put("organizationCode", "a8eaa73758c4476cb4065b49cb8c2480");
            reqBodyObj.put("queryScope", "0");
            reqBodyObj.put("pageNo", "1");
            reqBodyObj.put("pageSize", "20");

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

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

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

            // 发送POST请求
            String result = HTTPHelper.sendPOST(uploadApiUrl, 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);
        }
    }


    public static String sign256(String content, String key) {
        byte[] bytes = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, key).hmac(content);
        return new String(Hex.encodeHex(bytes));
    }

    public static String baseLength32() {
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        while (sb.length() < 32) {
            byte[] bytes = new byte[16]; // 生成16个字节，每个字节可以转换为2个16进制字符
            random.nextBytes(bytes);
            for (byte b : bytes) {
                sb.append(String.format("%02x", b)); // 将每个字节转换为2个16进制字符，并添加到StringBuilder中
            }
        }
        // 截取前32个字符，因为可能超过了32个字符
        String hexString = sb.toString().substring(0, 32);
        return hexString;
    }

    public static void main(String arge[]){
//        String length32 = baseLength32();
//        String url = testPost1(length32);
//        System.out.println(length32);
        // 文件上传
        //testPost();
//        testPost1(baseLength32());
//        testPost3();
//        testPost4();
        //文件 下载
//        testPost5();

//        testPost4();
    }


}
