package com.dxhy.common.utils;

import cn.hutool.core.codec.Base64;
import com.dxhy.common.util.Security;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @author user
 */
@Service("makeAppSecService")
@Slf4j

public class MakeAppSecService {

    public String makeAppSec(String secretId, String appid, String enterpriseCode, String taxperiod, String version,
        String data, String dataExchangeId, String aceKey) {
        String srcStr = "POST/rest/invoice/dii?authorize={\"appSecId\":\"" + secretId + "\"}&globalInfo={\"appId\":\""
            + appid + "\",\"version\":\"" + version + "\",\"interfaceCode\":\"" + taxperiod + "\",\"enterpriseCode\":\""
            + enterpriseCode + "\",\"dataExchangeId\":\"" + dataExchangeId + "\"}&" + "data=" + data + "";

        try {
            SecretKeySpec keySpec = new SecretKeySpec(aceKey.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(keySpec);
            byte[] singBytes = mac.doFinal(srcStr.getBytes(StandardCharsets.UTF_8));
            String appSec = Base64.encode(singBytes);
            log.info(taxperiod + "-接口生成的加密串=" + appSec + "-");
            return appSec;
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }
        return "";
    }

    public String getSign(String data, String key) {
        log.info("鉴权串：{} , 鉴权key:{}", data, key);
        try {
            String signature =
                Security.getSignature(data.getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8));
            log.info("鉴权加密结果：{}", signature);
            return signature;
        } catch (Exception e) {
           log.info("业务处理异常：{}", e);
        }
        return null;
    }

}
