package com.jwipc.api.esign;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.io.Files;
import com.jwipc.api.constant.RestCode;
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 java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.SecureRandom;
import java.text.MessageFormat;
import java.util.LinkedHashMap;

/**
 * 功能描述:
 *
 * @Author: zx
 * @Date: 2024/4/10 0010 15:36
 */
@Slf4j
public class SignUtils {


    //下载文件
    public static String getFile(String fileKey, Pair<String, String> pair, String ServerIP, String api,
                                 String ProjectSecret1, String ProjectID1)
    {
        try {
            // 构建请求Body体
            api = api + "?fileKey=" + fileKey;
            String hostGetSignFlowApi = ServerIP + api;
            // 构建请求头
            String accept = "*/*";
            final String abDir = pair.getKey();
            String contentType = "application/json; charset=UTF-8";
            int index = api.indexOf("?");
            String plaintext = index == -1 ? "" : api.substring(index + 1);
            String reqSignature = sign256(plaintext, ProjectSecret1);

            LinkedHashMap<String, String> header = new LinkedHashMap<>();
            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.sendGet(hostGetSignFlowApi, header, "UTF-8");
            ;
            JSONObject resultObj = JSONObject.parseObject(result);
            if (resultObj.getString("code").equals(RestCode.MES_SUCCESS.getCode())) {
                //下载文件
                String pathName = dowloadFile(resultObj.getJSONObject("data").getString("url"), abDir);
                return pathName;
            }
            System.out.println("请求返回信息： " + resultObj.toString());
        } catch (Exception e) {
            e.printStackTrace();
            String msg = MessageFormat.format("请求签名鉴权方式调用接口出现异常: {0}", e.getMessage());
            System.out.println(msg);
        }
        return "";
    }


    public static String dowloadFile(String fileURL, String abDir) {
        final String fileSuffix = "pdf";
        final String fileName = StrUtil.concat(false, "sign-" + UUID.randomUUID().toString(), StrUtil.DOT, fileSuffix);
        final String abpath = abDir + File.separator + fileName;
        File savedFile = new File(abpath);
        try {
            Files.createParentDirs(savedFile);
            InputStream in = new URL(fileURL).openStream();
            FileOutputStream fos = new FileOutputStream(savedFile);
            byte[] dataBuffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                fos.write(dataBuffer, 0, bytesRead);
            }
            System.out.println("File downloaded");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return abpath;
    }


    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;
    }


}
